factor/library/collections/growable.factor

50 lines
1.4 KiB
Factor
Raw Normal View History

! Copyright (C) 2005 Slava Pestov.
! See http://factor.sf.net/license.txt for BSD license.
! Some low-level code used by vectors and string buffers.
IN: sequences-internals
USING: errors kernel kernel-internals math math-internals
sequences ;
GENERIC: underlying
GENERIC: set-underlying
2005-09-10 00:26:12 -04:00
! fill pointer mutation. user code should use set-length
! instead, since it will also resize the underlying sequence.
GENERIC: set-fill
: capacity ( seq -- n ) underlying length ; inline
: expand ( len seq -- )
[ underlying resize ] keep set-underlying ;
2005-09-24 16:34:10 -04:00
: new-size ( n -- n ) 3 * dup 50 < [ drop 50 ] when ;
: ensure ( n seq -- )
#! If n is beyond the sequence's length, increase the length,
#! growing the underlying storage if necessary, with an
#! optimistic doubling of its size.
2005-09-24 16:34:10 -04:00
2dup length >= [
>r 1+ r>
2dup capacity > [ over new-size over expand ] when
2dup set-fill
] when 2drop ;
2005-09-24 16:34:10 -04:00
TUPLE: bounds-error index seq ;
: bounds-error <bounds-error> throw ;
: growable-check ( n seq -- fx seq )
over 0 < [ 2dup bounds-error ] when ; inline
: bounds-check ( n seq -- fx seq )
growable-check 2dup length >= [ 2dup bounds-error ] when ;
inline
: grow-length ( len seq -- )
2005-09-10 00:26:12 -04:00
growable-check 2dup capacity > [ 2dup expand ] when set-fill ;
2005-09-07 17:21:11 -04:00
: clone-growable ( obj -- obj )
#! Cloning vectors, sbufs, hashtables.
(clone) dup underlying clone over set-underlying ;