summaryrefslogtreecommitdiff
path: root/core/fxcrt/cfx_bitstream.cpp
blob: 3d3040d96abcaf73c6099e05904fccc0bb0b4844 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright 2017 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#include "core/fxcrt/cfx_bitstream.h"

#include <limits>

#include "core/fxcrt/fx_system.h"

CFX_BitStream::CFX_BitStream(pdfium::span<const uint8_t> pData)
    : m_BitPos(0), m_BitSize(pData.size() * 8), m_pData(pData.data()) {
  ASSERT(pData.size() <= std::numeric_limits<uint32_t>::max() / 8);
}

CFX_BitStream::~CFX_BitStream() {}

void CFX_BitStream::ByteAlign() {
  m_BitPos = (m_BitPos + 7) & ~7;
}

uint32_t CFX_BitStream::GetBits(uint32_t nBits) {
  ASSERT(nBits > 0);
  ASSERT(nBits <= 32);
  if (nBits > m_BitSize || m_BitPos > m_BitSize - nBits)
    return 0;

  const uint32_t bit_pos = m_BitPos % 8;
  uint32_t byte_pos = m_BitPos / 8;
  const uint8_t* data = m_pData.Get();
  uint8_t current_byte = data[byte_pos];

  if (nBits == 1) {
    int bit = (current_byte & (1 << (7 - bit_pos))) ? 1 : 0;
    m_BitPos++;
    return bit;
  }

  uint32_t bit_left = nBits;
  uint32_t result = 0;
  if (bit_pos) {
    uint32_t bits_readable = 8 - bit_pos;
    if (bits_readable >= bit_left) {
      result = (current_byte & (0xff >> bit_pos)) >> (bits_readable - bit_left);
      m_BitPos += bit_left;
      return result;
    }
    bit_left -= bits_readable;
    result = (current_byte & ((1 << bits_readable) - 1)) << bit_left;
    ++byte_pos;
  }
  while (bit_left >= 8) {
    bit_left -= 8;
    result |= data[byte_pos++] << bit_left;
  }
  if (bit_left)
    result |= data[byte_pos] >> (8 - bit_left);
  m_BitPos += nBits;
  return result;
}