-
Notifications
You must be signed in to change notification settings - Fork 36
/
key.ts
83 lines (75 loc) · 1.67 KB
/
key.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
81
82
83
import {Hash, parse as parseHash} from '../hash';
export function chunkDataKey(hash: Hash): string {
return `c/${hash}/d`;
}
export function chunkMetaKey(hash: Hash): string {
return `c/${hash}/m`;
}
export function chunkRefCountKey(hash: Hash): string {
return `c/${hash}/r`;
}
export function headKey(name: string): string {
return `h/${name}`;
}
export const enum KeyType {
ChunkData,
ChunkMeta,
ChunkRefCount,
Head,
}
export type Key =
| {
type: KeyType.ChunkData;
hash: Hash;
}
| {
type: KeyType.ChunkMeta;
hash: Hash;
}
| {
type: KeyType.ChunkRefCount;
hash: Hash;
}
| {
type: KeyType.Head;
name: string;
};
export function parse(key: string): Key {
const invalidKey = () => new Error(`Invalid key: '${key}'`);
const hash = () => parseHash(key.substring(2, key.length - 2));
// '/'
if (key.charCodeAt(1) === 47) {
switch (key.charCodeAt(0)) {
// c
case 99: {
if (key.length < 4 || key.charCodeAt(key.length - 2) !== 47) {
throw invalidKey();
}
switch (key.charCodeAt(key.length - 1)) {
case 100: // d
return {
type: KeyType.ChunkData,
hash: hash(),
};
case 109: // m
return {
type: KeyType.ChunkMeta,
hash: hash(),
};
case 114: // r
return {
type: KeyType.ChunkRefCount,
hash: hash(),
};
}
break;
}
case 104: // h
return {
type: KeyType.Head,
name: key.substring(2),
};
}
}
throw invalidKey();
}