factor/library/io/lines.factor

50 lines
1.2 KiB
Factor
Raw Normal View History

! 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 ;
TUPLE: line-reader cr ;
C: line-reader ( stream -- line ) [ set-delegate ] keep ;
: cr> dup line-reader-cr f rot set-line-reader-cr ;
: (readln) ( ? line -- ? )
#! 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
] [
, (readln)
2005-09-24 15:21:17 -04:00
] if
] if
] [
2drop
2005-09-24 15:21:17 -04:00
] if ;
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 ;
M: line-reader stream-read ( count line -- string )
[ delegate stream-read ] keep dup cr> [
over empty? [
drop
] [
>r 1 swap tail r> stream-read1 [ add ] when*
2005-09-24 15:21:17 -04:00
] if
] [
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.
[ V{ } clone (lines) ] with-stream ;