2 * Copyright © 2014 Canonical Ltd.
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License version 3 as
6 * published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Lesser General Public License for more details.
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 * Authored by: Alexandros Frantzis <alexandros.frantzis@canonical.com>
19 #ifndef ANBOX_COMMON_VARIABLE_LENGTH_ARRAY_H_
20 #define ANBOX_COMMON_VARIABLE_LENGTH_ARRAY_H_
22 #include <sys/types.h>
26 template <size_t BuiltInBufferSize>
27 class VariableLengthArray {
29 explicit VariableLengthArray(size_t size) : size_{size} {
30 /* Don't call resize if the initial values of member variables are valid */
31 if (size > BuiltInBufferSize) resize(size);
34 void resize(size_t size) {
35 if (size > BuiltInBufferSize)
36 effective_buffer = BufferUPtr{new unsigned char[size], heap_deleter};
38 effective_buffer = BufferUPtr{builtin_buffer, null_deleter};
43 unsigned char* data() const { return effective_buffer.get(); }
44 size_t size() const { return size_; }
47 typedef std::unique_ptr<unsigned char, void (*)(unsigned char*)> BufferUPtr;
49 static void null_deleter(unsigned char*) {}
50 static void heap_deleter(unsigned char* b) { delete[] b; }
52 unsigned char builtin_buffer[BuiltInBufferSize];
53 BufferUPtr effective_buffer{builtin_buffer, null_deleter};