factor/core/growable/growable.factor

81 lines
2.0 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.
2013-03-05 13:34:47 -05:00
USING: accessors kernel math math.private sequences
sequences.private ;
2007-09-20 18:09:08 -04:00
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
<PRIVATE
: push-unsafe ( elt seq -- )
[ length integer>fixnum ] keep
[ set-nth-unsafe ] [ [ 1 fixnum+fast ] dip length<< ] 2bi ; inline
: push-all-unsafe ( from to src dst -- )
[ over - swap ] 2dip [ pick ] dip [ length integer>fixnum ] keep
[ [ fixnum+fast ] dip length<< ] 2keep <copy> (copy) drop ; inline
PRIVATE>
: 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 + 2 * ; 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
[ integer>fixnum ] dip
2014-12-11 23:55:04 -05:00
over 1 fixnum+fast >>length
2007-09-20 18:09:08 -04:00
] [
[ integer>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