• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 PDFium 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 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6 
7 #include "core/fxcrt/cfx_bitstream.h"
8 
9 #include <limits>
10 
11 #include "core/fxcrt/fx_system.h"
12 
CFX_BitStream(const uint8_t * pData,uint32_t dwSize)13 CFX_BitStream::CFX_BitStream(const uint8_t* pData, uint32_t dwSize)
14     : m_BitPos(0), m_BitSize(dwSize * 8), m_pData(pData) {
15   ASSERT(dwSize <= std::numeric_limits<uint32_t>::max() / 8);
16 }
17 
~CFX_BitStream()18 CFX_BitStream::~CFX_BitStream() {}
19 
ByteAlign()20 void CFX_BitStream::ByteAlign() {
21   m_BitPos = (m_BitPos + 7) & ~7;
22 }
23 
GetBits(uint32_t nBits)24 uint32_t CFX_BitStream::GetBits(uint32_t nBits) {
25   if (nBits > m_BitSize || m_BitPos + nBits > m_BitSize)
26     return 0;
27 
28   const uint8_t* data = m_pData.Get();
29 
30   if (nBits == 1) {
31     int bit = (data[m_BitPos / 8] & (1 << (7 - m_BitPos % 8))) ? 1 : 0;
32     m_BitPos++;
33     return bit;
34   }
35 
36   uint32_t byte_pos = m_BitPos / 8;
37   uint32_t bit_pos = m_BitPos % 8;
38   uint32_t bit_left = nBits;
39   uint32_t result = 0;
40   if (bit_pos) {
41     if (8 - bit_pos >= bit_left) {
42       result = (data[byte_pos] & (0xff >> bit_pos)) >> (8 - bit_pos - bit_left);
43       m_BitPos += bit_left;
44       return result;
45     }
46     bit_left -= 8 - bit_pos;
47     result = (data[byte_pos++] & ((1 << (8 - bit_pos)) - 1)) << bit_left;
48   }
49   while (bit_left >= 8) {
50     bit_left -= 8;
51     result |= data[byte_pos++] << bit_left;
52   }
53   if (bit_left)
54     result |= data[byte_pos] >> (8 - bit_left);
55   m_BitPos += nBits;
56   return result;
57 }
58