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 3 // found in the LICENSE file. 4 5 #ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_BUFFER_H_ 6 #define MOJO_PUBLIC_CPP_BINDINGS_LIB_BUFFER_H_ 7 8 #include <stddef.h> 9 10 #include "base/logging.h" 11 #include "base/macros.h" 12 #include "mojo/public/cpp/bindings/lib/bindings_internal.h" 13 14 namespace mojo { 15 namespace internal { 16 17 // Buffer provides an interface to allocate memory blocks which are 8-byte 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. 21 class Buffer { 22 public: Buffer()23 Buffer() {} 24 25 // The memory must have been zero-initialized. |data| must be 8-byte 26 // aligned. Initialize(void * data,size_t size)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 size()36 size_t size() const { return size_; } 37 data()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. Allocate(size_t num_bytes)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); 65 }; 66 67 } // namespace internal 68 } // namespace mojo 69 70 #endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_BUFFER_H_ 71