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 #include <utility> 19 20 #include "absl/strings/string_view.h" 21 #include "rtc_base/bit_buffer.h" 22 #include "rtc_base/checks.h" 23 24 namespace webrtc { 25 26 // Wrap BitBufferWriter and extend its functionality by (1) keeping track of 27 // the number of bits written and (2) owning its buffer. 28 class BitWriter final { 29 public: BitWriter(size_t byte_count)30 explicit BitWriter(size_t byte_count) 31 : buffer_(byte_count, '\0'), 32 bit_writer_(reinterpret_cast<uint8_t*>(&buffer_[0]), buffer_.size()), 33 written_bits_(0), 34 valid_(true) { 35 RTC_DCHECK_GT(byte_count, 0); 36 } 37 38 BitWriter(const BitWriter&) = delete; 39 BitWriter& operator=(const BitWriter&) = delete; 40 41 void WriteBits(uint64_t val, size_t bit_count); 42 43 void WriteBits(absl::string_view input); 44 45 // Returns everything that was written so far. 46 // Nothing more may be written after this is called. 47 std::string GetString(); 48 49 private: 50 std::string buffer_; 51 rtc::BitBufferWriter bit_writer_; 52 // Note: Counting bits instead of bytes wraps around earlier than it has to, 53 // which means the maximum length is lower than it could be. We don't expect 54 // to go anywhere near the limit, though, so this is good enough. 55 size_t written_bits_; 56 bool valid_; 57 }; 58 59 } // namespace webrtc 60 61 #endif // LOGGING_RTC_EVENT_LOG_ENCODER_BIT_WRITER_H_ 62