Initial import of XMLTree
[SXSI/XMLTree.git] / libcds / src / static_sequence / wt_coder_huff.cpp
1
2 #include <wt_coder_huff.h>
3
4 wt_coder_huff::wt_coder_huff(uint * symbs, uint n, alphabet_mapper * am) {
5   for(uint i=0;i<n;i++)
6     symbs[i] = am->map(symbs[i]);
7         hc = new huffman_codes(symbs, n);
8   buffer = new uint[hc->max_length()/W+1]; 
9   s_len = 0; last_symbol = (uint)-1;
10   for(uint i=0;i<n;i++)
11     symbs[i] = am->unmap(symbs[i]);
12 }
13
14 wt_coder_huff::wt_coder_huff() {}
15
16 wt_coder_huff::~wt_coder_huff() {
17   delete hc;
18   delete [] buffer;
19 }
20
21 bool wt_coder_huff::is_set(uint symbol, uint l) {
22         if(symbol!=last_symbol) {
23     s_len = (uint)hc->encode(symbol, buffer, (ulong)0);
24     last_symbol = symbol;
25   }
26   return bitget(buffer,l);
27 }
28
29 bool wt_coder_huff::done(uint symbol, uint l) {
30   if(symbol!=last_symbol) {
31     s_len = (uint)hc->encode(symbol, buffer, (ulong)0);
32     last_symbol = symbol;
33   }
34   return l==s_len;
35 }
36
37 uint wt_coder_huff::size() {
38   return 2*sizeof(uint)+sizeof(wt_coder_huff)+hc->size()+(hc->max_length()/W+1)*sizeof(uint);
39 }
40
41 uint wt_coder_huff::save(FILE * fp) {
42   uint wr = WT_CODER_HUFF_HDR;
43   wr = fwrite(&wr,sizeof(uint),1,fp);
44   if(wr!=1) return 1;
45   if(hc->save(fp)) return 1;
46   //if(am->save(fp)) return 1;
47   return 0;
48 }
49
50 wt_coder_huff * wt_coder_huff::load(FILE *fp) {
51   uint rd;
52   if(fread(&rd,sizeof(uint),1,fp)!=1) return NULL;
53   if(rd!=WT_CODER_HUFF_HDR) return NULL;
54   wt_coder_huff * ret = new wt_coder_huff();
55   ret->hc = huffman_codes::load(fp);
56   ret->buffer = new uint[ret->hc->max_length()/W+1]; 
57   ret->s_len = 0; ret->last_symbol = (uint)-1;
58   return ret;
59 }