1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
|
module Zlib
class Deflate < ZStream
INVALID = -1
WindowEntry = Struct.new(:next, :prev, :hashval)
HashEntry = Struct.new(:first)
Match = Struct.new(:distance, :len)
WINSIZE = 32768
HASHMAX = 2039
MAXMATCH = 32
HASHCHARS = 3
MAXCODELEN = 16
CodeRecord = Struct.new(:code, :extra_bits, :range)
LEN_CODES = [
3, 4, 5, 6, 7, 8, 9, 10,
11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115,
131, 163, 195, 227, 258
].push(259).enum_with_index.to_enum(:each_cons, 2).map do |(l1, i), (l2, j)|
CodeRecord.new i + 257, i == 28 ? 0 : [i / 4 - 1, 0].max, l1...l2
end
DIST_CODES = [
1, 2, 3, 4, 5, 7, 9, 13,
17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073,
4097, 6145, 8193, 12289, 16385, 24577
].push(32769).enum_with_index.to_enum(:each_cons, 2).map do |(l1, i), (l2, j)|
CodeRecord.new i, [i / 2 - 1, 0].max, l1...l2
end
SYMLIMIT = 65536
SYMPFX_LITLEN = 0x00000000
SYMPFX_DIST = 0x40000000
SYMPFX_EXTRABITS = 0x80000000
SYMPFX_CODELEN = 0xC0000000
SYMPFX_MASK = 0xC0000000
SYM_EXTRABITS_MASK = 0x3C000000
SYM_EXTRABITS_SHIFT = 26
class HuffmanTree
attr_reader :codes, :lengths
def initialize
@codes = []
@lengths = []
end
end
def self.deflate data, level=nil
new.deflate data, level
end
def initialize level=DEFAULT_COMPRESSION, windowBits=MAX_WBITS, memlevel=nil, strategy=DEFAULT_STRATEGY
@zstring = ''
@header = false
@win = (0...WINSIZE).map { WindowEntry.new INVALID, INVALID, INVALID }
@hashtab = (0...HASHMAX).map { HashEntry.new INVALID }
@winpos = 0
@pending = 0.chr * HASHCHARS
@npending = 0
@data = 0.chr * WINSIZE
@nsyms = 0
@syms = [nil] * SYMLIMIT
@symstart = 0
lengths = [8] * 144 + [9] * 112 + [7] * 24 + [8] * 8
maxlen, codes = hufcodes lengths
@static_litlen = HuffmanTree.new
@static_litlen.codes.replace codes
@static_litlen.lengths.replace lengths
lengths = [5] * 30
maxlen, codes = hufcodes lengths
@static_dist = HuffmanTree.new
@static_dist.codes.replace codes
@static_dist.lengths.replace lengths
@output = BitWriter.new StringIO.new
end
def output
@output.io.string
end
def set_dictionary dict
@dict = dict
end
def params(*ignore)
end
def << data
@zstring << data
end
def finish
deflate '', FINISH
output
end
def lz77_hash data
(257 * data[0] + 263 * data[1] + 269 * data[2]) % HASHMAX
end
def lz77_advance c, hash
@win[@winpos].hashval = hash
@win[@winpos].prev = INVALID
off = @win[@winpos].next = @hashtab[hash].first
@hashtab[hash].first = @winpos
if off != INVALID
@win[off].prev = @winpos
end
@data[@winpos] = c
@winpos = (@winpos + 1) & (WINSIZE - 1)
end
def lz77_compress data, compress=true
len = data.length
charat = proc do |k|
k < 0 ? @data[(@winpos + k) & (WINSIZE - 1)] : data[k]
end
i = 0
temp = 0.chr * HASHCHARS
@npending.times do |i|
if len + @npending - i < HASHCHARS
(i...@npending).each { |j| @pending[j - i] = @pending[j] }
break
end
(0...HASHCHARS).each do |j|
temp[j] = i + j < @npending ? @pending[i + j] :
data[i + j - @npending]
end
lz77_advance temp[0], lz77_hash(temp)
end
@npending -= i
matches = []
defermatch = Match.new 0, 0
deferchr = 0
advance = 0
while len > 0
matches.clear
if compress && len >= HASHCHARS
hash = lz77_hash data
off = @hashtab[hash].first
while off != INVALID
distance = WINSIZE - (off + WINSIZE - @winpos) % WINSIZE
found = HASHCHARS.times do |i|
break true if charat[i] != charat[i - distance]
end
if found != true
matches << Match.new(distance, 3)
break if matches.length >= MAXMATCH
end
off = @win[off].next
end
else
hash = INVALID
end
if matches.empty?
if defermatch.len > 0
self.match defermatch.distance, defermatch.len
advance = defermatch.len - 1
defermatch.len = 0
else
self.literal data[0]
advance = 1
end
else
matchlen = HASHCHARS
while matchlen < len
still_matching = matches.select do |match|
charat[matchlen] == charat[matchlen - match.distance]
end
break if still_matching.empty?
matches = still_matching
matchlen += 1
end
matches[0].len = matchlen
if defermatch.len > 0
if matches[0].len > defermatch.len + 1
self.literal deferchr
defermatch = matches[0]
deferchr = data[0]
advance = 1
else
self.match defermatch.distance, defermatch.len
advance = defermatch.len - 1
defermatch.len = 0
end
else
defermatch = matches[0]
deferchr = data[0]
advance = 1
end
end
while advance > 0
if len >= HASHCHARS
lz77_advance data[0], lz77_hash(data)
else
@pending[@npending] = data[0]
@npending += 1
end
data.slice! 0, 1
len -= 1
advance -= 1
end
end
end
def deflate data, flush
unless @header
@header = true
level_flags = 2
header = ((DEFLATED + ((MAX_WBITS - 8) << 4)) << 8) | (level_flags << 6)
header |= PRESET_DICT if @dict
header += 31 - (header % 31)
outbits header >> 8, 8
outbits header & 0xff, 8
unless @zstring.empty?
data = @zstring + data
@zstring = ''
end
if @dict and data.length >= 3
dict = @dict + data[0, 3]
@dict.length.times do |i|
lz77_advance dict[0], lz77_hash(dict)
dict.slice! 0, 1
end
outbits [Checksum.adler32(@dict)].pack('V').unpack('N')[0], 32
end
end
lz77_compress data.dup
@checksum ||= 1
@checksum = Checksum.adler32(data, @checksum)
case flush
when NO_FLUSH
''
when PARTIAL_FLUSH, SYNC_FLUSH
raise NotImplementedError
when FULL_FLUSH
raise NotImplementedError
when FINISH
flushblock
pending = @output.instance_variable_get(:@have)
outbits 0, 8 - pending if pending != 0
outbits [@checksum].pack('V').unpack('N')[0], 32
output
when BLOCK
raise NotImplementedError
end
end
def hufcodes lengths
codes = [nil] * lengths.length
count = [0] * MAXCODELEN
startcode = count.dup
lengths.each { |l| count[l] += 1 }
maxlen = lengths.max
code = 0
(1...MAXCODELEN).each do |i|
startcode[i] = code
code += count[i]
maxlen = -1 if code > (1 << i)
code <<= 1
end
maxlen = -2 if code < (1 << MAXCODELEN)
lengths.length.times do |i|
code = startcode[lengths[i]]
startcode[lengths[i]] += 1
codes[i] = 0
lengths[i].times do |j|
codes[i] = (codes[i] << 1) | (code & 1)
code >>= 1
end
end
[maxlen, codes]
end
def literal c
outsym SYMPFX_LITLEN | c
end
def match distance, len
while len > 0
thislen = len > 260 ? 258 : len <= 258 ? len : len - 3
len -= thislen
code = LEN_CODES.find { |c| c.range === thislen }
outsym SYMPFX_LITLEN | code.code
if code.extra_bits > 0
outsym SYMPFX_EXTRABITS | (thislen - code.range.begin) |
(code.extra_bits << SYM_EXTRABITS_SHIFT)
end
code = DIST_CODES.find { |c| c.range === distance }
outsym SYMPFX_DIST | code.code
if code.extra_bits > 0
outsym SYMPFX_EXTRABITS | (distance - code.range.begin) |
(code.extra_bits << SYM_EXTRABITS_SHIFT)
end
end
end
def flushblock
outblock @nsyms, @nsyms
end
def outbits val, count
@output.write val, count
end
def writesym sym, huftrees
basesym = sym &~ SYMPFX_MASK
litlen, dist, codelen = huftrees
case sym & SYMPFX_MASK
when SYMPFX_LITLEN
outbits litlen.codes[basesym], litlen.lengths[basesym]
when SYMPFX_DIST
outbits dist.codes[basesym], dist.lengths[basesym]
when SYMPFX_CODELEN
outbits codelen.codes[basesym], codelen.lengths[basesym]
when SYMPFX_EXTRABITS
i = basesym >> SYM_EXTRABITS_SHIFT
basesym &= ~SYM_EXTRABITS_MASK
outbits basesym, i
end
end
def outsym sym
@syms[(@symstart + @nsyms) % SYMLIMIT] = sym
@nsyms += 1
chooseblock if @nsyms == SYMLIMIT
end
def outblock dynamic_len, static_len
@lastblock = true
dynamic = false
blklen = static_len
ht = [@static_litlen, @static_dist, nil]
bfinal = @lastblock ? 1 : 0
btype = dynamic ? 2 : 1
outbits bfinal, 1
outbits btype, 2
if dynamic
raise NotImplementedError
end
blklen.times do |i|
sym = @syms[(@symstart + i) % SYMLIMIT]
writesym sym, ht
end
writesym SYMPFX_LITLEN | 256, ht
@symstart = (@symstart + blklen) % SYMLIMIT
@nsyms -= blklen
end
LOG_2 = Math.log(2)
def log2(x)
(Math.log(x) / LOG_2).ceil * 8
end
def chooseblock
freqs1 = [0] * 286
freqs2 = [0] * 30
freqs1[256] = 1
longestlen = 0
total1 = 1
total2 = 0
bestlen = -1
bestvfm = 0
len = 300 * 8
@nsyms.times do |i|
sym = @syms[(@symstart + i) % SYMLIMIT]
if i > 0 && (sym & SYMPFX_MASK) == SYMPFX_LITLEN
vfm = i * 32768 / len
if bestlen < 0 || vfm > bestvfm
bestlen = i
bestvfm = vfm
end
longestlen = i
end
if (sym & SYMPFX_MASK) == SYMPFX_LITLEN
sym &= ~SYMPFX_MASK
len += freqs1[sym] * 8 * log2(freqs1[sym])
len -= total1 * approxlog2(total1)
freqs1[sym] += 1
total1 += 1
len -= freqs1[sym] * 8 * log2(freqs1[sym])
len += total1 * 8 * log2(total1)
elsif (sym & SYMPFX_MASK) == SYMPFX_DIST
sym &= ~SYMPFX_MASK
len += freqs2[sym] * 8 * log2(freqs2[sym])
len -= total2 * 8 * log2(total2)
freqs2[sym] += 1
total2 += 1
len -= freqs2[sym] * 8 * log2(freqs2[sym])
len += total2 * 8 * log2(total2)
elsif (sym & SYMPFX_MASK) == SYMPFX_EXTRABITS
len += 8 * ((sym &~ SYMPFX_MASK) >> SYM_EXTRABITS_SHIFT)
end
end
outblock bestlen, longestlen
end
end
end
|