Automated Commit: Committing new LKGM version 6953.0.0 for chromeos.
[chromium-blink-merge.git] / components / packed_ct_ev_whitelist / bit_stream_reader.cc
blobe4f6cc7b64a8896055bc56dd85f272d891b7f745
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 "components/packed_ct_ev_whitelist/bit_stream_reader.h"
7 #include "base/big_endian.h"
8 #include "base/logging.h"
9 #include "base/numerics/safe_conversions.h"
11 namespace packed_ct_ev_whitelist {
12 namespace internal {
14 BitStreamReader::BitStreamReader(const base::StringPiece& source)
15 : source_(source), current_byte_(0), current_bit_(7) {
16 DCHECK_LT(source_.length(), UINT32_MAX);
19 bool BitStreamReader::ReadUnaryEncoding(uint64_t* out) {
20 if (BitsLeft() == 0)
21 return false;
23 *out = 0;
24 while ((BitsLeft() > 0) && ReadBit())
25 ++(*out);
27 return true;
30 bool BitStreamReader::ReadBits(uint8_t num_bits, uint64_t* out) {
31 DCHECK_LE(num_bits, 64);
33 if (BitsLeft() < num_bits)
34 return false;
36 *out = 0;
37 for (uint8_t i = 0; i < num_bits; ++i)
38 (*out) |= (static_cast<uint64_t>(ReadBit()) << (num_bits - (i + 1)));
40 return true;
43 uint64_t BitStreamReader::BitsLeft() const {
44 if (current_byte_ == source_.length())
45 return 0;
46 DCHECK_GT(source_.length(), current_byte_);
47 return (source_.length() - (current_byte_ + 1)) * 8 + current_bit_ + 1;
50 uint8_t BitStreamReader::ReadBit() {
51 DCHECK_GT(BitsLeft(), 0u);
52 DCHECK(current_bit_ < 8 && current_bit_ >= 0);
53 uint8_t res =
54 (source_.data()[current_byte_] & (1 << current_bit_)) >> current_bit_;
55 current_bit_--;
56 if (current_bit_ < 0) {
57 current_byte_++;
58 current_bit_ = 7;
61 return res;
64 } // namespace internal
65 } // namespace packed_ct_ev_whitelist