OLD | NEW |
| (Empty) |
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. | |
4 | |
5 #include "chrome/browser/net/bit_stream_reader.h" | |
6 | |
7 #include "base/big_endian.h" | |
8 #include "base/logging.h" | |
9 #include "base/numerics/safe_conversions.h" | |
10 | |
11 namespace internal { | |
12 | |
13 BitStreamReader::BitStreamReader(const base::StringPiece& source) | |
14 : source_(source), current_byte_(0), current_bit_(7) { | |
15 DCHECK_LT(source_.length(), UINT32_MAX); | |
16 } | |
17 | |
18 bool BitStreamReader::ReadUnaryEncoding(uint64_t* out) { | |
19 if (BitsLeft() == 0) | |
20 return false; | |
21 | |
22 *out = 0; | |
23 while ((BitsLeft() > 0) && ReadBit()) | |
24 ++(*out); | |
25 | |
26 return true; | |
27 } | |
28 | |
29 bool BitStreamReader::ReadBits(uint8_t num_bits, uint64_t* out) { | |
30 DCHECK_LE(num_bits, 64); | |
31 | |
32 if (BitsLeft() < num_bits) | |
33 return false; | |
34 | |
35 *out = 0; | |
36 for (uint8_t i = 0; i < num_bits; ++i) | |
37 (*out) |= (static_cast<uint64_t>(ReadBit()) << (num_bits - (i + 1))); | |
38 | |
39 return true; | |
40 } | |
41 | |
42 uint64_t BitStreamReader::BitsLeft() const { | |
43 if (current_byte_ == source_.length()) | |
44 return 0; | |
45 DCHECK_GT(source_.length(), current_byte_); | |
46 return (source_.length() - (current_byte_ + 1)) * 8 + current_bit_ + 1; | |
47 } | |
48 | |
49 uint8_t BitStreamReader::ReadBit() { | |
50 DCHECK_GT(BitsLeft(), 0u); | |
51 DCHECK(current_bit_ < 8 && current_bit_ >= 0); | |
52 uint8_t res = | |
53 (source_.data()[current_byte_] & (1 << current_bit_)) >> current_bit_; | |
54 current_bit_--; | |
55 if (current_bit_ < 0) { | |
56 current_byte_++; | |
57 current_bit_ = 7; | |
58 } | |
59 | |
60 return res; | |
61 } | |
62 | |
63 } // namespace internal | |
OLD | NEW |