Home | History | Annotate | Download | only in lib
      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 <stddef.h>
      8 #include <stdlib.h>
      9 
     10 #include <algorithm>
     11 
     12 #include "base/logging.h"
     13 #include "mojo/public/cpp/bindings/lib/serialization_util.h"
     14 
     15 namespace mojo {
     16 namespace internal {
     17 
     18 FixedBuffer::FixedBuffer() : ptr_(nullptr), cursor_(0), size_(0) {}
     19 
     20 void FixedBuffer::Initialize(void* memory, size_t size) {
     21   DCHECK(size == internal::Align(size));
     22 
     23   ptr_ = static_cast<char*>(memory);
     24   cursor_ = 0;
     25   size_ = size;
     26 }
     27 
     28 void* FixedBuffer::Allocate(size_t delta) {
     29   delta = internal::Align(delta);
     30 
     31   if (delta == 0 || delta > size_ - cursor_) {
     32     NOTREACHED();
     33     return nullptr;
     34   }
     35 
     36   char* result = ptr_ + cursor_;
     37   cursor_ += delta;
     38 
     39   return result;
     40 }
     41 
     42 FixedBufferForTesting::FixedBufferForTesting(size_t size) {
     43   size_ = internal::Align(size);
     44   // Use calloc here to ensure all message memory is zero'd out.
     45   ptr_ = static_cast<char*>(calloc(size_, 1));
     46 }
     47 
     48 FixedBufferForTesting::~FixedBufferForTesting() {
     49   free(ptr_);
     50 }
     51 
     52 void* FixedBufferForTesting::Leak() {
     53   char* ptr = ptr_;
     54   ptr_ = nullptr;
     55   cursor_ = 0;
     56   size_ = 0;
     57   return ptr;
     58 }
     59 
     60 }  // namespace internal
     61 }  // namespace mojo
     62