Home | History | Annotate | Download | only in wifilogd
      1 /*
      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 
     27 namespace android {
     28 namespace 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 //
     34 // Usage could be as follows:
     35 //     const auto buffer = ByteBuffer<1024>()
     36 //         .AppendOrDie(header.data(), header.size())
     37 //         .AppendOrDie(body.data(), body.size());
     38 //     write(fd, buffer.data(), buffer.size());
     39 template <size_t SizeBytes>
     40 class ByteBuffer {
     41  public:
     42   ByteBuffer() : write_pos_(0) {}
     43 
     44   // Appends data to the end of this buffer. Aborts if the available
     45   // 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) {
     49     CHECK(data_len <= raw_buffer_.size() - write_pos_);
     50     std::memcpy(raw_buffer_.data() + write_pos_, data, data_len);
     51     write_pos_ += data_len;
     52     return *this;
     53   }
     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_
     69