unbflz.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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. #include <u.h>
  10. #include <libc.h>
  11. #include <bio.h>
  12. void
  13. usage(void)
  14. {
  15. fprint(2, "usage: unbflz [file]\n");
  16. exits("usage");
  17. }
  18. int
  19. Bgetint(Biobuf *b)
  20. {
  21. uchar p[4];
  22. if(Bread(b, p, 4) != 4)
  23. sysfatal("short read");
  24. return (p[0]<<24)|(p[1]<<16)|(p[2]<<8)|p[3];
  25. }
  26. /*
  27. * memmove but make sure overlap works properly.
  28. */
  29. void
  30. copy(uchar *dst, uchar *src, int n)
  31. {
  32. while(n-- > 0)
  33. *dst++ = *src++;
  34. }
  35. void
  36. main(int argc, char **argv)
  37. {
  38. Biobuf *b, bin;
  39. char buf[5];
  40. uchar *data;
  41. ulong *blk, l;
  42. int nblk, mblk;
  43. int sum;
  44. int i, j, length, m, n, o;
  45. ARGBEGIN{
  46. default:
  47. usage();
  48. }ARGEND
  49. switch(argc){
  50. default:
  51. usage();
  52. case 0:
  53. Binit(&bin, 0, OREAD);
  54. b = &bin;
  55. break;
  56. case 1:
  57. if((b = Bopen(argv[0], OREAD)) == nil)
  58. sysfatal("open %s: %r", argv[0]);
  59. break;
  60. }
  61. if(Bread(b, buf, 4) != 4)
  62. sysfatal("short read");
  63. if(memcmp(buf, "BLZ\n", 4) != 0)
  64. sysfatal("bad header");
  65. length = Bgetint(b);
  66. data = malloc(length);
  67. if(data == nil)
  68. sysfatal("out of memory");
  69. sum = 0;
  70. nblk = 0;
  71. mblk = 0;
  72. blk = nil;
  73. while(sum < length){
  74. if(nblk>=mblk){
  75. mblk += 16384;
  76. blk = realloc(blk, (mblk+1)*sizeof(blk[0]));
  77. if(blk == nil)
  78. sysfatal("out of memory");
  79. }
  80. l = Bgetint(b);
  81. blk[nblk++] = l;
  82. if(l&(1<<31))
  83. l &= ~(1<<31);
  84. else
  85. blk[nblk++] = Bgetint(b);
  86. sum += l;
  87. }
  88. if(sum != length)
  89. sysfatal("bad compressed data %d %d", sum, length);
  90. i = 0;
  91. j = 0;
  92. while(i < length){
  93. assert(j < nblk);
  94. n = blk[j++];
  95. if(n&(1<<31)){
  96. n &= ~(1<<31);
  97. if((m=Bread(b, data+i, n)) != n)
  98. sysfatal("short read %d %d", n, m);
  99. }else{
  100. o = blk[j++];
  101. copy(data+i, data+o, n);
  102. }
  103. i += n;
  104. }
  105. write(1, data, length);
  106. exits(nil);
  107. }