1// Copyright 2014 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_FIXED_BUFFER_H_
6#define MOJO_PUBLIC_CPP_BINDINGS_LIB_FIXED_BUFFER_H_
7
8#include <stddef.h>
9
10#include "base/macros.h"
11#include "mojo/public/cpp/bindings/lib/buffer.h"
12
13namespace mojo {
14namespace internal {
15
16// FixedBuffer provides a simple way to allocate objects within a fixed chunk
17// of memory. Objects are allocated by calling the |Allocate| method, which
18// extends the buffer accordingly. Objects allocated in this way are not freed
19// explicitly. Instead, they remain valid so long as the FixedBuffer remains
20// valid.  The Leak method may be used to steal the underlying memory from the
21// FixedBuffer.
22//
23// Typical usage:
24//
25//   {
26//     FixedBuffer buf(8 + 8);
27//
28//     int* a = static_cast<int*>(buf->Allocate(sizeof(int)));
29//     *a = 2;
30//
31//     double* b = static_cast<double*>(buf->Allocate(sizeof(double)));
32//     *b = 3.14f;
33//
34//     void* data = buf.Leak();
35//     Process(data);
36//
37//     free(data);
38//   }
39
40class FixedBuffer : public Buffer {
41 public:
42  FixedBuffer();
43
44  // |size| should be aligned using internal::Align.
45  void Initialize(void* memory, size_t size);
46
47  size_t size() const { return size_; }
48
49  // Grows the buffer by |num_bytes| and returns a pointer to the start of the
50  // addition. The resulting address is 8-byte aligned, and the content of the
51  // memory is zero-filled.
52  void* Allocate(size_t num_bytes) override;
53
54 protected:
55  char* ptr_;
56  size_t cursor_;
57  size_t size_;
58
59  DISALLOW_COPY_AND_ASSIGN(FixedBuffer);
60};
61
62class FixedBufferForTesting : public FixedBuffer {
63 public:
64  explicit FixedBufferForTesting(size_t size);
65  ~FixedBufferForTesting() override;
66
67  // Returns the internal memory owned by the Buffer to the caller. The Buffer
68  // relinquishes its pointer, effectively resetting the state of the Buffer
69  // and leaving the caller responsible for freeing the returned memory address
70  // when no longer needed.
71  void* Leak();
72
73 private:
74  DISALLOW_COPY_AND_ASSIGN(FixedBufferForTesting);
75};
76
77}  // namespace internal
78}  // namespace mojo
79
80#endif  // MOJO_PUBLIC_CPP_BINDINGS_LIB_FIXED_BUFFER_H_
81