testing
[SXSI/XMLTree.git] / libcds / src / static_sequence / wt_coder_huff.cpp
1 /* wt_coder_huff.cpp
2  * Copyright (C) 2008, Francisco Claude, all rights reserved.
3  *
4  * wt_coder_huff definition
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 <wt_coder_huff.h>
23
24 wt_coder_huff::wt_coder_huff(uint * symbs, uint n, alphabet_mapper * am) {
25   for(uint i=0;i<n;i++)
26     symbs[i] = am->map(symbs[i]);
27         hc = new huffman_codes(symbs, n);
28   buffer = new uint[hc->max_length()/W+1]; 
29   s_len = 0; last_symbol = (uint)-1;
30   for(uint i=0;i<n;i++)
31     symbs[i] = am->unmap(symbs[i]);
32 }
33
34 wt_coder_huff::wt_coder_huff() {}
35
36 wt_coder_huff::~wt_coder_huff() {
37   delete hc;
38   delete [] buffer;
39 }
40
41 bool wt_coder_huff::is_set(uint symbol, uint l) {
42         if(symbol!=last_symbol) {
43     s_len = (uint)hc->encode(symbol, buffer, (ulong)0);
44     last_symbol = symbol;
45   }
46   return bitget(buffer,l);
47 }
48
49 bool wt_coder_huff::done(uint symbol, uint l) {
50   if(symbol!=last_symbol) {
51     s_len = (uint)hc->encode(symbol, buffer, (ulong)0);
52     last_symbol = symbol;
53   }
54   return l==s_len;
55 }
56
57 uint wt_coder_huff::size() {
58   return 2*sizeof(uint)+sizeof(wt_coder_huff)+hc->size()+(hc->max_length()/W+1)*sizeof(uint);
59 }
60
61 uint wt_coder_huff::save(FILE * fp) {
62   uint wr = WT_CODER_HUFF_HDR;
63   wr = fwrite(&wr,sizeof(uint),1,fp);
64   if(wr!=1) return 1;
65   if(hc->save(fp)) return 1;
66   //if(am->save(fp)) return 1;
67   return 0;
68 }
69
70 wt_coder_huff * wt_coder_huff::load(FILE *fp) {
71   uint rd;
72   if(fread(&rd,sizeof(uint),1,fp)!=1) return NULL;
73   if(rd!=WT_CODER_HUFF_HDR) return NULL;
74   wt_coder_huff * ret = new wt_coder_huff();
75   ret->hc = huffman_codes::load(fp);
76   ret->buffer = new uint[ret->hc->max_length()/W+1]; 
77   ret->s_len = 0; ret->last_symbol = (uint)-1;
78   return ret;
79 }