Chromium Code Reviews| 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 | |
| 10 namespace internal { | |
| 11 | |
| 12 BitStreamReader::BitStreamReader(const base::StringPiece& source) | |
| 13 : source_(source), current_byte_(0), current_bit_(7) { | |
| 14 } | |
| 15 | |
| 16 bool BitStreamReader::ReadUnaryEncoding(uint64_t* out) { | |
| 17 uint64_t res = 0; | |
| 18 if (BitsLeft() == 0) | |
| 19 return false; | |
| 20 | |
| 21 while ((BitsLeft() > 0) && ReadBit()) | |
| 22 res++; | |
|
Ryan Sleevi
2014/10/20 19:18:24
Why keep the temporary?
You could change line 20
Eran Messeri
2014/10/21 14:59:59
Done.
| |
| 23 | |
| 24 *out = res; | |
| 25 return true; | |
| 26 } | |
| 27 | |
| 28 bool BitStreamReader::ReadBits(uint8_t num_bits, uint64_t* out) { | |
| 29 if (num_bits > 64) | |
| 30 return false; | |
|
Ryan Sleevi
2014/10/20 19:18:24
API: Your API contract says they shouldn't call wi
Eran Messeri
2014/10/21 14:59:59
Done. In practice I always read a fixed amount so
| |
| 31 | |
| 32 if (BitsLeft() < num_bits) | |
| 33 return false; | |
| 34 | |
| 35 uint64_t res = 0; | |
| 36 for (uint8_t i = 0; i < num_bits; ++i) | |
| 37 res |= (static_cast<uint64_t>(ReadBit()) << (num_bits - (i + 1))); | |
| 38 | |
| 39 *out = res; | |
|
Ryan Sleevi
2014/10/20 19:18:24
ditto the temporary again
Eran Messeri
2014/10/21 14:59:59
Done.
| |
| 40 return true; | |
| 41 } | |
| 42 | |
| 43 uint64_t BitStreamReader::BitsLeft() const { | |
| 44 if (current_byte_ == source_.length()) | |
| 45 return 0; | |
| 46 return (source_.length() - (current_byte_ + 1)) * 8 + current_bit_ + 1; | |
|
Ryan Sleevi
2014/10/20 19:18:24
BUG: integer overflow issues here. Should you use
Eran Messeri
2014/10/21 14:59:59
Added a DCHECK that source_.length() is greater th
| |
| 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 |