[ExtensionToolbarMac] Restrict action button drags to the container's bounds
[chromium-blink-merge.git] / chrome / browser / net / bit_stream_reader.cc
blob9e9f0aaf8d2eccc144be12f8eafa04acbf04d7d6
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"
11 namespace internal {
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) {
19 if (BitsLeft() == 0)
20 return false;
22 *out = 0;
23 while ((BitsLeft() > 0) && ReadBit())
24 ++(*out);
26 return true;
29 bool BitStreamReader::ReadBits(uint8_t num_bits, uint64_t* out) {
30 DCHECK_LE(num_bits, 64);
32 if (BitsLeft() < num_bits)
33 return false;
35 *out = 0;
36 for (uint8_t i = 0; i < num_bits; ++i)
37 (*out) |= (static_cast<uint64_t>(ReadBit()) << (num_bits - (i + 1)));
39 return true;
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;
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;
60 return res;
63 } // namespace internal