compress.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  1. /*
  2. * compress - File compression ala IEEE Computer, June 1984.
  3. *
  4. * Algorithm from "A Technique for High Performance Data Compression",
  5. * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
  6. *
  7. * Usage: compress [-dfvc] [-b bits] [file ...]
  8. * Inputs:
  9. * -b: limit the max number of bits/code.
  10. * -c: write output on stdout, don't remove original.
  11. * -d: decompress instead.
  12. * -f: Forces output file to be generated, even if one already
  13. * exists, and even if no space is saved by compressing.
  14. * If -f is not used, the user will be prompted if stdin is
  15. * a tty, otherwise, the output file will not be overwritten.
  16. * -v: Write compression statistics
  17. *
  18. * file ...: Files to be compressed. If none specified, stdin is used.
  19. * Outputs:
  20. * file.Z: Compressed form of file with same mode, owner, and utimes
  21. * or stdout (if stdin used as input)
  22. *
  23. * Assumptions:
  24. * When filenames are given, replaces with the compressed version
  25. * (.Z suffix) only if the file decreases in size.
  26. * Algorithm:
  27. * Modified Lempel-Ziv method (LZW). Basically finds common
  28. * substrings and replaces them with a variable size code. This is
  29. * deterministic, and can be done on the fly. Thus, the decompression
  30. * procedure needs no input table, but tracks the way the table was built.
  31. * Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)
  32. * Jim McKie (decvax!mcvax!jim)
  33. * Steve Davies (decvax!vax135!petsd!peora!srd)
  34. * Ken Turkowski (decvax!decwrl!turtlevax!ken)
  35. * James A. Woods (decvax!ihnp4!ames!jaw)
  36. * Joe Orost (decvax!vax135!petsd!joe)
  37. */
  38. #define _PLAN9_SOURCE
  39. #include <u.h>
  40. #include <stdio.h>
  41. #include <ctype.h>
  42. #include <stdlib.h>
  43. #include <string.h>
  44. #include <signal.h>
  45. #include <sys/types.h>
  46. #include <sys/stat.h>
  47. #define min(a,b) ((a>b) ? b : a)
  48. #define BITS 16
  49. #define HSIZE 69001 /* 95% occupancy */
  50. /*
  51. * a code_int must be able to hold 2**BITS values of type int, and also -1
  52. */
  53. typedef long code_int;
  54. typedef long count_int;
  55. static char rcs_ident[] = "$Header: compress.c,v 4.0 85/07/30 12:50:00 joe Release $";
  56. uchar magic_header[] = { 0x1F, 0x9D }; /* 1F 9D */
  57. /* Defines for third byte of header */
  58. #define BIT_MASK 0x1f
  59. #define BLOCK_MASK 0x80
  60. /* Masks 0x40 and 0x20 are free. I think 0x20 should mean that there is
  61. a fourth header byte (for expansion).
  62. */
  63. #define INIT_BITS 9 /* initial number of bits/code */
  64. void onintr(int);
  65. void oops(int);
  66. #define ARGVAL() (*++(*argv) || (--argc && *++argv))
  67. int n_bits; /* number of bits/code */
  68. int maxbits = BITS; /* user settable max # bits/code */
  69. code_int maxcode; /* maximum code, given n_bits */
  70. code_int maxmaxcode = 1 << BITS; /* should NEVER generate this code */
  71. #define MAXCODE(n_bits) ((1 << (n_bits)) - 1)
  72. count_int htab[HSIZE];
  73. ushort codetab[HSIZE];
  74. #define htabof(i) htab[i]
  75. #define codetabof(i) codetab[i]
  76. code_int hsize = HSIZE; /* for dynamic table sizing */
  77. count_int fsize;
  78. /*
  79. * To save much memory, we overlay the table used by compress() with those
  80. * used by decompress(). The tab_prefix table is the same size and type
  81. * as the codetab. The tab_suffix table needs 2**BITS characters. We
  82. * get this from the beginning of htab. The output stack uses the rest
  83. * of htab, and contains characters. There is plenty of room for any
  84. * possible stack (stack used to be 8000 characters).
  85. */
  86. #define tab_prefixof(i) codetabof(i)
  87. #define tab_suffixof(i) ((uchar *)(htab))[i]
  88. #define de_stack ((uchar *)&tab_suffixof(1<<BITS))
  89. code_int free_ent = 0; /* first unused entry */
  90. int exit_stat = 0;
  91. code_int getcode();
  92. Usage()
  93. {
  94. #ifdef DEBUG
  95. fprintf(stderr,"Usage: compress [-cdfDV] [-b maxbits] [file ...]\n");
  96. #else
  97. fprintf(stderr,"Usage: compress [-cdfvV] [-b maxbits] [file ...]\n");
  98. #endif /* DEBUG */
  99. }
  100. int debug = 0;
  101. int nomagic = 0; /* Use a 3-byte magic number header, unless old file */
  102. int zcat_flg = 0; /* Write output on stdout, suppress messages */
  103. int quiet = 1; /* don't tell me about compression */
  104. /*
  105. * block compression parameters -- after all codes are used up,
  106. * and compression rate changes, start over.
  107. */
  108. int block_compress = BLOCK_MASK;
  109. int clear_flg = 0;
  110. long ratio = 0;
  111. #define CHECK_GAP 10000 /* ratio check interval */
  112. count_int checkpoint = CHECK_GAP;
  113. /*
  114. * the next two codes should not be changed lightly, as they must not
  115. * lie within the contiguous general code space.
  116. */
  117. #define FIRST 257 /* first free entry */
  118. #define CLEAR 256 /* table clear output code */
  119. int force = 0;
  120. char ofname [100];
  121. #ifdef DEBUG
  122. int verbose = 0;
  123. #endif /* DEBUG */
  124. void (*bgnd_flag)(int);
  125. int do_decomp = 0;
  126. main(argc, argv)
  127. int argc;
  128. char **argv;
  129. {
  130. int overwrite = 0; /* Do not overwrite unless given -f flag */
  131. char tempname[512];
  132. char **filelist, **fileptr;
  133. char *cp;
  134. struct stat statbuf;
  135. if ( (bgnd_flag = signal ( SIGINT, SIG_IGN )) != SIG_IGN ) {
  136. signal(SIGINT, onintr);
  137. signal(SIGSEGV, oops);
  138. }
  139. filelist = fileptr = (char **)(malloc(argc * sizeof(*argv)));
  140. *filelist = NULL;
  141. if((cp = strrchr(argv[0], '/')) != 0)
  142. cp++;
  143. else
  144. cp = argv[0];
  145. if(strcmp(cp, "uncompress") == 0)
  146. do_decomp = 1;
  147. else if(strcmp(cp, "zcat") == 0) {
  148. do_decomp = 1;
  149. zcat_flg = 1;
  150. }
  151. /*
  152. * Argument Processing
  153. * All flags are optional.
  154. * -C generate output compatible with compress 2.0.
  155. * -D debug
  156. * -V print Version; debug verbose
  157. * -b maxbits maxbits. If -b is specified, then maxbits MUST be
  158. * given also.
  159. * -c cat all output to stdout
  160. * -d do_decomp
  161. * -f force overwrite of output file
  162. * -n no header: useful to uncompress old files
  163. * -v unquiet
  164. * if a string is left, must be an input filename.
  165. */
  166. for (argc--, argv++; argc > 0; argc--, argv++) {
  167. if (**argv == '-') { /* A flag argument */
  168. while (*++(*argv)) { /* Process all flags in this arg */
  169. switch (**argv) {
  170. case 'C':
  171. block_compress = 0;
  172. break;
  173. #ifdef DEBUG
  174. case 'D':
  175. debug = 1;
  176. break;
  177. case 'V':
  178. verbose = 1;
  179. version();
  180. break;
  181. #else
  182. case 'V':
  183. version();
  184. break;
  185. #endif
  186. case 'b':
  187. if (!ARGVAL()) {
  188. fprintf(stderr, "Missing maxbits\n");
  189. Usage();
  190. exit(1);
  191. }
  192. maxbits = atoi(*argv);
  193. goto nextarg;
  194. case 'c':
  195. zcat_flg = 1;
  196. break;
  197. case 'd':
  198. do_decomp = 1;
  199. break;
  200. case 'f':
  201. case 'F':
  202. overwrite = 1;
  203. force = 1;
  204. break;
  205. case 'n':
  206. nomagic = 1;
  207. break;
  208. case 'q':
  209. quiet = 1;
  210. break;
  211. case 'v':
  212. quiet = 0;
  213. break;
  214. default:
  215. fprintf(stderr, "Unknown flag: '%c'; ", **argv);
  216. Usage();
  217. exit(1);
  218. }
  219. }
  220. } else { /* Input file name */
  221. *fileptr++ = *argv; /* Build input file list */
  222. *fileptr = NULL;
  223. /* process nextarg; */
  224. }
  225. nextarg:
  226. continue;
  227. }
  228. if(maxbits < INIT_BITS) maxbits = INIT_BITS;
  229. if (maxbits > BITS) maxbits = BITS;
  230. maxmaxcode = 1 << maxbits;
  231. if (*filelist != NULL) {
  232. for (fileptr = filelist; *fileptr; fileptr++) {
  233. exit_stat = 0;
  234. if (do_decomp != 0) { /* DECOMPRESSION */
  235. /* Check for .Z suffix */
  236. if (strcmp(*fileptr + strlen(*fileptr) - 2, ".Z") != 0) {
  237. /* No .Z: tack one on */
  238. strcpy(tempname, *fileptr);
  239. strcat(tempname, ".Z");
  240. *fileptr = tempname;
  241. }
  242. /* Open input file */
  243. if ((freopen(*fileptr, "r", stdin)) == NULL) {
  244. perror(*fileptr);
  245. continue;
  246. }
  247. /* Check the magic number */
  248. if (nomagic == 0) {
  249. if ((getchar() != (magic_header[0] & 0xFF))
  250. || (getchar() != (magic_header[1] & 0xFF))) {
  251. fprintf(stderr, "%s: not in compressed format\n",
  252. *fileptr);
  253. continue;
  254. }
  255. maxbits = getchar(); /* set -b from file */
  256. block_compress = maxbits & BLOCK_MASK;
  257. maxbits &= BIT_MASK;
  258. maxmaxcode = 1 << maxbits;
  259. if(maxbits > BITS) {
  260. fprintf(stderr,
  261. "%s: compressed with %d bits, can only handle %d bits\n",
  262. *fileptr, maxbits, BITS);
  263. continue;
  264. }
  265. }
  266. /* Generate output filename */
  267. strcpy(ofname, *fileptr);
  268. ofname[strlen(*fileptr) - 2] = '\0'; /* Strip off .Z */
  269. } else { /* COMPRESSION */
  270. if (strcmp(*fileptr + strlen(*fileptr) - 2, ".Z") == 0) {
  271. fprintf(stderr,
  272. "%s: already has .Z suffix -- no change\n",
  273. *fileptr);
  274. continue;
  275. }
  276. /* Open input file */
  277. if ((freopen(*fileptr, "r", stdin)) == NULL) {
  278. perror(*fileptr);
  279. continue;
  280. }
  281. (void) stat(*fileptr, &statbuf);
  282. fsize = (long) statbuf.st_size;
  283. /*
  284. * tune hash table size for small files -- ad hoc,
  285. * but the sizes match earlier #defines, which
  286. * serve as upper bounds on the number of output codes.
  287. */
  288. hsize = HSIZE;
  289. if (fsize < (1 << 12))
  290. hsize = min(5003, HSIZE);
  291. else if (fsize < (1 << 13))
  292. hsize = min(9001, HSIZE);
  293. else if (fsize < (1 << 14))
  294. hsize = min (18013, HSIZE);
  295. else if (fsize < (1 << 15))
  296. hsize = min (35023, HSIZE);
  297. else if (fsize < 47000)
  298. hsize = min (50021, HSIZE);
  299. /* Generate output filename */
  300. strcpy(ofname, *fileptr);
  301. #ifndef BSD4_2
  302. if ((cp=strrchr(ofname,'/')) != NULL)
  303. cp++;
  304. else
  305. cp = ofname;
  306. /*
  307. *** changed 12 to 25; should be NAMELEN-3, but I don't want
  308. * to fight the headers. ehg 5 Nov 92 **
  309. */
  310. if (strlen(cp) > 25) {
  311. fprintf(stderr, "%s: filename too long to tack on .Z\n",
  312. cp);
  313. continue;
  314. }
  315. #endif
  316. strcat(ofname, ".Z");
  317. }
  318. /* Check for overwrite of existing file */
  319. if (overwrite == 0 && zcat_flg == 0 &&
  320. stat(ofname, &statbuf) == 0) {
  321. char response[2];
  322. response[0] = 'n';
  323. fprintf(stderr, "%s already exists;", ofname);
  324. if (foreground()) {
  325. fprintf(stderr,
  326. " do you wish to overwrite %s (y or n)? ",
  327. ofname);
  328. fflush(stderr);
  329. (void) read(2, response, 2);
  330. while (response[1] != '\n')
  331. if (read(2, response+1, 1) < 0) {
  332. /* Ack! */
  333. perror("stderr");
  334. break;
  335. }
  336. }
  337. if (response[0] != 'y') {
  338. fprintf(stderr, "\tnot overwritten\n");
  339. continue;
  340. }
  341. }
  342. if(zcat_flg == 0) { /* Open output file */
  343. if (freopen(ofname, "w", stdout) == NULL) {
  344. perror(ofname);
  345. continue;
  346. }
  347. if(!quiet)
  348. fprintf(stderr, "%s: ", *fileptr);
  349. }
  350. /* Actually do the compression/decompression */
  351. if (do_decomp == 0)
  352. compress();
  353. #ifndef DEBUG
  354. else
  355. decompress();
  356. #else
  357. else if (debug == 0)
  358. decompress();
  359. else
  360. printcodes();
  361. if (verbose)
  362. dump_tab();
  363. #endif /* DEBUG */
  364. if(zcat_flg == 0) {
  365. copystat(*fileptr, ofname); /* Copy stats */
  366. if (exit_stat == 1 || !quiet)
  367. putc('\n', stderr);
  368. }
  369. }
  370. } else { /* Standard input */
  371. if (do_decomp == 0) {
  372. compress();
  373. #ifdef DEBUG
  374. if(verbose)
  375. dump_tab();
  376. #endif
  377. if(!quiet)
  378. putc('\n', stderr);
  379. } else {
  380. /* Check the magic number */
  381. if (nomagic == 0) {
  382. if ((getchar()!=(magic_header[0] & 0xFF))
  383. || (getchar()!=(magic_header[1] & 0xFF))) {
  384. fprintf(stderr, "stdin: not in compressed format\n");
  385. exit(1);
  386. }
  387. maxbits = getchar(); /* set -b from file */
  388. block_compress = maxbits & BLOCK_MASK;
  389. maxbits &= BIT_MASK;
  390. maxmaxcode = 1 << maxbits;
  391. fsize = 100000; /* assume stdin large for USERMEM */
  392. if(maxbits > BITS) {
  393. fprintf(stderr,
  394. "stdin: compressed with %d bits, can only handle %d bits\n",
  395. maxbits, BITS);
  396. exit(1);
  397. }
  398. }
  399. #ifndef DEBUG
  400. decompress();
  401. #else
  402. if (debug == 0)
  403. decompress();
  404. else
  405. printcodes();
  406. if (verbose)
  407. dump_tab();
  408. #endif /* DEBUG */
  409. }
  410. }
  411. exit(exit_stat);
  412. }
  413. static int offset;
  414. long in_count = 1; /* length of input */
  415. long bytes_out; /* length of compressed output */
  416. long out_count = 0; /* # of codes output (for debugging) */
  417. /*
  418. * compress stdin to stdout
  419. *
  420. * Algorithm: use open addressing double hashing (no chaining) on the
  421. * prefix code / next character combination. We do a variant of Knuth's
  422. * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  423. * secondary probe. Here, the modular division first probe is gives way
  424. * to a faster exclusive-or manipulation. Also do block compression with
  425. * an adaptive reset, whereby the code table is cleared when the compression
  426. * ratio decreases, but after the table fills. The variable-length output
  427. * codes are re-sized at this point, and a special CLEAR code is generated
  428. * for the decompressor. Late addition: construct the table according to
  429. * file size for noticeable speed improvement on small files. Please direct
  430. * questions about this implementation to ames!jaw.
  431. */
  432. compress()
  433. {
  434. code_int ent, hsize_reg;
  435. code_int i = 0;
  436. int c, disp, hshift;
  437. long fcode;
  438. if (nomagic == 0) {
  439. putchar(magic_header[0]);
  440. putchar(magic_header[1]);
  441. putchar((char)(maxbits | block_compress));
  442. if(ferror(stdout))
  443. writeerr();
  444. }
  445. offset = 0;
  446. bytes_out = 3; /* includes 3-byte header mojo */
  447. out_count = 0;
  448. clear_flg = 0;
  449. ratio = 0;
  450. in_count = 1;
  451. checkpoint = CHECK_GAP;
  452. maxcode = MAXCODE(n_bits = INIT_BITS);
  453. free_ent = (block_compress? FIRST: 256);
  454. ent = getchar ();
  455. hshift = 0;
  456. for (fcode = (long)hsize; fcode < 65536L; fcode *= 2)
  457. hshift++;
  458. hshift = 8 - hshift; /* set hash code range bound */
  459. hsize_reg = hsize;
  460. cl_hash( (count_int) hsize_reg); /* clear hash table */
  461. while ((c = getchar()) != EOF) {
  462. in_count++;
  463. fcode = (long) (((long) c << maxbits) + ent);
  464. i = ((c << hshift) ^ ent); /* xor hashing */
  465. if (htabof (i) == fcode) {
  466. ent = codetabof(i);
  467. continue;
  468. } else if ((long)htabof(i) < 0 ) /* empty slot */
  469. goto nomatch;
  470. disp = hsize_reg - i; /* secondary hash (after G. Knott) */
  471. if (i == 0)
  472. disp = 1;
  473. probe:
  474. if ((i -= disp) < 0)
  475. i += hsize_reg;
  476. if (htabof (i) == fcode) {
  477. ent = codetabof(i);
  478. continue;
  479. }
  480. if ((long)htabof(i) > 0)
  481. goto probe;
  482. nomatch:
  483. output((code_int)ent);
  484. out_count++;
  485. ent = c;
  486. if (free_ent < maxmaxcode) {
  487. codetabof(i) = free_ent++; /* code -> hashtable */
  488. htabof(i) = fcode;
  489. } else if ((count_int)in_count >= checkpoint && block_compress)
  490. cl_block ();
  491. }
  492. /*
  493. * Put out the final code.
  494. */
  495. output( (code_int)ent );
  496. out_count++;
  497. output( (code_int)-1 );
  498. /*
  499. * Print out stats on stderr
  500. */
  501. if(zcat_flg == 0 && !quiet) {
  502. #ifdef DEBUG
  503. fprintf( stderr,
  504. "%ld chars in, %ld codes (%ld bytes) out, compression factor: ",
  505. in_count, out_count, bytes_out );
  506. prratio( stderr, in_count, bytes_out );
  507. fprintf( stderr, "\n");
  508. fprintf( stderr, "\tCompression as in compact: " );
  509. prratio( stderr, in_count-bytes_out, in_count );
  510. fprintf( stderr, "\n");
  511. fprintf( stderr, "\tLargest code (of last block) was %d (%d bits)\n",
  512. free_ent - 1, n_bits );
  513. #else /* !DEBUG */
  514. fprintf( stderr, "Compression: " );
  515. prratio( stderr, in_count-bytes_out, in_count );
  516. #endif /* DEBUG */
  517. }
  518. if(bytes_out > in_count) /* exit(2) if no savings */
  519. exit_stat = 2;
  520. }
  521. /*
  522. * TAG( output )
  523. *
  524. * Output the given code.
  525. * Inputs:
  526. * code: A n_bits-bit integer. If == -1, then EOF. This assumes
  527. * that n_bits =< (long)wordsize - 1.
  528. * Outputs:
  529. * Outputs code to the file.
  530. * Assumptions:
  531. * Chars are 8 bits long.
  532. * Algorithm:
  533. * Maintain a BITS character long buffer (so that 8 codes will
  534. * fit in it exactly). When the buffer fills up empty it and start over.
  535. */
  536. static char buf[BITS];
  537. uchar lmask[9] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
  538. uchar rmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
  539. output( code )
  540. code_int code;
  541. {
  542. #ifdef DEBUG
  543. static int col = 0;
  544. #endif
  545. int r_off = offset, bits= n_bits;
  546. char *bp = buf;
  547. #ifdef DEBUG
  548. if (verbose)
  549. fprintf(stderr, "%5d%c", code,
  550. (col+=6) >= 74? (col = 0, '\n'): ' ');
  551. #endif
  552. if (code >= 0) {
  553. /*
  554. * byte/bit numbering on the VAX is simulated by the
  555. * following code
  556. */
  557. /*
  558. * Get to the first byte.
  559. */
  560. bp += (r_off >> 3);
  561. r_off &= 7;
  562. /*
  563. * Since code is always >= 8 bits, only need to mask the first
  564. * hunk on the left.
  565. */
  566. *bp = (*bp & rmask[r_off]) | (code << r_off) & lmask[r_off];
  567. bp++;
  568. bits -= 8 - r_off;
  569. code >>= 8 - r_off;
  570. /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  571. if ( bits >= 8 ) {
  572. *bp++ = code;
  573. code >>= 8;
  574. bits -= 8;
  575. }
  576. /* Last bits. */
  577. if(bits)
  578. *bp = code;
  579. offset += n_bits;
  580. if ( offset == (n_bits << 3) ) {
  581. bp = buf;
  582. bits = n_bits;
  583. bytes_out += bits;
  584. do {
  585. putchar(*bp++);
  586. } while(--bits);
  587. offset = 0;
  588. }
  589. /*
  590. * If the next entry is going to be too big for the code size,
  591. * then increase it, if possible.
  592. */
  593. if ( free_ent > maxcode || (clear_flg > 0)) {
  594. /*
  595. * Write the whole buffer, because the input side won't
  596. * discover the size increase until after it has read it.
  597. */
  598. if ( offset > 0 ) {
  599. if( fwrite( buf, 1, n_bits, stdout ) != n_bits)
  600. writeerr();
  601. bytes_out += n_bits;
  602. }
  603. offset = 0;
  604. if ( clear_flg ) {
  605. maxcode = MAXCODE (n_bits = INIT_BITS);
  606. clear_flg = 0;
  607. } else {
  608. n_bits++;
  609. if ( n_bits == maxbits )
  610. maxcode = maxmaxcode;
  611. else
  612. maxcode = MAXCODE(n_bits);
  613. }
  614. #ifdef DEBUG
  615. if ( debug ) {
  616. fprintf(stderr,
  617. "\nChange to %d bits\n", n_bits);
  618. col = 0;
  619. }
  620. #endif
  621. }
  622. } else {
  623. /*
  624. * At EOF, write the rest of the buffer.
  625. */
  626. if ( offset > 0 )
  627. fwrite( buf, 1, (offset + 7) / 8, stdout );
  628. bytes_out += (offset + 7) / 8;
  629. offset = 0;
  630. fflush( stdout );
  631. #ifdef DEBUG
  632. if ( verbose )
  633. fprintf( stderr, "\n" );
  634. #endif
  635. if( ferror( stdout ) )
  636. writeerr();
  637. }
  638. }
  639. /*
  640. * Decompress stdin to stdout. This routine adapts to the codes in the
  641. * file building the "string" table on-the-fly; requiring no table to
  642. * be stored in the compressed file. The tables used herein are shared
  643. * with those of the compress() routine. See the definitions above.
  644. */
  645. decompress()
  646. {
  647. int finchar;
  648. code_int code, oldcode, incode;
  649. uchar *stackp;
  650. /*
  651. * As above, initialize the first 256 entries in the table.
  652. */
  653. maxcode = MAXCODE(n_bits = INIT_BITS);
  654. for (code = 255; code >= 0; code--) {
  655. tab_prefixof(code) = 0;
  656. tab_suffixof(code) = (uchar)code;
  657. }
  658. free_ent = (block_compress? FIRST: 256);
  659. finchar = oldcode = getcode();
  660. if(oldcode == -1) /* EOF already? */
  661. return; /* Get out of here */
  662. putchar((char)finchar); /* first code must be 8 bits = char */
  663. if(ferror(stdout)) /* Crash if can't write */
  664. writeerr();
  665. stackp = de_stack;
  666. while ((code = getcode()) > -1) {
  667. if ((code == CLEAR) && block_compress) {
  668. for (code = 255; code >= 0; code--)
  669. tab_prefixof(code) = 0;
  670. clear_flg = 1;
  671. free_ent = FIRST - 1;
  672. if ((code = getcode()) == -1) /* O, untimely death! */
  673. break;
  674. }
  675. incode = code;
  676. /*
  677. * Special case for KwKwK string.
  678. */
  679. if (code >= free_ent) {
  680. *stackp++ = finchar;
  681. code = oldcode;
  682. }
  683. /*
  684. * Generate output characters in reverse order
  685. */
  686. while (code >= 256) {
  687. *stackp++ = tab_suffixof(code);
  688. code = tab_prefixof(code);
  689. }
  690. *stackp++ = finchar = tab_suffixof(code);
  691. /*
  692. * And put them out in forward order
  693. */
  694. do {
  695. putchar(*--stackp);
  696. } while (stackp > de_stack);
  697. /*
  698. * Generate the new entry.
  699. */
  700. if ( (code=free_ent) < maxmaxcode ) {
  701. tab_prefixof(code) = (ushort)oldcode;
  702. tab_suffixof(code) = finchar;
  703. free_ent = code+1;
  704. }
  705. /*
  706. * Remember previous code.
  707. */
  708. oldcode = incode;
  709. }
  710. fflush(stdout);
  711. if(ferror(stdout))
  712. writeerr();
  713. }
  714. /*
  715. * TAG( getcode )
  716. *
  717. * Read one code from the standard input. If EOF, return -1.
  718. * Inputs:
  719. * stdin
  720. * Outputs:
  721. * code or -1 is returned.
  722. */
  723. code_int
  724. getcode()
  725. {
  726. int r_off, bits;
  727. code_int code;
  728. static int offset = 0, size = 0;
  729. static uchar buf[BITS];
  730. uchar *bp = buf;
  731. if ( clear_flg > 0 || offset >= size || free_ent > maxcode ) {
  732. /*
  733. * If the next entry will be too big for the current code
  734. * size, then we must increase the size. This implies reading
  735. * a new buffer full, too.
  736. */
  737. if ( free_ent > maxcode ) {
  738. n_bits++;
  739. if ( n_bits == maxbits )
  740. maxcode = maxmaxcode; /* won't get any bigger now */
  741. else
  742. maxcode = MAXCODE(n_bits);
  743. }
  744. if ( clear_flg > 0) {
  745. maxcode = MAXCODE(n_bits = INIT_BITS);
  746. clear_flg = 0;
  747. }
  748. size = fread(buf, 1, n_bits, stdin);
  749. if (size <= 0)
  750. return -1; /* end of file */
  751. offset = 0;
  752. /* Round size down to integral number of codes */
  753. size = (size << 3) - (n_bits - 1);
  754. }
  755. r_off = offset;
  756. bits = n_bits;
  757. /*
  758. * Get to the first byte.
  759. */
  760. bp += (r_off >> 3);
  761. r_off &= 7;
  762. /* Get first part (low order bits) */
  763. code = (*bp++ >> r_off);
  764. bits -= (8 - r_off);
  765. r_off = 8 - r_off; /* now, offset into code word */
  766. /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  767. if (bits >= 8) {
  768. code |= *bp++ << r_off;
  769. r_off += 8;
  770. bits -= 8;
  771. }
  772. /* high order bits. */
  773. code |= (*bp & rmask[bits]) << r_off;
  774. offset += n_bits;
  775. return code;
  776. }
  777. #ifdef DEBUG
  778. printcodes()
  779. {
  780. /*
  781. * Just print out codes from input file. For debugging.
  782. */
  783. code_int code;
  784. int col = 0, bits;
  785. bits = n_bits = INIT_BITS;
  786. maxcode = MAXCODE(n_bits);
  787. free_ent = ((block_compress) ? FIRST : 256 );
  788. while ( ( code = getcode() ) >= 0 ) {
  789. if ( (code == CLEAR) && block_compress ) {
  790. free_ent = FIRST - 1;
  791. clear_flg = 1;
  792. }
  793. else if ( free_ent < maxmaxcode )
  794. free_ent++;
  795. if ( bits != n_bits ) {
  796. fprintf(stderr, "\nChange to %d bits\n", n_bits );
  797. bits = n_bits;
  798. col = 0;
  799. }
  800. fprintf(stderr, "%5d%c", code, (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  801. }
  802. putc( '\n', stderr );
  803. exit( 0 );
  804. }
  805. code_int sorttab[1<<BITS]; /* sorted pointers into htab */
  806. #define STACK_SIZE 15000
  807. dump_tab() /* dump string table */
  808. {
  809. int i, first, c, ent;
  810. int stack_top = STACK_SIZE;
  811. if(do_decomp == 0) { /* compressing */
  812. int flag = 1;
  813. for(i=0; i<hsize; i++) { /* build sort pointers */
  814. if((long)htabof(i) >= 0) {
  815. sorttab[codetabof(i)] = i;
  816. }
  817. }
  818. first = block_compress ? FIRST : 256;
  819. for(i = first; i < free_ent; i++) {
  820. fprintf(stderr, "%5d: \"", i);
  821. de_stack[--stack_top] = '\n';
  822. de_stack[--stack_top] = '"';
  823. stack_top = in_stack((htabof(sorttab[i])>>maxbits)&0xff,
  824. stack_top);
  825. for(ent=htabof(sorttab[i]) & ((1<<maxbits)-1);
  826. ent > 256;
  827. ent=htabof(sorttab[ent]) & ((1<<maxbits)-1)) {
  828. stack_top = in_stack(htabof(sorttab[ent]) >> maxbits,
  829. stack_top);
  830. }
  831. stack_top = in_stack(ent, stack_top);
  832. fwrite( &de_stack[stack_top], 1, STACK_SIZE-stack_top, stderr);
  833. stack_top = STACK_SIZE;
  834. }
  835. } else if(!debug) { /* decompressing */
  836. for ( i = 0; i < free_ent; i++ ) {
  837. ent = i;
  838. c = tab_suffixof(ent);
  839. if ( isascii(c) && isprint(c) )
  840. fprintf( stderr, "%5d: %5d/'%c' \"",
  841. ent, tab_prefixof(ent), c );
  842. else
  843. fprintf( stderr, "%5d: %5d/\\%03o \"",
  844. ent, tab_prefixof(ent), c );
  845. de_stack[--stack_top] = '\n';
  846. de_stack[--stack_top] = '"';
  847. for ( ; ent != NULL;
  848. ent = (ent >= FIRST ? tab_prefixof(ent) : NULL) ) {
  849. stack_top = in_stack(tab_suffixof(ent), stack_top);
  850. }
  851. fwrite( &de_stack[stack_top], 1, STACK_SIZE - stack_top, stderr );
  852. stack_top = STACK_SIZE;
  853. }
  854. }
  855. }
  856. int
  857. in_stack(int c, int stack_top)
  858. {
  859. if ( (isascii(c) && isprint(c) && c != '\\') || c == ' ' ) {
  860. de_stack[--stack_top] = c;
  861. } else {
  862. switch( c ) {
  863. case '\n': de_stack[--stack_top] = 'n'; break;
  864. case '\t': de_stack[--stack_top] = 't'; break;
  865. case '\b': de_stack[--stack_top] = 'b'; break;
  866. case '\f': de_stack[--stack_top] = 'f'; break;
  867. case '\r': de_stack[--stack_top] = 'r'; break;
  868. case '\\': de_stack[--stack_top] = '\\'; break;
  869. default:
  870. de_stack[--stack_top] = '0' + c % 8;
  871. de_stack[--stack_top] = '0' + (c / 8) % 8;
  872. de_stack[--stack_top] = '0' + c / 64;
  873. break;
  874. }
  875. de_stack[--stack_top] = '\\';
  876. }
  877. return stack_top;
  878. }
  879. #endif /* DEBUG */
  880. writeerr()
  881. {
  882. perror(ofname);
  883. unlink(ofname);
  884. exit(1);
  885. }
  886. copystat(ifname, ofname)
  887. char *ifname, *ofname;
  888. {
  889. int mode;
  890. time_t timep[2];
  891. struct stat statbuf;
  892. fclose(stdout);
  893. if (stat(ifname, &statbuf)) { /* Get stat on input file */
  894. perror(ifname);
  895. return;
  896. }
  897. if (!S_ISREG(statbuf.st_mode)) {
  898. if (quiet)
  899. fprintf(stderr, "%s: ", ifname);
  900. fprintf(stderr, " -- not a regular file: unchanged");
  901. exit_stat = 1;
  902. } else if (exit_stat == 2 && (!force)) {
  903. /* No compression: remove file.Z */
  904. if (!quiet)
  905. fprintf(stderr, " -- file unchanged");
  906. } else { /* Successful Compression */
  907. exit_stat = 0;
  908. mode = statbuf.st_mode & 07777;
  909. if (chmod(ofname, mode)) /* Copy modes */
  910. perror(ofname);
  911. /* Copy ownership */
  912. chown(ofname, statbuf.st_uid, statbuf.st_gid);
  913. timep[0] = statbuf.st_atime;
  914. timep[1] = statbuf.st_mtime;
  915. /* Update last accessed and modified times */
  916. utime(ofname, timep);
  917. // if (unlink(ifname)) /* Remove input file */
  918. // perror(ifname);
  919. }
  920. /* Unsuccessful return -- one of the tests failed */
  921. if (unlink(ofname))
  922. perror(ofname);
  923. }
  924. /*
  925. * This routine returns 1 if we are running in the foreground and stderr
  926. * is a tty.
  927. */
  928. foreground()
  929. {
  930. if(bgnd_flag) /* background? */
  931. return 0;
  932. else /* foreground */
  933. return isatty(2); /* and stderr is a tty */
  934. }
  935. void
  936. onintr(int x)
  937. {
  938. unlink(ofname);
  939. exit(1);
  940. }
  941. void
  942. oops(int x) /* wild pointer -- assume bad input */
  943. {
  944. if (do_decomp == 1)
  945. fprintf(stderr, "uncompress: corrupt input\n");
  946. unlink(ofname);
  947. exit(1);
  948. }
  949. cl_block () /* table clear for block compress */
  950. {
  951. long rat;
  952. checkpoint = in_count + CHECK_GAP;
  953. #ifdef DEBUG
  954. if ( debug ) {
  955. fprintf ( stderr, "count: %ld, ratio: ", in_count );
  956. prratio ( stderr, in_count, bytes_out );
  957. fprintf ( stderr, "\n");
  958. }
  959. #endif /* DEBUG */
  960. if (in_count > 0x007fffff) { /* shift will overflow */
  961. rat = bytes_out >> 8;
  962. if (rat == 0) /* Don't divide by zero */
  963. rat = 0x7fffffff;
  964. else
  965. rat = in_count / rat;
  966. } else
  967. rat = (in_count << 8) / bytes_out; /* 8 fractional bits */
  968. if (rat > ratio)
  969. ratio = rat;
  970. else {
  971. ratio = 0;
  972. #ifdef DEBUG
  973. if (verbose)
  974. dump_tab(); /* dump string table */
  975. #endif
  976. cl_hash((count_int)hsize);
  977. free_ent = FIRST;
  978. clear_flg = 1;
  979. output((code_int)CLEAR);
  980. #ifdef DEBUG
  981. if (debug)
  982. fprintf(stderr, "clear\n");
  983. #endif /* DEBUG */
  984. }
  985. }
  986. cl_hash(hsize) /* reset code table */
  987. count_int hsize;
  988. {
  989. count_int *htab_p = htab+hsize;
  990. long i;
  991. long m1 = -1;
  992. i = hsize - 16;
  993. do { /* might use Sys V memset(3) here */
  994. *(htab_p-16) = m1;
  995. *(htab_p-15) = m1;
  996. *(htab_p-14) = m1;
  997. *(htab_p-13) = m1;
  998. *(htab_p-12) = m1;
  999. *(htab_p-11) = m1;
  1000. *(htab_p-10) = m1;
  1001. *(htab_p-9) = m1;
  1002. *(htab_p-8) = m1;
  1003. *(htab_p-7) = m1;
  1004. *(htab_p-6) = m1;
  1005. *(htab_p-5) = m1;
  1006. *(htab_p-4) = m1;
  1007. *(htab_p-3) = m1;
  1008. *(htab_p-2) = m1;
  1009. *(htab_p-1) = m1;
  1010. htab_p -= 16;
  1011. } while ((i -= 16) >= 0);
  1012. for ( i += 16; i > 0; i-- )
  1013. *--htab_p = m1;
  1014. }
  1015. prratio(stream, num, den)
  1016. FILE *stream;
  1017. long num, den;
  1018. {
  1019. int q; /* Doesn't need to be long */
  1020. if(num > 214748L) /* 2147483647/10000 */
  1021. q = num / (den / 10000L);
  1022. else
  1023. q = 10000L * num / den; /* Long calculations, though */
  1024. if (q < 0) {
  1025. putc('-', stream);
  1026. q = -q;
  1027. }
  1028. fprintf(stream, "%d.%02d%%", q / 100, q % 100);
  1029. }
  1030. version()
  1031. {
  1032. fprintf(stderr, "%s\n", rcs_ident);
  1033. fprintf(stderr, "Options: ");
  1034. #ifdef DEBUG
  1035. fprintf(stderr, "DEBUG, ");
  1036. #endif
  1037. #ifdef BSD4_2
  1038. fprintf(stderr, "BSD4_2, ");
  1039. #endif
  1040. fprintf(stderr, "BITS = %d\n", BITS);
  1041. }
  1042. /*
  1043. * The revision-history novel:
  1044. *
  1045. * $Header: compress.c,v 4.0 85/07/30 12:50:00 joe Release $
  1046. * $Log: compress.c,v $
  1047. * Revision 4.0 85/07/30 12:50:00 joe
  1048. * Removed ferror() calls in output routine on every output except first.
  1049. * Prepared for release to the world.
  1050. *
  1051. * Revision 3.6 85/07/04 01:22:21 joe
  1052. * Remove much wasted storage by overlaying hash table with the tables
  1053. * used by decompress: tab_suffix[1<<BITS], stack[8000]. Updated USERMEM
  1054. * computations. Fixed dump_tab() DEBUG routine.
  1055. *
  1056. * Revision 3.5 85/06/30 20:47:21 jaw
  1057. * Change hash function to use exclusive-or. Rip out hash cache. These
  1058. * speedups render the megamemory version defunct, for now. Make decoder
  1059. * stack global. Parts of the RCS trunks 2.7, 2.6, and 2.1 no longer apply.
  1060. *
  1061. * Revision 3.4 85/06/27 12:00:00 ken
  1062. * Get rid of all floating-point calculations by doing all compression ratio
  1063. * calculations in fixed point.
  1064. *
  1065. * Revision 3.3 85/06/24 21:53:24 joe
  1066. * Incorporate portability suggestion for M_XENIX. Got rid of text on #else
  1067. * and #endif lines. Cleaned up #ifdefs for vax and interdata.
  1068. *
  1069. * Revision 3.2 85/06/06 21:53:24 jaw
  1070. * Incorporate portability suggestions for Z8000, IBM PC/XT from mailing list.
  1071. * Default to "quiet" output (no compression statistics).
  1072. *
  1073. * Revision 3.1 85/05/12 18:56:13 jaw
  1074. * Integrate decompress() stack speedups (from early pointer mods by McKie).
  1075. * Repair multi-file USERMEM gaffe. Unify 'force' flags to mimic semantics
  1076. * of SVR2 'pack'. Streamline block-compress table clear logic. Increase
  1077. * output byte count by magic number size.
  1078. *
  1079. * Revision 3.0 84/11/27 11:50:00 petsd!joe
  1080. * Set HSIZE depending on BITS. Set BITS depending on USERMEM. Unrolled
  1081. * loops in clear routines. Added "-C" flag for 2.0 compatibility. Used
  1082. * unsigned compares on Perkin-Elmer. Fixed foreground check.
  1083. *
  1084. * Revision 2.7 84/11/16 19:35:39 ames!jaw
  1085. * Cache common hash codes based on input statistics; this improves
  1086. * performance for low-density raster images. Pass on #ifdef bundle
  1087. * from Turkowski.
  1088. *
  1089. * Revision 2.6 84/11/05 19:18:21 ames!jaw
  1090. * Vary size of hash tables to reduce time for small files.
  1091. * Tune PDP-11 hash function.
  1092. *
  1093. * Revision 2.5 84/10/30 20:15:14 ames!jaw
  1094. * Junk chaining; replace with the simpler (and, on the VAX, faster)
  1095. * double hashing, discussed within. Make block compression standard.
  1096. *
  1097. * Revision 2.4 84/10/16 11:11:11 ames!jaw
  1098. * Introduce adaptive reset for block compression, to boost the rate
  1099. * another several percent. (See mailing list notes.)
  1100. *
  1101. * Revision 2.3 84/09/22 22:00:00 petsd!joe
  1102. * Implemented "-B" block compress. Implemented REVERSE sorting of tab_next.
  1103. * Bug fix for last bits. Changed fwrite to putchar loop everywhere.
  1104. *
  1105. * Revision 2.2 84/09/18 14:12:21 ames!jaw
  1106. * Fold in news changes, small machine typedef from thomas,
  1107. * #ifdef interdata from joe.
  1108. *
  1109. * Revision 2.1 84/09/10 12:34:56 ames!jaw
  1110. * Configured fast table lookup for 32-bit machines.
  1111. * This cuts user time in half for b <= FBITS, and is useful for news batching
  1112. * from VAX to PDP sites. Also sped up decompress() [fwrite->putc] and
  1113. * added signal catcher [plus beef in writeerr()] to delete effluvia.
  1114. *
  1115. * Revision 2.0 84/08/28 22:00:00 petsd!joe
  1116. * Add check for foreground before prompting user. Insert maxbits into
  1117. * compressed file. Force file being uncompressed to end with ".Z".
  1118. * Added "-c" flag and "zcat". Prepared for release.
  1119. *
  1120. * Revision 1.10 84/08/24 18:28:00 turtlevax!ken
  1121. * Will only compress regular files (no directories), added a magic number
  1122. * header (plus an undocumented -n flag to handle old files without headers),
  1123. * added -f flag to force overwriting of possibly existing destination file,
  1124. * otherwise the user is prompted for a response. Will tack on a .Z to a
  1125. * filename if it doesn't have one when decompressing. Will only replace
  1126. * file if it was compressed.
  1127. *
  1128. * Revision 1.9 84/08/16 17:28:00 turtlevax!ken
  1129. * Removed scanargs(), getopt(), added .Z extension and unlimited number of
  1130. * filenames to compress. Flags may be clustered (-Ddvb12) or separated
  1131. * (-D -d -v -b 12), or combination thereof. Modes and other status is
  1132. * copied with copystat(). -O bug for 4.2 seems to have disappeared with
  1133. * 1.8.
  1134. *
  1135. * Revision 1.8 84/08/09 23:15:00 joe
  1136. * Made it compatible with vax version, installed jim's fixes/enhancements
  1137. *
  1138. * Revision 1.6 84/08/01 22:08:00 joe
  1139. * Sped up algorithm significantly by sorting the compress chain.
  1140. *
  1141. * Revision 1.5 84/07/13 13:11:00 srd
  1142. * Added C version of vax asm routines. Changed structure to arrays to
  1143. * save much memory. Do unsigned compares where possible (faster on
  1144. * Perkin-Elmer)
  1145. *
  1146. * Revision 1.4 84/07/05 03:11:11 thomas
  1147. * Clean up the code a little and lint it. (Lint complains about all
  1148. * the regs used in the asm, but I'm not going to "fix" this.)
  1149. *
  1150. * Revision 1.3 84/07/05 02:06:54 thomas
  1151. * Minor fixes.
  1152. *
  1153. * Revision 1.2 84/07/05 00:27:27 thomas
  1154. * Add variable bit length output.
  1155. */