OLD | NEW |
1 // Copyright 2013 The Chromium Authors. All rights reserved. | 1 // Copyright 2013 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_BUFFER_H_ | 5 #ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_BUFFER_H_ |
6 #define MOJO_PUBLIC_CPP_BINDINGS_LIB_BUFFER_H_ | 6 #define MOJO_PUBLIC_CPP_BINDINGS_LIB_BUFFER_H_ |
7 | 7 |
8 #include <stddef.h> | 8 #include <stddef.h> |
9 | 9 |
| 10 #include "base/logging.h" |
| 11 #include "base/macros.h" |
| 12 #include "mojo/public/cpp/bindings/lib/bindings_internal.h" |
| 13 |
10 namespace mojo { | 14 namespace mojo { |
11 namespace internal { | 15 namespace internal { |
12 | 16 |
13 // Buffer provides a way to allocate memory. Allocations are 8-byte aligned and | 17 // Buffer provides an interface to allocate memory blocks which are 8-byte |
14 // zero-initialized. Allocations remain valid for the lifetime of the Buffer. | 18 // aligned and zero-initialized. It doesn't own the underlying memory. Users |
| 19 // must ensure that the memory stays valid while using the allocated blocks from |
| 20 // Buffer. |
15 class Buffer { | 21 class Buffer { |
16 public: | 22 public: |
17 virtual ~Buffer() {} | 23 Buffer() {} |
18 virtual void* Allocate(size_t num_bytes) = 0; | 24 |
| 25 // The memory must have been zero-initialized. |data| must be 8-byte |
| 26 // aligned. |
| 27 void Initialize(void* data, size_t size) { |
| 28 DCHECK(IsAligned(data)); |
| 29 |
| 30 data_ = data; |
| 31 size_ = size; |
| 32 cursor_ = reinterpret_cast<uintptr_t>(data); |
| 33 data_end_ = cursor_ + size; |
| 34 } |
| 35 |
| 36 size_t size() const { return size_; } |
| 37 |
| 38 void* data() const { return data_; } |
| 39 |
| 40 // Allocates |num_bytes| from the buffer and returns a pointer to the start of |
| 41 // the allocated block. |
| 42 // The resulting address is 8-byte aligned, and the content of the memory is |
| 43 // zero-filled. |
| 44 void* Allocate(size_t num_bytes) { |
| 45 num_bytes = Align(num_bytes); |
| 46 uintptr_t result = cursor_; |
| 47 cursor_ += num_bytes; |
| 48 if (cursor_ > data_end_ || cursor_ < result) { |
| 49 NOTREACHED(); |
| 50 cursor_ -= num_bytes; |
| 51 return nullptr; |
| 52 } |
| 53 |
| 54 return reinterpret_cast<void*>(result); |
| 55 } |
| 56 |
| 57 private: |
| 58 void* data_ = nullptr; |
| 59 size_t size_ = 0; |
| 60 |
| 61 uintptr_t cursor_ = 0; |
| 62 uintptr_t data_end_ = 0; |
| 63 |
| 64 DISALLOW_COPY_AND_ASSIGN(Buffer); |
19 }; | 65 }; |
20 | 66 |
21 } // namespace internal | 67 } // namespace internal |
22 } // namespace mojo | 68 } // namespace mojo |
23 | 69 |
24 #endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_BUFFER_H_ | 70 #endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_BUFFER_H_ |
OLD | NEW |