factor/library/io/lines.factor

47 lines
1.1 KiB
Factor
Raw Normal View History

! Copyright (C) 2004, 2005 Slava Pestov.
2006-01-16 02:48:15 -05:00
! See http://factorcode.org/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 ;
2006-08-16 21:55:53 -04:00
C: line-reader ( stream -- new-stream ) [ 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 number= [
drop t swap set-line-reader-cr
] [
dup CHAR: \n number= [
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
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
[ delegate stream-read ] keep dup cr> [
over empty? [
drop
] [
>r 1 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
2006-08-16 21:55:53 -04:00
: (lines) ( -- ) readln [ , (lines) ] when* ;
2005-06-19 18:31:02 -04:00
2006-01-16 02:48:15 -05:00
: lines ( stream -- seq ) [ [ (lines) ] { } make ] with-stream ;