bit_reader.cc 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2017 The Chromium OS 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. #include "puffin/src/bit_reader.h"
  5. #include "puffin/src/logging.h"
  6. namespace puffin {
  7. bool BufferBitReader::CacheBits(size_t nbits) {
  8. if ((in_size_ - index_) * 8 + in_cache_bits_ < nbits) {
  9. return false;
  10. }
  11. if (nbits > sizeof(in_cache_) * 8) {
  12. return false;
  13. }
  14. while (in_cache_bits_ < nbits) {
  15. in_cache_ |= in_buf_[index_++] << in_cache_bits_;
  16. in_cache_bits_ += 8;
  17. }
  18. return true;
  19. }
  20. uint32_t BufferBitReader::ReadBits(size_t nbits) {
  21. return in_cache_ & ((1U << nbits) - 1);
  22. }
  23. void BufferBitReader::DropBits(size_t nbits) {
  24. in_cache_ >>= nbits;
  25. in_cache_bits_ -= nbits;
  26. }
  27. uint8_t BufferBitReader::ReadBoundaryBits() {
  28. return in_cache_ & ((1 << (in_cache_bits_ & 7)) - 1);
  29. }
  30. size_t BufferBitReader::SkipBoundaryBits() {
  31. size_t nbits = in_cache_bits_ & 7;
  32. in_cache_ >>= nbits;
  33. in_cache_bits_ -= nbits;
  34. return nbits;
  35. }
  36. bool BufferBitReader::GetByteReaderFn(
  37. size_t length, std::function<bool(uint8_t*, size_t)>* read_fn) {
  38. index_ -= (in_cache_bits_ + 7) / 8;
  39. in_cache_ = 0;
  40. in_cache_bits_ = 0;
  41. TEST_AND_RETURN_FALSE(length <= in_size_ - index_);
  42. *read_fn = [this, length](uint8_t* buffer, size_t count) mutable {
  43. TEST_AND_RETURN_FALSE(count <= length);
  44. if (buffer != nullptr) {
  45. memcpy(buffer, &in_buf_[index_], count);
  46. }
  47. index_ += count;
  48. length -= count;
  49. return true;
  50. };
  51. return true;
  52. }
  53. size_t BufferBitReader::Offset() const {
  54. return index_ - in_cache_bits_ / 8;
  55. }
  56. uint64_t BufferBitReader::OffsetInBits() const {
  57. return (index_ * 8) - in_cache_bits_;
  58. }
  59. uint64_t BufferBitReader::BitsRemaining() const {
  60. return ((in_size_ - index_) * 8) + in_cache_bits_;
  61. }
  62. } // namespace puffin