factor/core/growable/growable.factor

69 lines
1.6 KiB
Factor
Raw Normal View History

! Copyright (C) 2005, 2009 Slava Pestov.
2007-09-20 18:09:08 -04:00
! See http://factorcode.org/license.txt for BSD license.
USING: accessors kernel kernel.private math math.private
2007-09-20 18:09:08 -04:00
sequences sequences.private ;
IN: growable
MIXIN: growable
SLOT: length
SLOT: underlying
2007-09-20 18:09:08 -04:00
M: growable length length>> ; inline
M: growable nth-unsafe underlying>> nth-unsafe ; inline
M: growable set-nth-unsafe underlying>> set-nth-unsafe ; inline
2007-09-20 18:09:08 -04:00
: capacity ( seq -- n ) underlying>> length ; inline
2007-09-20 18:09:08 -04:00
: expand ( len seq -- )
[ resize ] change-underlying drop ; inline
2007-09-20 18:09:08 -04:00
GENERIC: contract ( len seq -- )
M: growable contract ( len seq -- )
2007-09-20 18:09:08 -04:00
[ length ] keep
[ [ 0 ] 2dip set-nth-unsafe ] curry
(each-integer) ; inline
2007-09-20 18:09:08 -04:00
M: growable set-length ( n seq -- )
2011-10-14 13:23:52 -04:00
bounds-check-head
2007-09-20 18:09:08 -04:00
2dup length < [
2dup contract
] [
2dup capacity > [ 2dup expand ] when
] if
length<< ;
2007-09-20 18:09:08 -04:00
: new-size ( old -- new ) 1 + 3 * ; inline
2007-09-20 18:09:08 -04:00
: ensure ( n seq -- n seq )
2011-10-14 13:23:52 -04:00
bounds-check-head
2007-09-20 18:09:08 -04:00
2dup length >= [
2dup capacity >= [ over new-size over expand ] when
[ >fixnum ] dip
over 1 fixnum+fast over length<<
2007-09-20 18:09:08 -04:00
] [
[ >fixnum ] dip
2007-09-20 18:09:08 -04:00
] if ; inline
M: growable set-nth ensure set-nth-unsafe ; inline
2007-09-20 18:09:08 -04:00
M: growable clone (clone) [ clone ] change-underlying ; inline
2007-09-20 18:09:08 -04:00
M: growable lengthen ( n seq -- )
2dup length > [
2dup capacity > [ over new-size over expand ] when
2dup length<<
] when 2drop ; inline
2007-09-20 18:09:08 -04:00
2008-07-12 02:08:30 -04:00
M: growable shorten ( n seq -- )
2011-10-14 13:23:52 -04:00
bounds-check-head
2008-07-12 02:08:30 -04:00
2dup length < [
2dup contract
2dup length<<
] when 2drop ; inline
2008-07-12 02:08:30 -04:00
M: growable new-resizable new-sequence 0 over set-length ; inline
2007-09-20 18:09:08 -04:00
INSTANCE: growable sequence