bit_writer.cc (1467B)
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 #include "logging/rtc_event_log/encoder/bit_writer.h" 12 13 #include <climits> 14 #include <cstddef> 15 #include <cstdint> 16 #include <string> 17 #include <utility> 18 19 #include "absl/strings/string_view.h" 20 #include "rtc_base/checks.h" 21 22 namespace webrtc { 23 24 namespace { 25 size_t BitsToBytes(size_t bits) { 26 return (bits / 8) + (bits % 8 > 0 ? 1 : 0); 27 } 28 } // namespace 29 30 void BitWriter::WriteBits(uint64_t val, size_t bit_count) { 31 RTC_DCHECK(valid_); 32 const bool success = bit_writer_.WriteBits(val, bit_count); 33 RTC_DCHECK(success); 34 written_bits_ += bit_count; 35 } 36 37 void BitWriter::WriteBits(absl::string_view input) { 38 RTC_DCHECK(valid_); 39 for (char c : input) { 40 WriteBits(static_cast<unsigned char>(c), CHAR_BIT); 41 } 42 } 43 44 // Returns everything that was written so far. 45 // Nothing more may be written after this is called. 46 std::string BitWriter::GetString() { 47 RTC_DCHECK(valid_); 48 valid_ = false; 49 50 buffer_.resize(BitsToBytes(written_bits_)); 51 written_bits_ = 0; 52 53 std::string result; 54 std::swap(buffer_, result); 55 return result; 56 } 57 58 } // namespace webrtc