Initial commit.
[pdfium.git] / core / src / fxcodec / jbig2 / JBig2_HuffmanDecoder.cpp
1 // Copyright 2014 PDFium Authors. All rights reserved.\r
2 // Use of this source code is governed by a BSD-style license that can be\r
3 // found in the LICENSE file.\r
4  \r
5 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com\r
6 \r
7 #include "JBig2_HuffmanDecoder.h"\r
8 CJBig2_HuffmanDecoder::CJBig2_HuffmanDecoder(CJBig2_BitStream *pStream)\r
9 {\r
10     m_pStream = pStream;\r
11 }\r
12 CJBig2_HuffmanDecoder::~CJBig2_HuffmanDecoder()\r
13 {\r
14 }\r
15 int CJBig2_HuffmanDecoder::decodeAValue(CJBig2_HuffmanTable *pTable, int *nResult)\r
16 {\r
17     int nVal, nTmp, i, nBits;\r
18     nVal = 0;\r
19     nBits = 0;\r
20     while(1) {\r
21         if(m_pStream->read1Bit(&nTmp) == -1) {\r
22             return -1;\r
23         }\r
24         nVal = (nVal << 1) | nTmp;\r
25         nBits ++;\r
26         for(i = 0; i < pTable->NTEMP; i++) {\r
27             if((pTable->PREFLEN[i] == nBits) && (pTable->CODES[i] == nVal)) {\r
28                 if((pTable->HTOOB == 1) && (i == pTable->NTEMP - 1)) {\r
29                     return JBIG2_OOB;\r
30                 }\r
31                 if(m_pStream->readNBits(pTable->RANGELEN[i], &nTmp) == -1) {\r
32                     return -1;\r
33                 }\r
34                 if(pTable->HTOOB) {\r
35                     if(i == pTable->NTEMP - 3) {\r
36                         *nResult = pTable->RANGELOW[i] - nTmp;\r
37                         return 0;\r
38                     } else {\r
39                         *nResult = pTable->RANGELOW[i] + nTmp;\r
40                         return 0;\r
41                     }\r
42                 } else {\r
43                     if(i == pTable->NTEMP - 2) {\r
44                         *nResult = pTable->RANGELOW[i] - nTmp;\r
45                         return 0;\r
46                     } else {\r
47                         *nResult = pTable->RANGELOW[i] + nTmp;\r
48                         return 0;\r
49                     }\r
50                 }\r
51             }\r
52         }\r
53     }\r
54     return -2;\r
55 }\r