/***********************************************************************1* *2* This software is part of the ast package *3* Copyright (c) 1993-2011 AT&T Intellectual Property *4* and is licensed under the *5* Eclipse Public License, Version 1.0 *6* by AT&T Intellectual Property *7* *8* A copy of the License is available at *9* http://www.eclipse.org/org/documents/epl-v10.html *10* (with md5 checksum b35adb5213ca9657e911e9befb180842) *11* *12* Information and Software Systems Research *13* AT&T Research *14* Florham Park NJ *15* *16* David Korn <[email protected]> *17* *18***********************************************************************/19#pragma prototyped20/*21* huffman coding routine to read a pack format header22*23* David Korn24* AT&T Laboratories25*/2627#include "huffman.h"28#include <error.h>2930#define END (1<<CHAR_BIT)3132Huff_t *huffgethdr(register Sfio_t *infile)33{34register Huff_t* hp;35register int i, j, c;36/* allocate space for huffman tree */37if(!(hp=newof(0, Huff_t, 1, 0)))38{39errno = ENOMEM;40return((Huff_t*)0);41}42/* check two-byte header */43if(sfgetc(infile)!=HUFFMAG1 || sfgetc(infile)!=HUFFMAG2)44goto error;45/* get size of original file, */46for (i=0; i<4; i++)47hp->insize = (hp->insize<<CHAR_BIT)+ sfgetc(infile);48/* get number of levels in maxlev, */49hp->maxlev = sfgetc(infile);50if(hp->maxlev==0)51{52/* larger than 2**32 */53for (i=0; i<4; i++)54hp->insize = (hp->insize<<CHAR_BIT)+ sfgetc(infile);55hp->maxlev = sfgetc(infile);56}57if(hp->maxlev < 0 || hp->maxlev > HUFFLEV)58goto error;59/* get number of leaves on level i */60for (i=1; i<=hp->maxlev; i++)61{62if((c=sfgetc(infile)) < 0)63goto error;64hp->levcount[i] = c;65}66/* read in the characters and compute number of bits for each */67for(i=0; i <= END; i++)68hp->length[i] = 0;69hp->nchars = 0;70for (i=1; i<=hp->maxlev; i++)71{72j = hp->levcount[i];73if((hp->nchars += j) >=END)74goto error;75while (j-- > 0)76{77if((c=sfgetc(infile)) < 0)78goto error;79hp->length[c] = i;80}81}82if((c=sfgetc(infile)) < 0)83goto error;84hp->length[c] = i-1;85return(hp);8687error:88huffend(hp);89return ((Huff_t*)0);90}919293