-
Notifications
You must be signed in to change notification settings - Fork 221
Expand file tree
/
Copy pathbencode.factor
More file actions
59 lines (42 loc) · 1.33 KB
/
Copy pathbencode.factor
File metadata and controls
59 lines (42 loc) · 1.33 KB
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
USING: arrays assocs byte-arrays combinators io
io.encodings.binary io.streams.byte-array io.streams.string
kernel linked-assocs math math.parser sequences sequences.extras strings ;
IN: bencode
GENERIC: >bencode ( obj -- bencode )
M: integer >bencode
number>string "i" "e" surround ;
M: string >bencode
[ length number>string ":" ] keep 3append ;
M: byte-array >bencode "" like >bencode ;
M: sequence >bencode
[ >bencode ] map concat "l" "e" surround ;
M: assoc >bencode
[ [ >bencode ] bi@ append ] { } assoc>map concat
"d" "e" surround ;
DEFER: read-bencode
<PRIVATE
: read-integer ( -- obj )
"e" read-until CHAR: e assert= string>number ;
: read-list ( -- obj )
[ read-bencode ] loop>array ;
: read-dictionary ( -- obj )
[
read-bencode [ read-bencode 2array ] [ f ] if*
] loop>array >linked-hash ;
: read-string ( prefix -- obj )
":" read-until CHAR: : assert= swap prefix
string>number read "" like ;
PRIVATE>
: read-bencode ( -- obj )
read1 {
{ CHAR: i [ read-integer ] }
{ CHAR: l [ read-list ] }
{ CHAR: d [ read-dictionary ] }
{ CHAR: e [ f ] }
[ read-string ]
} case ;
GENERIC: bencode> ( bencode -- obj )
M: byte-array bencode>
binary [ read-bencode ] with-byte-reader ;
M: string bencode>
[ read-bencode ] with-string-reader ;