-
Notifications
You must be signed in to change notification settings - Fork 0
/
minipack.ts
80 lines (66 loc) · 1.87 KB
/
minipack.ts
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
import {u8Encode, u8Decode} from "./text.ts";
const sizeName = 1;
const sizeBody = 4;
/**
* Simple name and data pair.
*/
export interface DataMap{
name: string;
body: Uint8Array;
}
/**
* Concatenate files with "minipack" format.
* @see https://deno.land/x/simple_utility#minipack
* @example
* ```ts
* const files = [{
* name: "foo.txt",
* body: await Deno.readFile("./foo.txt")
* }];
* const encode = minipackEncode(files);
* const decode = minipackDecode(encode);
* ```
*/
export function minipackEncode(files:DataMap[]):Uint8Array{
const archive = new Uint8Array(files.reduce((size, {name, body}) => size + sizeName + sizeBody + u8Encode(name).byteLength + body.byteLength, 0));
let i = 0;
for(const {name, body} of files){
const u8name = u8Encode(name);
new DataView(archive.buffer, i).setUint8(0, u8name.byteLength);
i += sizeName;
new DataView(archive.buffer, i).setUint32(0, body.byteLength);
i += sizeBody;
archive.set(u8name, i);
i += u8name.byteLength;
archive.set(body, i);
i += body.byteLength;
}
return archive;
}
/**
* Decode binary of "minipack" format.
* @see https://deno.land/x/simple_utility#minipack
* @example
* ```ts
* const files = [{
* name: "foo.txt",
* body: await Deno.readFile("./foo.txt")
* }];
* const encode = minipackEncode(files);
* const decode = minipackDecode(encode);
* ```
*/
export function minipackDecode(archive:Uint8Array):DataMap[]{
const files:DataMap[] = [];
for(let i = 0; i < archive.byteLength;){
const ns = new DataView(archive.buffer, i).getUint8(0);
i += sizeName;
const bs = new DataView(archive.buffer, i).getUint32(0);
i += sizeBody;
files.push({
name: u8Decode(archive.subarray(i, i += ns)),
body: archive.slice(i, i += bs)
});
}
return files;
}