needs lib/struct io/stream unit mem/roll extends Stream struct RollBuf { uint ridx widx nextridx bufsz ; [void,0] buffer ; } : _readbuf ( n stream -- ?a read-n ) r! nextridx dup r@ to ridx ( n ridx ) \ V1=stream r@ widx swap r@ buffer over + rot> ( n a wr rd ) 2dup >= if - else nip r@ bufsz swap- then ( n a u ) rot min ( a u ) r@ ridx over + r@ bufsz mod r> to nextridx ( a u ) dup not if nip then ; : _writebuf ( a n stream -- written-n ) r! ridx r@ widx ( src n rd wr ) \ V1=stream r@ buffer over + rot> ( n a rd wr ) 2dup > if - 1- else nip r@ bufsz swap- then ( src n dst u ) rot min ( src dst u ) r! cmove r> ( u ) r@ widx over + r@ bufsz mod r> to widx ; : newrollingbuffer ( bufsz -- rollbuf ) ['] _readbuf ['] _writebuf newstream 0 , 0 , 0 , over ( bufsz ) , swap allot ; : fastputc, ( -- br ) \ A=stream W=c A) offsetof widx +) S>) @, A) offsetof buffer +) &) S>) +, S) 8b) !, A) offsetof widx +) @, 1 i) +, A) offsetof bufsz +) /mod, \ S=widx A) offsetof ridx +) S>) <>) if, A) offsetof widx +) S>) !, ;