]> gitweb.factorcode.org Git - factor.git/blob - core/growable/growable.factor
Merge branch 'master' into experimental (untested!)
[factor.git] / core / growable / growable.factor
1 ! Copyright (C) 2005, 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3
4 ! Some low-level code used by vectors and string buffers.
5 USING: accessors kernel kernel.private math math.private
6 sequences sequences.private ;
7 IN: growable
8
9 MIXIN: growable
10
11 SLOT: length
12 SLOT: underlying
13
14 M: growable length length>> ;
15 M: growable nth-unsafe underlying>> nth-unsafe ;
16 M: growable set-nth-unsafe underlying>> set-nth-unsafe ;
17
18 : capacity ( seq -- n ) underlying>> length ; inline
19
20 : expand ( len seq -- )
21     [ resize ] change-underlying drop ; inline
22
23 : contract ( len seq -- )
24     [ length ] keep
25     [ 0 -rot set-nth-unsafe ] curry
26     (each-integer) ; inline
27
28 : growable-check ( n seq -- n seq )
29     over 0 < [ bounds-error ] when ; inline
30
31 M: growable set-length ( n seq -- )
32     growable-check
33     2dup length < [
34         2dup contract
35     ] [
36         2dup capacity > [ 2dup expand ] when
37     ] if
38     (>>length) ;
39
40 : new-size ( old -- new ) 1+ 3 * ; inline
41
42 : ensure ( n seq -- n seq )
43     growable-check
44     2dup length >= [
45         2dup capacity >= [ over new-size over expand ] when
46         [ >fixnum ] dip
47         over 1 fixnum+fast over (>>length)
48     ] [
49         [ >fixnum ] dip
50     ] if ; inline
51
52 M: growable set-nth ensure set-nth-unsafe ;
53
54 M: growable clone (clone) [ clone ] change-underlying ;
55
56 M: growable lengthen ( n seq -- )
57     2dup length > [
58         2dup capacity > [ over new-size over expand ] when
59         2dup (>>length)
60     ] when 2drop ;
61
62 M: growable shorten ( n seq -- )
63     growable-check
64     2dup length < [
65         2dup contract
66         2dup (>>length)
67     ] when 2drop ;
68
69 INSTANCE: growable sequence