factor/extra/bencode/bencode.factor

53 lines
1.2 KiB
Factor
Raw Normal View History

2016-05-10 00:36:19 -04:00
USING: arrays assocs combinators hashtables io
io.encodings.ascii io.encodings.string io.streams.string kernel
math math.parser sequences strings ;
IN: bencode
GENERIC: >bencode ( obj -- bencode )
M: integer >bencode
number>string "i" "e" surround ;
M: string >bencode
[ length number>string ":" ] keep 3append ;
M: sequence >bencode
[ >bencode ] map concat "l" "e" surround ;
M: assoc >bencode
[ [ >bencode ] bi@ append ] { } assoc>map concat
"d" "e" surround ;
<PRIVATE
DEFER: read-bencode
: read-integer ( -- obj )
2017-06-04 17:00:02 -04:00
"e" read-until char: e assert= string>number ;
2016-05-10 00:36:19 -04:00
: read-list ( -- obj )
[ read-bencode dup ] [ ] produce nip ;
: read-dictionary ( -- obj )
[
read-bencode [ read-bencode 2array ] [ f ] if* dup
] [ ] produce nip >hashtable ;
: read-string ( prefix -- obj )
2017-06-04 17:00:02 -04:00
":" read-until char: : assert= swap prefix
2016-05-10 00:36:19 -04:00
string>number read ascii decode ;
: read-bencode ( -- obj )
read1 {
2017-06-04 17:00:02 -04:00
{ char: i [ read-integer ] }
{ char: l [ read-list ] }
{ char: d [ read-dictionary ] }
{ char: e [ f ] }
2016-05-10 00:36:19 -04:00
[ read-string ]
} case ;
PRIVATE>
: bencode> ( bencode -- obj )
[ read-bencode ] with-string-reader ;