compress.c 32 KB

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