Mir
variable_length_array.h
Go to the documentation of this file.
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 MIR_VARIABLE_LENGTH_ARRAY_H_
20 #define MIR_VARIABLE_LENGTH_ARRAY_H_
21 
22 #include <sys/types.h>
23 #include <memory>
24 
25 namespace mir
26 {
27 
28 template <size_t BuiltInBufferSize>
30 {
31 public:
32  explicit VariableLengthArray(size_t size) : size_{size}
33  {
34  /* Don't call resize if the initial values of member variables are valid */
35  if (size > BuiltInBufferSize) resize(size);
36  }
37 
38  void resize(size_t size)
39  {
40  if (size > BuiltInBufferSize)
41  effective_buffer = BufferUPtr{new unsigned char[size], heap_deleter};
42  else
43  effective_buffer = BufferUPtr{builtin_buffer, null_deleter};
44 
45  size_ = size;
46  }
47 
48  unsigned char* data() const { return effective_buffer.get(); }
49  size_t size() const { return size_; }
50 
51 private:
52  typedef std::unique_ptr<unsigned char,void (*)(unsigned char*)> BufferUPtr;
53 
54  static void null_deleter(unsigned char*) {}
55  static void heap_deleter(unsigned char* b) { delete[] b; }
56 
57  unsigned char builtin_buffer[BuiltInBufferSize];
58  BufferUPtr effective_buffer{builtin_buffer, null_deleter};
59  size_t size_;
60 };
61 
62 }
63 
64 #endif /* MIR_VARIABLE_LENGTH_ARRAY_H_ */
All things Mir.
Definition: atomic_callback.h:25
size_t size() const
Definition: variable_length_array.h:49
VariableLengthArray(size_t size)
Definition: variable_length_array.h:32
unsigned char * data() const
Definition: variable_length_array.h:48
Definition: variable_length_array.h:29
void resize(size_t size)
Definition: variable_length_array.h:38

Copyright © 2012-2015 Canonical Ltd.
Generated on Thu Sep 8 14:50:19 UTC 2016