1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/net/bit_stream_reader.h"
7 #include "base/big_endian.h"
8 #include "base/logging.h"
9 #include "base/numerics/safe_conversions.h"
13 BitStreamReader::BitStreamReader(const base::StringPiece
& source
)
14 : source_(source
), current_byte_(0), current_bit_(7) {
15 DCHECK_LT(source_
.length(), UINT32_MAX
);
18 bool BitStreamReader::ReadUnaryEncoding(uint64_t* out
) {
23 while ((BitsLeft() > 0) && ReadBit())
29 bool BitStreamReader::ReadBits(uint8_t num_bits
, uint64_t* out
) {
30 DCHECK_LE(num_bits
, 64);
32 if (BitsLeft() < num_bits
)
36 for (uint8_t i
= 0; i
< num_bits
; ++i
)
37 (*out
) |= (static_cast<uint64_t>(ReadBit()) << (num_bits
- (i
+ 1)));
42 uint64_t BitStreamReader::BitsLeft() const {
43 if (current_byte_
== source_
.length())
45 DCHECK_GT(source_
.length(), current_byte_
);
46 return (source_
.length() - (current_byte_
+ 1)) * 8 + current_bit_
+ 1;
49 uint8_t BitStreamReader::ReadBit() {
50 DCHECK_GT(BitsLeft(), 0u);
51 DCHECK(current_bit_
< 8 && current_bit_
>= 0);
53 (source_
.data()[current_byte_
] & (1 << current_bit_
)) >> current_bit_
;
55 if (current_bit_
< 0) {
63 } // namespace internal