bit_writer.h (1839B)
1 /* 2 * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved. 3 * 4 * Use of this source code is governed by a BSD-style license 5 * that can be found in the LICENSE file in the root of the source 6 * tree. An additional intellectual property rights grant can be found 7 * in the file PATENTS. All contributing project authors may 8 * be found in the AUTHORS file in the root of the source tree. 9 */ 10 11 #ifndef LOGGING_RTC_EVENT_LOG_ENCODER_BIT_WRITER_H_ 12 #define LOGGING_RTC_EVENT_LOG_ENCODER_BIT_WRITER_H_ 13 14 #include <stddef.h> 15 #include <stdint.h> 16 17 #include <string> 18 19 #include "absl/strings/string_view.h" 20 #include "rtc_base/bit_buffer.h" 21 #include "rtc_base/checks.h" 22 23 namespace webrtc { 24 25 // Wrap BitBufferWriter and extend its functionality by (1) keeping track of 26 // the number of bits written and (2) owning its buffer. 27 class BitWriter final { 28 public: 29 explicit BitWriter(size_t byte_count) 30 : buffer_(byte_count, '\0'), 31 bit_writer_(reinterpret_cast<uint8_t*>(&buffer_[0]), buffer_.size()), 32 written_bits_(0), 33 valid_(true) { 34 RTC_DCHECK_GT(byte_count, 0); 35 } 36 37 BitWriter(const BitWriter&) = delete; 38 BitWriter& operator=(const BitWriter&) = delete; 39 40 void WriteBits(uint64_t val, size_t bit_count); 41 42 void WriteBits(absl::string_view input); 43 44 // Returns everything that was written so far. 45 // Nothing more may be written after this is called. 46 std::string GetString(); 47 48 private: 49 std::string buffer_; 50 BitBufferWriter bit_writer_; 51 // Note: Counting bits instead of bytes wraps around earlier than it has to, 52 // which means the maximum length is lower than it could be. We don't expect 53 // to go anywhere near the limit, though, so this is good enough. 54 size_t written_bits_; 55 bool valid_; 56 }; 57 58 } // namespace webrtc 59 60 #endif // LOGGING_RTC_EVENT_LOG_ENCODER_BIT_WRITER_H_