2005-06-19 17:50:35 -04:00
|
|
|
! Copyright (C) 2004, 2005 Slava Pestov.
|
|
|
|
! See http://factor.sf.net/license.txt for BSD license.
|
2005-07-19 21:52:10 -04:00
|
|
|
IN: io
|
2005-08-19 21:46:12 -04:00
|
|
|
USING: errors generic io kernel math namespaces sequences
|
|
|
|
vectors ;
|
2005-06-19 17:50:35 -04:00
|
|
|
|
|
|
|
TUPLE: line-reader cr ;
|
|
|
|
|
|
|
|
C: line-reader ( stream -- line ) [ set-delegate ] keep ;
|
|
|
|
|
|
|
|
: cr> dup line-reader-cr f rot set-line-reader-cr ;
|
|
|
|
|
2005-07-21 21:43:37 -04:00
|
|
|
: (readln) ( ? line -- ? )
|
2005-06-19 17:50:35 -04:00
|
|
|
#! The flag is set after the first character is read.
|
|
|
|
dup delegate stream-read1 dup [
|
|
|
|
>r >r drop t r> r> dup CHAR: \r = [
|
|
|
|
drop t swap set-line-reader-cr
|
|
|
|
] [
|
|
|
|
dup CHAR: \n = [
|
2005-09-24 15:21:17 -04:00
|
|
|
drop dup cr> [ (readln) ] [ drop ] if
|
2005-06-19 17:50:35 -04:00
|
|
|
] [
|
2005-07-21 21:43:37 -04:00
|
|
|
, (readln)
|
2005-09-24 15:21:17 -04:00
|
|
|
] if
|
|
|
|
] if
|
2005-06-19 17:50:35 -04:00
|
|
|
] [
|
|
|
|
2drop
|
2005-09-24 15:21:17 -04:00
|
|
|
] if ;
|
2005-06-19 17:50:35 -04:00
|
|
|
|
|
|
|
M: line-reader stream-readln ( line -- string )
|
2005-08-25 15:27:38 -04:00
|
|
|
[ f swap (readln) ] "" make
|
2005-09-24 15:21:17 -04:00
|
|
|
dup empty? [ f ? ] [ nip ] if ;
|
2005-06-19 17:50:35 -04:00
|
|
|
|
|
|
|
M: line-reader stream-read ( count line -- string )
|
|
|
|
[ delegate stream-read ] keep dup cr> [
|
2005-06-23 15:53:54 -04:00
|
|
|
over empty? [
|
|
|
|
drop
|
|
|
|
] [
|
|
|
|
>r 1 swap tail r> stream-read1 [ add ] when*
|
2005-09-24 15:21:17 -04:00
|
|
|
] if
|
2005-06-19 17:50:35 -04:00
|
|
|
] [
|
|
|
|
drop
|
2005-09-24 15:21:17 -04:00
|
|
|
] if ;
|
2005-06-19 18:31:02 -04:00
|
|
|
|
2005-08-19 21:46:12 -04:00
|
|
|
: (lines) ( seq -- seq )
|
|
|
|
readln [ over push (lines) ] when* ;
|
2005-06-19 18:31:02 -04:00
|
|
|
|
2005-08-19 21:46:12 -04:00
|
|
|
: lines ( stream -- seq )
|
|
|
|
#! Read all lines from the stream into a sequence.
|
2005-10-29 23:25:38 -04:00
|
|
|
[ V{ } clone (lines) ] with-stream ;
|