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
Builder()13 Builder::Builder()
14 : capacity_(0u), at_(0u), buffer_(nullptr) {}
15
Builder(void * buffer,uint32_t capacity)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
Builder(Builder && other)22 Builder::Builder(Builder&& other)
23 : capacity_(other.capacity_),
24 at_(other.at_),
25 buffer_(other.buffer_) {
26 other.Reset(nullptr, 0);
27 }
28
operator =(Builder && other)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
Allocate(uint32_t size)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
Finalize()49 BytePart Builder::Finalize() {
50 BytePart bytes(buffer_, capacity_, at_);
51 capacity_ = 0u;
52 at_ = 0u;
53 return bytes;
54 }
55
Reset(void * buffer,uint32_t capacity)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
63