factor/extra/io/buffers/buffers.factor

78 lines
2.1 KiB
Factor
Raw Normal View History

2007-09-20 18:09:08 -04:00
! Copyright (C) 2004, 2005 Mackenzie Straight.
! Copyright (C) 2006, 2008 Slava Pestov.
2007-09-20 18:09:08 -04:00
! See http://factorcode.org/license.txt for BSD license.
2008-02-01 00:00:08 -05:00
USING: alien alien.accessors alien.c-types alien.syntax kernel
kernel.private libc math sequences byte-arrays strings hints
accessors math.order ;
IN: io.buffers
2007-09-20 18:09:08 -04:00
TUPLE: buffer size ptr fill pos ;
: <buffer> ( n -- buffer )
dup malloc 0 0 buffer boa ;
2007-09-20 18:09:08 -04:00
: buffer-free ( buffer -- )
dup buffer-ptr free f swap set-buffer-ptr ;
: buffer-reset ( n buffer -- )
2008-02-02 19:14:26 -05:00
0 swap { set-buffer-fill set-buffer-pos } set-slots ;
2007-09-20 18:09:08 -04:00
: buffer-consume ( n buffer -- )
[ buffer-pos + ] keep
[ buffer-fill min ] keep
[ set-buffer-pos ] keep
dup buffer-pos over buffer-fill >= [
0 over set-buffer-pos
0 over set-buffer-fill
] when drop ;
: buffer@ ( buffer -- alien )
dup buffer-pos swap buffer-ptr <displaced-alien> ;
: buffer-end ( buffer -- alien )
dup buffer-fill swap buffer-ptr <displaced-alien> ;
2008-03-11 20:51:58 -04:00
: buffer-peek ( buffer -- byte )
2007-09-20 18:09:08 -04:00
buffer@ 0 alien-unsigned-1 ;
2008-03-11 20:51:58 -04:00
: buffer-pop ( buffer -- byte )
2007-09-20 18:09:08 -04:00
dup buffer-peek 1 rot buffer-consume ;
: (buffer-read) ( n buffer -- byte-array )
[ [ fill>> ] [ pos>> ] bi - min ] keep
2008-03-07 22:26:35 -05:00
buffer@ swap memory>byte-array ;
2007-09-20 18:09:08 -04:00
: buffer-read ( n buffer -- byte-array )
[ (buffer-read) ] [ buffer-consume ] 2bi ;
2007-10-27 14:43:17 -04:00
2007-09-20 18:09:08 -04:00
: buffer-length ( buffer -- n )
[ fill>> ] [ pos>> ] bi - ;
2007-09-20 18:09:08 -04:00
: buffer-capacity ( buffer -- n )
[ size>> ] [ fill>> ] bi - ;
2007-09-20 18:09:08 -04:00
: buffer-empty? ( buffer -- ? )
fill>> zero? ;
2007-09-20 18:09:08 -04:00
: extend-buffer ( n buffer -- )
2007-11-09 03:19:01 -05:00
2dup buffer-ptr swap realloc
2007-09-20 18:09:08 -04:00
over set-buffer-ptr set-buffer-size ;
: check-overflow ( n buffer -- )
2dup buffer-capacity > [ extend-buffer ] [ 2drop ] if ;
2008-03-07 22:26:35 -05:00
: >buffer ( byte-array buffer -- )
2007-09-20 18:09:08 -04:00
over length over check-overflow
2008-03-07 22:26:35 -05:00
[ buffer-end byte-array>memory ] 2keep
2007-09-20 18:09:08 -04:00
[ buffer-fill swap length + ] keep set-buffer-fill ;
2008-03-11 20:51:58 -04:00
: byte>buffer ( byte buffer -- )
2007-09-20 18:09:08 -04:00
1 over check-overflow
[ buffer-end 0 set-alien-unsigned-1 ] keep
[ 1+ ] change-fill drop ;
2007-09-20 18:09:08 -04:00
: n>buffer ( n buffer -- )
[ buffer-fill + ] keep
[ buffer-size > [ "Buffer overflow" throw ] when ] 2keep
set-buffer-fill ;