TYPE3
[iec.git] / src / type3_AndroidCloud / anbox-master / src / anbox / common / variable_length_array.h
1 /*
2  * Copyright © 2014 Canonical Ltd.
3  *
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.
7  *
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.
12  *
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/>.
15  *
16  * Authored by: Alexandros Frantzis <alexandros.frantzis@canonical.com>
17  */
18
19 #ifndef ANBOX_COMMON_VARIABLE_LENGTH_ARRAY_H_
20 #define ANBOX_COMMON_VARIABLE_LENGTH_ARRAY_H_
21
22 #include <sys/types.h>
23 #include <memory>
24
25 namespace anbox {
26 template <size_t BuiltInBufferSize>
27 class VariableLengthArray {
28  public:
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);
32   }
33
34   void resize(size_t size) {
35     if (size > BuiltInBufferSize)
36       effective_buffer = BufferUPtr{new unsigned char[size], heap_deleter};
37     else
38       effective_buffer = BufferUPtr{builtin_buffer, null_deleter};
39
40     size_ = size;
41   }
42
43   unsigned char* data() const { return effective_buffer.get(); }
44   size_t size() const { return size_; }
45
46  private:
47   typedef std::unique_ptr<unsigned char, void (*)(unsigned char*)> BufferUPtr;
48
49   static void null_deleter(unsigned char*) {}
50   static void heap_deleter(unsigned char* b) { delete[] b; }
51
52   unsigned char builtin_buffer[BuiltInBufferSize];
53   BufferUPtr effective_buffer{builtin_buffer, null_deleter};
54   size_t size_;
55 };
56 }  // namespace anbox
57
58 #endif