libopenraw
huffman.cpp
1 /* -*- tab-width:4; c-basic-offset:4 -*- */
2 /*
3  * libopenraw - huffman.cpp
4  *
5  * Copyright (C) 2008 Rafael Avila de Espindola.
6  *
7  * This library is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public License
9  * as published by the Free Software Foundation, either version 3 of
10  * the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library. If not, see
19  * <http://www.gnu.org/licenses/>.
20  */
21 
22 #include <string>
23 #include <iostream>
24 #include "huffman.h"
25 
26 namespace OpenRaw {
27 namespace Internals {
28 
29 void HuffmanDecoder::printTable_(std::string prefix, unsigned int pos) const
30 {
31  const HuffmanNode &cur = m_p[pos];
32  if (cur.isLeaf) {
33  std::cerr << prefix << " " << cur.data << "\n";
34  } else {
35  printTable_(prefix + "0", pos + 1);
36  printTable_(prefix + "1", cur.data);
37  }
38 }
39 
40 HuffmanDecoder::HuffmanDecoder(const HuffmanNode* const p) : m_p(p)
41 {
42 }
43 
44 void HuffmanDecoder::printTable() const
45 {
46  printTable_("", 0);
47 }
48 
49 unsigned int HuffmanDecoder::decode(BitIterator& i)
50 {
51  int cur = 0;
52  while (!m_p[cur].isLeaf) {
53  unsigned int bit = i.get(1);
54  if (bit)
55  cur = m_p[cur].data;
56  else
57  cur = cur + 1;
58  }
59  return m_p[cur].data;
60 }
61 
62 }
63 }