Add csv>string and string>csv

db4
Doug Coleman 2010-02-25 18:30:40 -06:00
parent 18c0935b64
commit 5eff2e0e9a
2 changed files with 36 additions and 4 deletions

View File

@ -21,6 +21,20 @@ HELP: csv>file
}
{ $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" } }
@ -42,6 +56,10 @@ ARTICLE: "csv" "Comma-separated-values parsing and writing"
{ $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:"

View File

@ -1,7 +1,8 @@
! 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
@ -65,6 +66,9 @@ PRIVATE>
[ [ (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 ;
@ -97,7 +101,17 @@ PRIVATE>
[ 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 ;