}
{ $description "Writes a comma-separated-value structure to a file." } ;
+HELP: string>csv
+{ $values
+ { "string" string }
+ { "csv" "csv" }
+}
+{ $description "Parses a string into a sequence of comma-separated-value fields." } ;
+
+HELP: csv>string
+{ $values
+ { "rows" "a sequence of sequences of strings" }
+ { "string" string }
+}
+{ $description "Writes a comma-separated-value structure to a string." } ;
+
HELP: csv-row
{ $values { "stream" "an input stream" }
{ "row" "an array of fields" } }
{ $subsections file>csv }
"Writing a csv file:"
{ $subsections csv>file }
+"Reading a string to csv:"
+{ $subsections string>csv }
+"Writing csv to a string:"
+{ $subsections csv>string }
"Changing the delimiter from a comma:"
{ $subsections with-delimiter }
"Reading from a stream:"
! Copyright (C) 2007, 2008 Phil Dawes
! See http://factorcode.org/license.txt for BSD license.
USING: kernel sequences io namespaces make combinators
-unicode.categories io.files combinators.short-circuit ;
+unicode.categories io.files combinators.short-circuit
+io.streams.string ;
IN: csv
SYMBOL: delimiter
[ [ (csv) ] { } make ] with-input-stream
dup last { "" } = [ but-last ] when ;
+: string>csv ( string -- csv )
+ <string-reader> csv ;
+
: file>csv ( path encoding -- csv )
<file-reader> csv ;
: write-row ( row -- )
[ delimiter get write1 ]
[ escape-if-required write ] interleave nl ; inline
+
+<PRIVATE
+
+: (write-csv) ( rows -- )
+ [ write-row ] each ;
+PRIVATE>
+
: write-csv ( rows stream -- )
- [ [ write-row ] each ] with-output-stream ;
+ [ (write-csv) ] with-output-stream ;
+: csv>string ( csv -- string )
+ [ (write-csv) ] with-string-writer ;
+
: csv>file ( rows path encoding -- ) <file-writer> write-csv ;