aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/containers/stack_array/stack_array.h
diff options
context:
space:
mode:
authorDevtools Arcadia <arcadia-devtools@yandex-team.ru>2022-02-07 18:08:42 +0300
committerDevtools Arcadia <arcadia-devtools@mous.vla.yp-c.yandex.net>2022-02-07 18:08:42 +0300
commit1110808a9d39d4b808aef724c861a2e1a38d2a69 (patch)
treee26c9fed0de5d9873cce7e00bc214573dc2195b7 /library/cpp/containers/stack_array/stack_array.h
downloadydb-1110808a9d39d4b808aef724c861a2e1a38d2a69.tar.gz
intermediate changes
ref:cde9a383711a11544ce7e107a78147fb96cc4029
Diffstat (limited to 'library/cpp/containers/stack_array/stack_array.h')
-rw-r--r--library/cpp/containers/stack_array/stack_array.h40
1 files changed, 40 insertions, 0 deletions
diff --git a/library/cpp/containers/stack_array/stack_array.h b/library/cpp/containers/stack_array/stack_array.h
new file mode 100644
index 0000000000..28e49bfc3c
--- /dev/null
+++ b/library/cpp/containers/stack_array/stack_array.h
@@ -0,0 +1,40 @@
+#pragma once
+
+#include "range_ops.h"
+
+#include <util/generic/array_ref.h>
+#include <util/system/defaults.h> /* For alloca. */
+
+namespace NStackArray {
+ /**
+ * A stack-allocated array. Should be used instead of � variable length
+ * arrays that are not part of C++ standard.
+ *
+ * Example usage:
+ * @code
+ * void f(int size) {
+ * // T array[size]; // Wrong!
+ * TStackArray<T> array(ALLOC_ON_STACK(T, size)); // Right!
+ * // ...
+ * }
+ * @endcode
+ *
+ * Note that it is generally a *VERY BAD* idea to use this in inline methods
+ * as those might be called from a loop, and then stack overflow is in the cards.
+ */
+ template <class T>
+ class TStackArray: public TArrayRef<T> {
+ public:
+ inline TStackArray(void* data, size_t len)
+ : TArrayRef<T>((T*)data, len)
+ {
+ NRangeOps::InitializeRange(this->begin(), this->end());
+ }
+
+ inline ~TStackArray() {
+ NRangeOps::DestroyRange(this->begin(), this->end());
+ }
+ };
+}
+
+#define ALLOC_ON_STACK(type, n) alloca(sizeof(type) * (n)), (n)