1// Copyright 2014 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/fxcodec/jbig2/JBig2_HuffmanDecoder.h"
8
9#include "core/fxcodec/jbig2/JBig2_Define.h"
10
11CJBig2_HuffmanDecoder::CJBig2_HuffmanDecoder(CJBig2_BitStream* pStream)
12    : m_pStream(pStream) {}
13
14CJBig2_HuffmanDecoder::~CJBig2_HuffmanDecoder() {}
15
16int CJBig2_HuffmanDecoder::decodeAValue(CJBig2_HuffmanTable* pTable,
17                                        int* nResult) {
18  int nVal = 0;
19  int nBits = 0;
20  while (1) {
21    uint32_t nTmp;
22    if (m_pStream->read1Bit(&nTmp) == -1)
23      break;
24
25    nVal = (nVal << 1) | nTmp;
26    ++nBits;
27    for (uint32_t i = 0; i < pTable->Size(); ++i) {
28      if (pTable->GetPREFLEN()[i] == nBits && pTable->GetCODES()[i] == nVal) {
29        if (pTable->IsHTOOB() && i == pTable->Size() - 1)
30          return JBIG2_OOB;
31
32        if (m_pStream->readNBits(pTable->GetRANGELEN()[i], &nTmp) == -1)
33          return -1;
34
35        uint32_t offset = pTable->IsHTOOB() ? 3 : 2;
36        if (i == pTable->Size() - offset)
37          *nResult = pTable->GetRANGELOW()[i] - nTmp;
38        else
39          *nResult = pTable->GetRANGELOW()[i] + nTmp;
40        return 0;
41      }
42    }
43  }
44  return -1;
45}
46