blob: 1d79b6d60a761c9d5b7a7d18b59439e582d44843 [file] [log] [blame]
mukesh agrawal3d8db082016-09-30 18:47:12 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef BYTE_BUFFER_H_
18#define BYTE_BUFFER_H_
19
20#include <array>
21#include <cstring>
22
23#include "android-base/logging.h"
24
25#include "wifilogd/local_utils.h"
26
27namespace android {
28namespace wifilogd {
29
30// A fixed-size buffer, which provides the ability to accumulate bytes.
31// The buffer tracks its (populated) size, and does not require dynamic
32// memory allocation.
33//
mukesh agrawal937164d2016-10-20 15:35:26 -070034// Usage could be as follows:
xshu31aa7aa2017-09-29 14:05:32 -070035// const auto buffer = ByteBuffer<1024>()
mukesh agrawal937164d2016-10-20 15:35:26 -070036// .AppendOrDie(header.data(), header.size())
37// .AppendOrDie(body.data(), body.size());
mukesh agrawal3d8db082016-09-30 18:47:12 -070038// write(fd, buffer.data(), buffer.size());
39template <size_t SizeBytes>
40class ByteBuffer {
41 public:
42 ByteBuffer() : write_pos_(0) {}
43
44 // Appends data to the end of this buffer. Aborts if the available
mukesh agrawal937164d2016-10-20 15:35:26 -070045 // space in the buffer is less than |data_len|. Returns a reference to
46 // the ByteBuffer, to support chaining.
47 ByteBuffer<SizeBytes>& AppendOrDie(NONNULL const void* data,
48 size_t data_len) {
mukesh agrawal3d8db082016-09-30 18:47:12 -070049 CHECK(data_len <= raw_buffer_.size() - write_pos_);
50 std::memcpy(raw_buffer_.data() + write_pos_, data, data_len);
51 write_pos_ += data_len;
mukesh agrawal937164d2016-10-20 15:35:26 -070052 return *this;
mukesh agrawal3d8db082016-09-30 18:47:12 -070053 }
54
55 // Returns a pointer to the head of this buffer.
56 RETURNS_NONNULL const uint8_t* data() const { return raw_buffer_.data(); }
57
58 // Returns the number of bytes written to this buffer.
59 size_t size() const { return write_pos_; }
60
61 private:
62 std::array<uint8_t, SizeBytes> raw_buffer_;
63 size_t write_pos_;
64};
65
66} // namespace wifilogd
67} // namespace android
68#endif // BYTE_BUFFER_H_