-
Notifications
You must be signed in to change notification settings - Fork 128
/
archive.d
3639 lines (3149 loc) · 114 KB
/
archive.d
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/++
Provides LZMA (aka .xz), gzip (.gz) and .tar file read-only support.
Combine to read .tar.xz and .tar.gz files, or use in conjunction with
other libraries to read other kinds of files.
Also has a custom archive called arcz read and write support.
It is designed to efficiently pack and randomly access large
numbers of similar files. Unlike .zip files, it will do
cross-file compression (meaning it can significantly shrink
archives with several small but similar files), and unlike
tar.gz files, it supports random access without decompressing
the whole archive to get an individual file. It is designed
for large numbers of small, similar files.
History:
tar code (and arsd module formed) originally written December 2019 to support my d_android library downloader. It was added to dub in March 2020 (dub v7.0).
The LZMA code is a D port of Igor Pavlov's LzmaDec.h, written in 2017 with contributions by Lasse Collin. It was ported to D by ketmar some time after that and included in the original version of `arsd.archive` in the first December 2019 release.
The arcz code was written by ketmar in 2016 and added to arsd.archive in March 2020.
A number of improvements were made with the help of Steven Schveighoffer on March 22, 2023.
`arsd.archive` was changed to require [arsd.core] on March 23, 2023 (dub v11.0). Previously, it was a standalone module. It uses arsd.core's exception helpers only at this time and you could turn them back into plain (though uninformative) D base `Exception` instances to remove the dependency if you wanted to keep the file independent.
+/
module arsd.archive;
import arsd.core;
version(WithoutLzmaDecoder) {} else
version=WithLzmaDecoder;
version(WithoutArczCode) {} else
version=WithArczCode;
/+
/++
Reads a tar file and passes the chunks to your handler. Use it like:
TarFile f = TarFile("filename.tar");
foreach(part; f) {
if(part.isNewFile) {
}
}
FIXME not implemented
+/
struct TarFile {
this(string filename) {
}
}
+/
inout(char)[] upToZero(inout(char)[] a) {
int i = 0;
while(i < a.length && a[i]) i++;
return a[0 .. i];
}
/++
A header of a file in the archive. This represents the
binary format of the header block.
+/
align(512)
struct TarFileHeader {
align(1):
char[100] fileName_ = 0;
char[8] fileMode_ = 0;
char[8] ownerUid_ = 0;
char[8] ownerGid_ = 0;
char[12] size_ = 0; // in octal
char[12] mtime_ = 0; // octal unix timestamp
char[8] checksum_ = 0; // right?????
char[1] fileType_ = 0; // hard link, soft link, etc
char[100] linkFileName_ = 0;
char[6] ustarMagic_ = 0; // if "ustar\0", remaining fields are set
char[2] ustarVersion_ = 0;
char[32] ownerName_ = 0;
char[32] groupName_ = 0;
char[8] deviceMajorNumber_ = 0;
char[8] deviceMinorNumber_ = 0;
char[155] filenamePrefix_ = 0;
/// Returns the filename. You should cache the return value as long as TarFileHeader is in scope (it returns a slice after calling strlen)
const(char)[] filename() {
import core.stdc.string;
if(filenamePrefix_[0])
return upToZero(filenamePrefix_[]) ~ upToZero(fileName_[]);
return upToZero(fileName_[]);
}
/++
Returns the target of a symlink or hardlink. Remember, this returns a slice of the TarFileHeader structure, so once it goes out of scope, this slice will be dangling!
History:
Added March 24, 2023 (dub v11.0)
+/
const(char)[] linkFileName() {
return upToZero(linkFileName_[]);
}
///
ulong size() {
import core.stdc.stdlib;
return strtoul(size_.ptr, null, 8);
}
///
TarFileType type() {
if(fileType_[0] == 0)
return TarFileType.normal;
else
return cast(TarFileType) (fileType_[0] - '0');
}
///
uint mode() {
import core.stdc.stdlib;
return cast(uint) strtoul(fileMode_.ptr, null, 8);
}
}
/// There's other types but this is all I care about. You can still detect the char by `((cast(char) type) + '0')`
enum TarFileType {
normal = 0, ///
hardLink = 1, ///
symLink = 2, ///
characterSpecial = 3, ///
blockSpecial = 4, ///
directory = 5, ///
fifo = 6 ///
}
/++
Low level tar file processor. You must pass it a
TarFileHeader buffer as well as a size_t for context.
Both must be initialized to all zeroes on first call,
then not modified in between calls.
Each call must populate the dataBuffer with 512 bytes.
returns true if still work to do.
Please note that it currently only passes regular files, hard and soft links, and directories to your handler.
History:
[TarFileType.symLink] and [TarFileType.hardLink] used to be skipped by this function. On March 24, 2023, it was changed to send them to your `handleData` delegate too. The `data` argument to your handler will have the target of the link. Check `header.type` to know if it is a hard link, symbolic link, directory, normal file, or other special type (which are still currently skipped, but future proof yourself by either skipping or handling them now).
+/
bool processTar(
TarFileHeader* header,
long* bytesRemainingOnCurrentFile,
const(ubyte)[] dataBuffer,
scope void delegate(TarFileHeader* header, bool isNewFile, bool fileFinished, const(ubyte)[] data) handleData
)
{
assert(dataBuffer.length == 512);
assert(bytesRemainingOnCurrentFile !is null);
assert(header !is null);
if(*bytesRemainingOnCurrentFile) {
bool isNew = *bytesRemainingOnCurrentFile == header.size();
if(*bytesRemainingOnCurrentFile <= 512) {
handleData(header, isNew, true, dataBuffer[0 .. cast(size_t) *bytesRemainingOnCurrentFile]);
*bytesRemainingOnCurrentFile = 0;
} else {
handleData(header, isNew, false, dataBuffer[]);
*bytesRemainingOnCurrentFile -= 512;
}
} else {
*header = *(cast(TarFileHeader*) dataBuffer.ptr);
auto s = header.size();
*bytesRemainingOnCurrentFile = s;
if(header.type() == TarFileType.directory)
handleData(header, true, false, null);
if(header.type() == TarFileType.hardLink || header.type() == TarFileType.symLink)
handleData(header, true, true, cast(ubyte[]) header.linkFileName());
if(s == 0 && header.type == TarFileType.normal)
return false;
}
return true;
}
///
unittest {
/+
void main() {
TarFileHeader tfh;
long size;
import std.stdio;
ubyte[512] buffer;
foreach(chunk; File("/home/me/test/pl.tar", "r").byChunk(buffer[])) {
processTar(&tfh, &size, buffer[],
(header, isNewFile, fileFinished, data) {
if(isNewFile)
writeln("**** " , header.filename, " ", header.size);
write(cast(string) data);
if(fileFinished)
writeln("+++++++++++++++");
});
}
}
main();
+/
}
// Advances data up to the end of the vla
ulong readVla(ref const(ubyte)[] data) {
ulong n = 0;
int i = 0;
while (data[0] & 0x80) {
ubyte b = data[0];
data = data[1 .. $];
assert(b != 0);
if(b == 0) return 0;
n |= (ulong)(b & 0x7F) << (i * 7);
i++;
}
ubyte b = data[0];
data = data[1 .. $];
n |= (ulong)(b & 0x7F) << (i * 7);
return n;
}
/++
decompressLzma lzma (.xz file) decoder/decompressor that works by passed functions. Can be used as a higher-level alternative to [XzDecoder]. decompressGzip is gzip (.gz file) decoder/decompresser) that works by passed functions. Can be used as an alternative to [std.zip], while using the same underlying zlib library.
Params:
chunkReceiver = a function that receives chunks of uncompressed data and processes them. Note that the chunk you receive will be overwritten once your function returns, so make sure you write it to a file or copy it to an outside array if you want to keep the data
bufferFiller = a function that fills the provided buffer as much as you can, then returns the slice of the buffer you actually filled.
chunkBuffer = an optional parameter providing memory that will be used to buffer uncompressed data chunks. If you pass `null`, it will allocate one for you. Any data in the buffer will be immediately overwritten.
inputBuffer = an optional parameter providing memory that will hold compressed input data. If you pass `null`, it will allocate one for you. You should NOT populate this buffer with any data; it will be immediately overwritten upon calling this function. The `inputBuffer` must be at least 64 bytes in size.
allowPartialChunks = can be set to true if you want `chunkReceiver` to be called as soon as possible, even if it is only partially full before the end of the input stream. The default is to fill the input buffer for every call to `chunkReceiver` except the last which has remainder data from the input stream.
History:
Added March 24, 2023 (dub v11.0)
On October 25, 2024, the implementation got a major fix - it can read multiple blocks off the xz file now, were as before it would stop at the first one. This changed the requirement of the input buffer minimum size from 32 to 64 bytes (but it is always better to go more, I recommend 32 KB).
+/
version(WithLzmaDecoder)
void decompressLzma(scope void delegate(in ubyte[] chunk) chunkReceiver, scope ubyte[] delegate(ubyte[] buffer) bufferFiller, ubyte[] chunkBuffer = null, ubyte[] inputBuffer = null, bool allowPartialChunks = false) @trusted {
if(chunkBuffer is null)
chunkBuffer = new ubyte[](1024 * 32);
if(inputBuffer is null)
inputBuffer = new ubyte[](1024 * 32);
assert(inputBuffer.length >= 64);
bool isStartOfFile = true;
const(ubyte)[] compressedData = bufferFiller(inputBuffer[]);
XzDecoder decoder = XzDecoder(compressedData);
compressedData = decoder.unprocessed;
auto usableChunkBuffer = chunkBuffer;
while(!decoder.finished) {
auto newChunk = decoder.processData(usableChunkBuffer, compressedData);
auto chunk = chunkBuffer[0 .. (newChunk.ptr - chunkBuffer.ptr) + newChunk.length];
if(chunk.length && (decoder.finished || allowPartialChunks || chunk.length == chunkBuffer.length)) {
chunkReceiver(chunk);
usableChunkBuffer = chunkBuffer;
} else if(!decoder.finished) {
// if we're here we got a partial chunk
usableChunkBuffer = chunkBuffer[chunk.length .. $];
}
if(decoder.needsMoreData) {
import core.stdc.string;
memmove(inputBuffer.ptr, decoder.unprocessed.ptr, decoder.unprocessed.length);
auto newlyRead = bufferFiller(inputBuffer[decoder.unprocessed.length .. $]);
assert(newlyRead.ptr >= inputBuffer.ptr && newlyRead.ptr < inputBuffer.ptr + inputBuffer.length);
compressedData = inputBuffer[0 .. decoder.unprocessed.length + newlyRead.length];
} else {
compressedData = decoder.unprocessed;
}
}
}
/// ditto
void decompressGzip(scope void delegate(in ubyte[] chunk) chunkReceiver, scope ubyte[] delegate(ubyte[] buffer) bufferFiller, ubyte[] chunkBuffer = null, ubyte[] inputBuffer = null, bool allowPartialChunks = false) @trusted {
import etc.c.zlib;
if(chunkBuffer is null)
chunkBuffer = new ubyte[](1024 * 32);
if(inputBuffer is null)
inputBuffer = new ubyte[](1024 * 32);
const(ubyte)[] compressedData = bufferFiller(inputBuffer[]);
z_stream zs;
scope(exit)
inflateEnd(&zs); // can return Z_STREAM_ERROR if state inconsistent
int windowBits = 15 + 32; // determine header from data
int err = inflateInit2(&zs, 15 + 32); // determine header from data
if(err)
throw ArsdException!"zlib"(err, zs.msg[0 .. 80].upToZero.idup); // FIXME: the 80 limit is arbitrary
// zs.msg is also an error message string
zs.next_in = compressedData.ptr;
zs.avail_in = cast(uint) compressedData.length;
while(true) {
zs.next_out = chunkBuffer.ptr;
zs.avail_out = cast(uint) chunkBuffer.length;
fill_more_chunk:
err = inflate(&zs, Z_NO_FLUSH);
if(err == Z_OK || err == Z_STREAM_END || err == Z_BUF_ERROR) {
import core.stdc.string;
auto decompressed = chunkBuffer[0 .. chunkBuffer.length - zs.avail_out];
// if the buffer is full, we always send a chunk.
// partial chunks can be enabled, but we still will never send an empty chunk
// if we're at the end of a stream, we always send the final chunk
if(zs.avail_out == 0 || ((err == Z_STREAM_END || allowPartialChunks) && decompressed.length)) {
chunkReceiver(decompressed);
} else if(err != Z_STREAM_END) {
// need more data to fill the next chunk
if(zs.avail_in) {
memmove(inputBuffer.ptr, zs.next_in, zs.avail_in);
}
auto newlyRead = bufferFiller(inputBuffer[zs.avail_in .. $ - zs.avail_in]);
assert(newlyRead.ptr >= inputBuffer.ptr && newlyRead.ptr < inputBuffer.ptr + inputBuffer.length);
zs.next_in = inputBuffer.ptr;
zs.avail_in = cast(int) (zs.avail_in + newlyRead.length);
if(zs.avail_out)
goto fill_more_chunk;
} else {
assert(0, "progress impossible; your input buffer of compressed data might be too small");
}
if(err == Z_STREAM_END)
break;
} else {
throw ArsdException!"zlib"(err, zs.msg[0 .. 80].upToZero.idup); // FIXME: the 80 limit is arbitrary
}
}
}
/// [decompressLzma] and [processTar] can be used together like this:
unittest {
/+
import arsd.archive;
void main() {
import std.stdio;
auto file = File("test.tar.xz");
TarFileHeader tfh;
long size;
ubyte[512] tarBuffer;
decompressLzma(
(in ubyte[] chunk) => cast(void) processTar(&tfh, &size, chunk,
(header, isNewFile, fileFinished, data) {
if(isNewFile)
writeln("**** " , header.filename, " ", header.size);
//write(cast(string) data);
if(fileFinished)
writeln("+++++++++++++++");
}),
(ubyte[] buffer) => file.rawRead(buffer),
tarBuffer[]
);
}
+/
}
/++
A simple .xz file decoder.
See the constructor and [processData] docs for details.
You might prefer using [decompressLzma] for a higher-level api.
FIXME: it doesn't implement very many checks, instead
assuming things are what it expects. Don't use this without
assertions enabled!
+/
version(WithLzmaDecoder)
struct XzDecoder {
/++
Start decoding by feeding it some initial data. You must
send it at least enough bytes for the header (> 16 bytes prolly);
try to send it a reasonably sized chunk.
It sets `this.unprocessed` to be a slice of the *tail* of the `initialData`
member, indicating leftover data after parsing the header. You will need to
pass this to [processData] at least once to start decoding the data left over
after the header. See [processData] for more information.
+/
this(const(ubyte)[] initialData) {
ubyte[6] magic;
magic[] = initialData[0 .. magic.length];
initialData = initialData[magic.length .. $];
if(cast(string) magic != "\xFD7zXZ\0")
throw new Exception("not an xz file");
ubyte[2] streamFlags = initialData[0 .. 2];
initialData = initialData[2 .. $];
// size of the check at the end in the footer. im just ignoring tbh
checkSize = streamFlags[1] == 0 ? 0 : (4 << ((streamFlags[1]-1) / 3));
//uint crc32 = initialData[0 .. 4]; // FIXME just cast it. this is the crc of the flags.
initialData = initialData[4 .. $];
state = State.readingHeader;
readBlockHeader(initialData);
}
private enum State {
readingHeader,
readingData,
readingFooter,
}
private State state;
// returns true if it successfully read it, false if it needs more data
private bool readBlockHeader(const(ubyte)[] initialData) {
// now we are into an xz block...
if(initialData.length == 0) {
unprocessed = initialData;
needsMoreData_ = true;
finished_ = false;
return false;
}
if(initialData[0] == 0) {
// this is actually an index and a footer...
// we could process it but this also really marks us being done!
// FIXME: should actually pull the data out and finish it off
// see Index records etc at https://tukaani.org/xz/xz-file-format.txt
unprocessed = null;
finished_ = true;
needsMoreData_ = false;
return true;
}
int blockHeaderSize = (initialData[0] + 1) * 4;
auto first = initialData.ptr;
if(blockHeaderSize > initialData.length) {
unprocessed = initialData;
needsMoreData_ = true;
finished_ = false;
return false;
}
auto srcPostHeader = initialData[blockHeaderSize .. $];
initialData = initialData[1 .. $];
ubyte blockFlags = initialData[0];
initialData = initialData[1 .. $];
if(blockFlags & 0x40) {
compressedSize = readVla(initialData);
} else {
compressedSize = 0;
}
if(blockFlags & 0x80) {
uncompressedSize = readVla(initialData);
} else {
uncompressedSize = 0;
}
//import std.stdio; writeln(compressedSize , " compressed, expands to ", uncompressedSize);
auto filterCount = (blockFlags & 0b11) + 1;
ubyte props;
foreach(f; 0 .. filterCount) {
auto fid = readVla(initialData);
auto sz = readVla(initialData);
// import std.stdio; writefln("%02x %d", fid, sz);
assert(fid == 0x21);
assert(sz == 1);
props = initialData[0];
initialData = initialData[1 .. $];
}
// writeln(initialData.ptr);
// writeln(srcPostHeader.ptr);
// there should be some padding to a multiple of 4...
// three bytes of zeroes given the assumptions here
assert(blockHeaderSize >= 4);
long expectedRemainder = cast(long) blockHeaderSize - 4;
expectedRemainder -= initialData.ptr - first;
assert(expectedRemainder >= 0);
while(expectedRemainder) {
expectedRemainder--;
if(initialData[0] != 0)
throw new Exception("non-zero where padding byte expected in xz file");
initialData = initialData[1 .. $];
}
// and then a header crc
initialData = initialData[4 .. $]; // skip header crc
assert(initialData.ptr is srcPostHeader.ptr);
// skip unknown header bytes
while(initialData.ptr < srcPostHeader.ptr) {
initialData = initialData[1 .. $];
}
// should finally be at compressed data...
//writeln(compressedSize);
//writeln(uncompressedSize);
if(Lzma2Dec_Allocate(&lzmaDecoder, props) != SRes.OK) {
assert(0);
}
Lzma2Dec_Init(&lzmaDecoder);
unprocessed = initialData;
state = State.readingData;
return true;
}
private bool readBlockFooter(const(ubyte)[] data) {
// skip block padding
while(data.length && data[0] == 0) {
data = data[1 .. $];
}
if(data.length < checkSize) {
unprocessed = data;
finished_ = false;
needsMoreData_ = true;
return false;
}
// skip the check
data = data[checkSize .. $];
state = State.readingHeader;
return readBlockHeader(data);
//return true;
}
~this() {
LzmaDec_FreeProbs(&lzmaDecoder.decoder);
}
/++
Continues an in-progress decompression of the `src` data, putting it into the `dest` buffer.
The `src` data must be at least 20 bytes long, but I'd recommend making it at larger.
Returns the slice of the head of the `dest` buffer actually filled, then updates the following
member variables of `XzDecoder`:
$(LIST
* [finished] will be `true` if the compressed data has been completely decompressed.
* [needsMoreData] will be `true` if more src data was needed to fill the `dest` buffer. Note that you can also check this from the return value; if the return value's length is less than the destination buffer's length and the decoder is not finished, that means you needed more data to fill it.
* And very importantly, [unprocessed] will contain a slice of the $(I tail of the `src` buffer) holding thus-far unprocessed data from the source buffer. This will almost always be set unless `dest` was big enough to hold the entire remaining uncompressed data.
)
This function will not modify the `src` buffer in any way. This is why the [unprocessed] member holds a slice to its tail - it is your own responsibility to decide how to proceed.
If your `src` buffer contains the entire compressed file, you can pass `unprocessed` in a loop until finished:
---
static import std.file;
auto compressedData = cast(immutable(ubyte)[]) std.file.read("file.xz"); // load it all into memory at once
XzDecoder decoder = XzDecoder(compressedData);
auto buffer = new ubyte[](4096); // to hold chunks of uncompressed data
ubyte[] wholeUncompressedFile;
while(!decoder.finished) {
// it returns the slice of buffer with new data, so we can append that
// to reconstruct the whole file. and then it sets `decoded.unprocessed` to
// a slice of what is left out of the source file to continue processing in
// the next iteration of the loop.
wholeUncompressedFile ~= decoder.processData(buffer, decoder.unprocessed);
}
// wholeUncompressedFile is now fully populated
---
If you are reading from a file or some other streaming source, you may need to either move the unprocessed data back to the beginning of the buffer then load more into it, or copy it to a new, larger buffer and append more data then.
---
import std.stdio;
auto file = File("file.xz");
ubyte[] compressedDataBuffer = new ubyte[](1024 * 32);
// read the first chunk. all modifications will be done through `compressedDataBuffer`
// so we can make this part const for easier assignment to the slices `decoder.unprocessed` will hold
const(ubyte)[] compressedData = file.rawRead(compressedDataBuffer);
XzDecoder decoder = XzDecoder(compressedData);
// need to keep what was unprocessed after construction
compressedData = decoder.unprocessed;
auto buffer = new ubyte[](4096); // to hold chunks of uncompressed data
ubyte[] wholeUncompressedFile;
while(!decoder.finished) {
wholeUncompressedFile ~= decoder.processData(buffer, compressedData);
if(decoder.needsMoreData) {
// it needed more data to fill the buffer
// first, move the unprocessed data bask to the head
// you cannot necessarily use a D slice assign operator
// because the `unprocessed` is a slice of the `compressedDataBuffer`,
// meaning they might overlap. Instead, we'll use C's `memmove`
import core.stdc.string;
memmove(compressedDataBuffer.ptr, decoder.unprocessed.ptr, decoder.unprocessed.length);
// now we can read more data to fill in the tail of the buffer again
auto newlyRead = file.rawRead(compressedDataBuffer[decoder.unprocessed.length .. $]);
// the new compressed data ready to process is what we moved from before,
// now at the head of the buffer, plus what was just read, at the end of
// the same buffer
compressedData = compressedDataBuffer[0 .. decoder.unprocessed.length + newlyRead.length];
} else {
// otherwise, the output buffer was full, but there's probably
// still more unprocessed data. Set it to be used on the next
// loop iteration.
compressedData = decoder.unprocessed;
}
}
// wholeUncompressedFile is now fully populated
---
+/
ubyte[] processData(ubyte[] dest, const(ubyte)[] src) {
if(state == State.readingHeader) {
if(!readBlockHeader(src))
return dest[0 .. 0];
src = unprocessed;
}
size_t destLen = dest.length;
size_t srcLen = src.length;
ELzmaStatus status;
auto res = Lzma2Dec_DecodeToBuf(
&lzmaDecoder,
dest.ptr,
&destLen,
src.ptr,
&srcLen,
LZMA_FINISH_ANY,
&status
);
if(res != 0) {
throw ArsdException!"Lzma2Dec_DecodeToBuf"(res);
}
/+
import std.stdio;
writeln(res, " ", status);
writeln(srcLen);
writeln(destLen, ": ", cast(string) dest[0 .. destLen]);
+/
if(status == LZMA_STATUS_NEEDS_MORE_INPUT) {
unprocessed = src[srcLen .. $];
finished_ = false;
needsMoreData_ = true;
} else if(status == LZMA_STATUS_FINISHED_WITH_MARK || status == LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK) {
// this is the end of a block, but not necessarily the end of the file
state = State.readingFooter;
// the readBlockFooter function updates state, unprocessed, finished, and needs more data
readBlockFooter(src[srcLen .. $]);
} else if(status == LZMA_STATUS_NOT_FINISHED) {
unprocessed = src[srcLen .. $];
finished_ = false;
needsMoreData_ = false;
} else {
// wtf
throw ArsdException!"Unhandled LZMA_STATUS"(status);
}
return dest[0 .. destLen];
}
/++
Returns true after [processData] has finished decoding the compressed data.
+/
bool finished() {
return finished_;
}
/++
After calling [processData], this will return `true` if more data is required to fill
the destination buffer.
Please note that `needsMoreData` can return `false` before decompression is completely
[finished]; this would simply mean it satisfied the request to fill that one buffer.
In this case, you will want to concatenate [unprocessed] with new data, then call [processData]
again. Remember that [unprocessed] is a slice of the tail of the source buffer you passed to
`processData`, so if you want to reuse the same buffer, you may want to `memmove` it to the
head, then fill he tail again.
+/
bool needsMoreData() {
return needsMoreData_;
}
private bool finished_;
private bool needsMoreData_;
CLzma2Dec lzmaDecoder;
int checkSize;
ulong compressedSize; ///
ulong uncompressedSize; ///
const(ubyte)[] unprocessed; ///
}
///
/+
version(WithLzmaDecoder)
unittest {
void main() {
ubyte[512] dest; // into tar size chunks!
ubyte[1024] src;
import std.stdio;
//auto file = File("/home/me/test/amazing.txt.xz", "rb");
auto file = File("/home/me/Android/ldcdl/test.tar.xz", "rb");
auto bfr = file.rawRead(src[]);
XzDecoder xzd = XzDecoder(bfr);
// not necessarily set, don't rely on them
writeln(xzd.compressedSize, " / ", xzd.uncompressedSize);
// for tar
TarFileHeader tfh;
long size;
long sum = 0;
while(!xzd.finished) {
// as long as your are not finished, there is more work to do. But it doesn't
// necessarily need more data, so that is a separate check.
if(xzd.needsMoreData) {
// if it needs more data, append new stuff to the end of the buffer, after
// the existing unprocessed stuff. If your buffer is too small, you may be
// forced to grow it here, but anything >= 1 KB seems OK in my tests.
bfr = file.rawRead(src[bfr.length - xzd.unprocessed.length .. $]);
} else {
// otherwise, you want to continue working with existing unprocessed data
bfr = cast(ubyte[]) xzd.unprocessed;
}
//write(cast(string) xzd.processData(dest[], bfr));
auto buffer = xzd.processData(dest[], bfr);
// if the buffer is empty we are probably done
// or need more data, so continue the loop to evaluate.
if(buffer.length == 0)
continue;
// our tar code requires specifically 512 byte pieces
while(!xzd.finished && buffer.length != 512) {
// need more data hopefully
assert(xzd.needsMoreData);
// using the existing buffer...
bfr = file.rawRead(src[bfr.length - xzd.unprocessed.length .. $]);
auto nbuffer = xzd.processData(dest[buffer.length .. $], bfr);
buffer = dest[0 .. buffer.length + nbuffer.length];
}
sum += buffer.length;
// process the buffer through the tar file handler
processTar(&tfh, &size, buffer[],
(header, isNewFile, fileFinished, data) {
if(isNewFile)
writeln("**** " , header.filename, " ", header.size);
//write(cast(string) data);
if(fileFinished)
writeln("+++++++++++++++");
});
}
writeln(sum);
}
main();
}
+/
version(WithArczCode) {
/* The code in this section was originally written by Ketmar Dark for his arcz.d module. I modified it afterward. */
/** ARZ chunked archive format processor.
*
* This module provides `std.stdio.File`-like interface to ARZ archives.
*
* Copyright: Copyright Ketmar Dark, 2016
*
* License: Boost License 1.0
*/
// module iv.arcz;
// use Balz compressor if available
static if (__traits(compiles, { import iv.balz; })) enum arcz_has_balz = true; else enum arcz_has_balz = false;
static if (__traits(compiles, { import iv.zopfli; })) enum arcz_has_zopfli = true; else enum arcz_has_zopfli = false;
static if (arcz_has_balz) import iv.balz;
static if (arcz_has_zopfli) import iv.zopfli;
// comment this to free pakced chunk buffer right after using
// i.e. `AZFile` will allocate new block for each new chunk
//version = arcz_use_more_memory;
public import core.stdc.stdio : SEEK_SET, SEEK_CUR, SEEK_END;
// ////////////////////////////////////////////////////////////////////////// //
/// ARZ archive accessor. Use this to open ARZ archives, and open packed files from ARZ archives.
public struct ArzArchive {
private:
static assert(size_t.sizeof >= (void*).sizeof);
private import core.stdc.stdio : FILE, fopen, fclose, fread, fseek;
private import etc.c.zlib;
static struct ChunkInfo {
uint ofs; // offset in file
uint pksize; // packed chunk size (same as chunk size: chunk is unpacked)
}
static struct FileInfo {
string name;
uint chunk;
uint chunkofs; // offset of first file byte in unpacked chunk
uint size; // unpacked file size
}
static struct Nfo {
uint rc = 1; // refcounter
ChunkInfo[] chunks;
FileInfo[string] files;
uint chunkSize;
uint lastChunkSize;
bool useBalz;
FILE* afl; // archive file, we'll keep it opened
@disable this (this); // no copies!
static void decRef (size_t me) {
if (me) {
auto nfo = cast(Nfo*)me;
assert(nfo.rc);
if (--nfo.rc == 0) {
import core.memory : GC;
import core.stdc.stdlib : free;
if (nfo.afl !is null) fclose(nfo.afl);
nfo.chunks.destroy;
nfo.files.destroy;
nfo.afl = null;
GC.removeRange(cast(void*)nfo/*, Nfo.sizeof*/);
free(nfo);
debug(arcz_rc) { import core.stdc.stdio : printf; printf("Nfo %p freed\n", nfo); }
}
}
}
}
size_t nfop; // hide it from GC
private @property Nfo* nfo () { pragma(inline, true); return cast(Nfo*)nfop; }
void decRef () { pragma(inline, true); Nfo.decRef(nfop); nfop = 0; }
static uint readUint (FILE* fl) {
if (fl is null) throw new Exception("cannot read from closed file");
uint v;
if (fread(&v, 1, v.sizeof, fl) != v.sizeof) throw new Exception("file reading error");
version(BigEndian) {
import core.bitop : bswap;
v = bswap(v);
} else version(LittleEndian) {
// nothing to do
} else {
static assert(0, "wtf?!");
}
return v;
}
static uint readUbyte (FILE* fl) {
if (fl is null) throw new Exception("cannot read from closed file");
ubyte v;
if (fread(&v, 1, v.sizeof, fl) != v.sizeof) throw new Exception("file reading error");
return v;
}
static void readBuf (FILE* fl, void[] buf) {
if (buf.length > 0) {
if (fl is null) throw new Exception("cannot read from closed file");
if (fread(buf.ptr, 1, buf.length, fl) != buf.length) throw new Exception("file reading error");
}
}
static T* xalloc(T, bool clear=true) (uint mem) if (T.sizeof > 0) {
import core.exception : onOutOfMemoryError;
assert(mem != 0);
static if (clear) {
import core.stdc.stdlib : calloc;
auto res = calloc(mem, T.sizeof);
if (res is null) onOutOfMemoryError();
static if (is(T == struct)) {
import core.stdc.string : memcpy;
static immutable T i = T.init;
foreach (immutable idx; 0..mem) memcpy(res+idx, &i, T.sizeof);
}
debug(arcz_alloc) { import core.stdc.stdio : printf; printf("allocated %u bytes at %p\n", cast(uint)(mem*T.sizeof), res); }
return cast(T*)res;
} else {
import core.stdc.stdlib : malloc;
auto res = malloc(mem*T.sizeof);
if (res is null) onOutOfMemoryError();
static if (is(T == struct)) {
import core.stdc.string : memcpy;
static immutable T i = T.init;
foreach (immutable idx; 0..mem) memcpy(res+idx, &i, T.sizeof);
}
debug(arcz_alloc) { import core.stdc.stdio : printf; printf("allocated %u bytes at %p\n", cast(uint)(mem*T.sizeof), res); }
return cast(T*)res;
}
}
static void xfree(T) (T* ptr) {
if (ptr !is null) {
import core.stdc.stdlib : free;
debug(arcz_alloc) { import core.stdc.stdio : printf; printf("freing at %p\n", ptr); }
free(ptr);
}
}
static if (arcz_has_balz) static ubyte balzDictSize (uint blockSize) {
foreach (ubyte bits; Balz.MinDictBits..Balz.MaxDictBits+1) {