e603133204537cf93d9f746a6af3ee4eb4e97459
[SXSI/XMLTree.git] / libcds / src / coders / huffman_codes.cpp
1 /* huffman_codes.cpp
2    Copyright (C) 2008, Francisco Claude, all rights reserved.
3
4    Wrapper for huff written by Gonzalo Navarro
5
6    This library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Lesser General Public
8    License as published by the Free Software Foundation; either
9    version 2.1 of the License, or (at your option) any later version.
10
11    This library is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    Lesser General Public License for more details.
15
16    You should have received a copy of the GNU Lesser General Public
17    License along with this library; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19
20 */
21
22 #include <huffman_codes.h>
23
24 huffman_codes::huffman_codes(uint * symb, uint n) {
25   uint max_v = 0;
26   for(uint i=0;i<n;i++)
27     max_v = max(max_v,symb[i]);
28   uint * occ = new uint[max_v+1];
29   for(uint i=0;i<max_v+1;i++)
30     occ[i] = 0;
31   for(uint i=0;i<n;i++)
32     occ[symb[i]]++;
33   huff_table = createHuff(occ, max_v);
34   delete [] occ;
35 }
36
37 huffman_codes::huffman_codes(uchar * symb, uint n) {
38   uchar max_v = 0;
39   for(uint i=0;i<n;i++)
40     max_v = max(max_v,symb[i]);
41   uint * occ = new uint[max_v+1];
42   for(uint i=0;i<(uint)max_v+1;i++)
43     occ[i] = 0;
44   for(uint i=0;i<n;i++)
45     occ[symb[i]]++;
46   huff_table = createHuff(occ, max_v);
47   delete [] occ;
48 }
49
50 huffman_codes::huffman_codes() {
51 }
52
53 huffman_codes::~huffman_codes() {
54   freeHuff(huff_table);
55 }
56
57 uint huffman_codes::max_length() {
58   return huff_table.depth;
59 }
60
61 uint huffman_codes::size() {
62   return sizeof(huffman_codes)+sizeHuff(huff_table);
63 }
64
65 ulong huffman_codes::encode(uint symb, uint * stream, ulong pos) {
66   return encodeHuff(huff_table, symb, stream, pos);
67 }
68
69 ulong huffman_codes::decode(uint * symb, uint * stream, ulong pos) {
70   return decodeHuff(huff_table, symb, stream, pos);
71 }
72
73 uint huffman_codes::save(FILE *fp) {
74   saveHuff(huff_table,fp);
75   return 0;
76 }
77
78 huffman_codes * huffman_codes::load(FILE * fp) {
79   huffman_codes * ret = new huffman_codes();
80   ret->huff_table = loadHuff(fp,1);
81   return ret;
82 }