! Copyright (C) 2013-2014 Björn Lindqvist
! See http://factorcode.org/license.txt for BSD license
-USING: accessors ascii assocs base64 fry io io.encodings
-io.encodings.string io.encodings.utf16 kernel math
+USING: accessors ascii base64 fry io io.encodings
+io.encodings.string io.encodings.utf16 kernel make math
math.functions sequences splitting strings ;
IN: io.encodings.utf7
[ swap [ first ] [ concat ] bi replace nip ]
[ >raw-base64 -rot [ first2 replace ] [ first2 surround ] bi* ] if ;
+: split-chunk ( str -- after before printable? )
+ dup first printable? [
+ dupd '[ printable? _ = not ] find drop
+ [ cut-slice ] [ f ] if* swap
+ ] keep ;
+
: encode-utf7-string ( str codec -- bytes )
- [ [ printable? ] collect-by ] dip dialect>> first2
- '[ [ _ _ ] 2dip swap encode-chunk ] { } assoc>map
- B{ } concat-as ;
+ dialect>> first2 rot '[
+ [ dup empty? ] [
+ split-chunk '[ 2dup _ _ encode-chunk % ] dip
+ ] until
+ ] B{ } make 3nip ;
M: utf7codec encode-string ( str stream codec -- )
swapd encode-utf7-string swap stream-write ;