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#include "mojo/public/cpp/bindings/lib/fixed_buffer.h"
6
7#include <stdlib.h>
8
9#include <algorithm>
10
11#include "mojo/public/cpp/bindings/lib/bindings_serialization.h"
12#include "mojo/public/cpp/environment/logging.h"
13
14namespace mojo {
15namespace internal {
16
17FixedBuffer::FixedBuffer(size_t size)
18    : ptr_(NULL),
19      cursor_(0),
20      size_(internal::Align(size)) {
21  // calloc() required to zero memory and thus avoid info leaks.
22  ptr_ = static_cast<char*>(calloc(size_, 1));
23}
24
25FixedBuffer::~FixedBuffer() {
26  free(ptr_);
27}
28
29void* FixedBuffer::Allocate(size_t delta) {
30  delta = internal::Align(delta);
31
32  if (delta == 0 || delta > size_ - cursor_) {
33    MOJO_DCHECK(false) << "Not reached";
34    return NULL;
35  }
36
37  char* result = ptr_ + cursor_;
38  cursor_ += delta;
39
40  return result;
41}
42
43void* FixedBuffer::Leak() {
44  char* ptr = ptr_;
45  ptr_ = NULL;
46  cursor_ = 0;
47  size_ = 0;
48  return ptr;
49}
50
51}  // namespace internal
52}  // namespace mojo
53