Doug Horn | 1427b6a | 2018-12-11 13:19:16 -0800 | [diff] [blame] | 1 | // Copyright 2018 The Fuchsia 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 <lib/fidl/cpp/builder.h> |
| 6 | |
| 7 | #include <string.h> |
| 8 | |
| 9 | #include <lib/fidl/internal.h> |
| 10 | |
| 11 | namespace fidl { |
| 12 | |
| 13 | Builder::Builder() |
| 14 | : capacity_(0u), at_(0u), buffer_(nullptr) {} |
| 15 | |
| 16 | Builder::Builder(void* buffer, uint32_t capacity) |
| 17 | : capacity_(capacity), at_(0u), buffer_(static_cast<uint8_t*>(buffer)) { |
| 18 | } |
| 19 | |
| 20 | Builder::~Builder() = default; |
| 21 | |
| 22 | Builder::Builder(Builder&& other) |
| 23 | : capacity_(other.capacity_), |
| 24 | at_(other.at_), |
| 25 | buffer_(other.buffer_) { |
| 26 | other.Reset(nullptr, 0); |
| 27 | } |
| 28 | |
| 29 | Builder& Builder::operator=(Builder&& other) { |
| 30 | if (this != &other) { |
| 31 | capacity_ = other.capacity_; |
| 32 | at_ = other.at_; |
| 33 | buffer_ = other.buffer_; |
| 34 | other.Reset(nullptr, 0); |
| 35 | } |
| 36 | return *this; |
| 37 | } |
| 38 | |
| 39 | void* Builder::Allocate(uint32_t size) { |
| 40 | uint64_t limit = FidlAlign(at_ + size); |
| 41 | if (limit > capacity_) |
| 42 | return nullptr; |
| 43 | uint8_t* result = &buffer_[at_]; |
| 44 | memset(buffer_ + at_, 0, limit - at_); |
| 45 | at_ = static_cast<uint32_t>(limit); |
| 46 | return result; |
| 47 | } |
| 48 | |
| 49 | BytePart Builder::Finalize() { |
| 50 | BytePart bytes(buffer_, capacity_, at_); |
| 51 | capacity_ = 0u; |
| 52 | at_ = 0u; |
| 53 | return bytes; |
| 54 | } |
| 55 | |
| 56 | void Builder::Reset(void* buffer, uint32_t capacity) { |
| 57 | buffer_ = static_cast<uint8_t*>(buffer); |
| 58 | capacity_ = capacity; |
| 59 | at_ = 0u; |
| 60 | } |
| 61 | |
| 62 | } // namespace fidl |