1 ! Copyright (C) 2022 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
4 USING: accessors assocs checksums checksums.crc32 combinators
5 endian formatting io.encodings.binary io.files io.files.info
6 kernel make math math.functions math.order namespaces sequences
11 ! TODO: Support yparts
13 SYMBOL: yenc-line-length
14 yenc-line-length [ 128 ] initialize
19 building get length yenc-line-length get
20 [ 2 + ] bi@ divisor? [ "\r\n" % ] when ;
25 dup "\0\r\n=" member? [ CHAR: = , 64 + 256 mod ] when ,
31 : yenc ( bytes -- yenc )
37 [ file-info size>> yenc-line-length get ] keep
38 "=ybegin size=%d line=%d name=%s\n" sprintf % ;
41 [ file-info size>> ] [ crc32 checksum-bytes be> ] bi
42 "\n=yend size=%d crc32=%08X" sprintf % ;
46 : yenc-file ( path -- yenc )
49 [ binary file-contents yenc% ]
55 : ydec, ( encode? ch -- encode?' )
56 dup "\r\n" member? [ drop ] [
57 2dup [ not ] [ CHAR: = = ] bi* and [ 2drop t ] [
58 over [ 64 - [ drop f ] dip ] when
59 dup 0 41 between? [ 214 + ] [ 42 - ] if ,
65 : ydec ( yenc -- bytes )
66 [ f swap [ ydec, ] each drop ] B{ } make ;
70 : parse-metadata ( line -- metadata )
71 >string " " split [ "=" split1 ] H{ } map>assoc ;
73 : find-metadata ( lines type -- metadata i )
74 [ '[ _ head? ] find ] keep ?head drop parse-metadata swap ;
78 : ydec-file ( yenc -- ybegin yend bytes )
80 [ "=ybegin " find-metadata 1 + ]
81 [ "=yend " find-metadata swapd ]
84 f swap [ [ ydec, ] each ] each drop