-! Copyright (C) 2009 Daniel Ehrenberg
+! Copyright (C) 2009, 2023 Daniel Ehrenberg, Alexander Ilin
! See https://factorcode.org/license.txt for BSD license.
-USING: help.syntax help.markup sequences ;
+USING: help.syntax help.markup io sequences ;
IN: io.crlf
HELP: crlf
{ $values { "seq" sequence } }
{ $description "Reads until the next LF (line feed) or CRLF (carriage return followed by line feed) from the current input stream, throwing an error if CR is present without immediately being followed by LF." } ;
+HELP: use-crlf
+{ $description "Substitutes the current " { $link output-stream } " with a wrapper that outputs CR followed by LF for every " { $link stream-nl } " call (words like " { $link print } " and " { $link nl } " use that internally)." } ;
+
{ crlf>lf lf>crlf } related-words
{ "abcd" } [ "a\nb\r\ncd" [ 5 read-ignoring-crlf ] with-string-reader ] unit-test
{ "abcde" } [ "a\nb\r\ncd\r\ne" [ 5 read-ignoring-crlf ] with-string-reader ] unit-test
{ "abcde" } [ "a\nb\r\ncd\r\ne\nfghi" [ 5 read-ignoring-crlf ] with-string-reader ] unit-test
+
+{ "Hello\r\nworld.\r\n" } [
+ [ use-crlf "Hello" print "world." write nl ] with-string-writer
+] unit-test
-! Copyright (C) 2009 Daniel Ehrenberg, Slava Pestov
+! Copyright (C) 2009, 2023 Daniel Ehrenberg, Slava Pestov, Alexander Ilin
! See https://factorcode.org/license.txt for BSD license.
-USING: byte-vectors io io.private kernel math namespaces sbufs
-sequences splitting ;
+USING: accessors byte-vectors delegate delegate.protocols
+destructors io io.private kernel math namespaces sbufs sequences
+splitting ;
IN: io.crlf
: crlf ( -- )
: read-ignoring-crlf ( n -- seq/f )
input-stream get stream-read-ignoring-crlf ;
+
+TUPLE: crlf-stream underlying ;
+INSTANCE: crlf-stream output-stream
+CONSULT: output-stream-protocol crlf-stream underlying>> ;
+
+C: <crlf-stream> crlf-stream
+
+M: crlf-stream dispose underlying>> dispose ;
+
+M: crlf-stream stream-nl
+ CHAR: \r over stream-write1
+ CHAR: \n swap stream-write1 ;
+
+: use-crlf ( -- )
+ output-stream [ <crlf-stream> ] change ;