2005-04-02 02:39:33 -05:00
|
|
|
! Copyright (C) 2005 Slava Pestov.
|
|
|
|
|
! See http://factor.sf.net/license.txt for BSD license.
|
|
|
|
|
IN: sequences
|
2005-05-05 22:30:58 -04:00
|
|
|
USING: errors generic kernel math math-internals strings vectors ;
|
2005-04-02 02:39:33 -05:00
|
|
|
|
|
|
|
|
! This file is needed very early in bootstrap.
|
|
|
|
|
|
|
|
|
|
! Sequences support the following protocol. Concrete examples
|
|
|
|
|
! are strings, string buffers, vectors, and arrays. Arrays are
|
|
|
|
|
! low level and not bounds-checked; they are in the
|
|
|
|
|
! kernel-internals vocabulary, so don't use them unless you have
|
|
|
|
|
! a good reason.
|
|
|
|
|
|
2005-04-25 19:54:21 -04:00
|
|
|
GENERIC: empty? ( sequence -- ? )
|
2005-04-02 02:39:33 -05:00
|
|
|
GENERIC: length ( sequence -- n )
|
|
|
|
|
GENERIC: set-length ( n sequence -- )
|
|
|
|
|
GENERIC: nth ( n sequence -- obj )
|
|
|
|
|
GENERIC: set-nth ( value n sequence -- obj )
|
2005-04-25 19:54:21 -04:00
|
|
|
GENERIC: thaw ( seq -- mutable-seq )
|
2005-04-17 21:59:11 -04:00
|
|
|
GENERIC: freeze ( new orig -- new )
|
2005-04-25 19:54:21 -04:00
|
|
|
GENERIC: reverse ( seq -- seq )
|
2005-04-26 00:35:55 -04:00
|
|
|
GENERIC: peek ( seq -- elt )
|
2005-05-05 22:30:58 -04:00
|
|
|
GENERIC: contains? ( elt seq -- ? )
|
2005-04-25 19:54:21 -04:00
|
|
|
|
|
|
|
|
DEFER: append ! remove this when sort is moved from lists to sequences
|
2005-05-05 22:30:58 -04:00
|
|
|
|
|
|
|
|
! Some low-level code used by vectors and string buffers.
|
|
|
|
|
IN: kernel-internals
|
|
|
|
|
|
|
|
|
|
: assert-positive ( fx -- )
|
|
|
|
|
0 fixnum<
|
|
|
|
|
[ "Sequence index must be positive" throw ] when ; inline
|
|
|
|
|
|
|
|
|
|
: assert-bounds ( fx seq -- )
|
|
|
|
|
over assert-positive
|
|
|
|
|
length fixnum>=
|
|
|
|
|
[ "Sequence index out of bounds" throw ] when ; inline
|
|
|
|
|
|
|
|
|
|
: bounds-check ( n seq -- fixnum seq )
|
|
|
|
|
>r >fixnum r> 2dup assert-bounds ; inline
|
|
|
|
|
|
|
|
|
|
: growable-check ( n seq -- fixnum seq )
|
|
|
|
|
>r >fixnum dup assert-positive r> ; inline
|
|
|
|
|
|
|
|
|
|
GENERIC: underlying
|
|
|
|
|
GENERIC: set-underlying
|
|
|
|
|
GENERIC: set-capacity
|
|
|
|
|
GENERIC: (grow)
|
|
|
|
|
|
|
|
|
|
: grow ( len seq -- )
|
|
|
|
|
#! If the sequence cannot accomodate len elements, resize it
|
|
|
|
|
#! to exactly len.
|
|
|
|
|
[ underlying (grow) ] keep set-underlying ;
|
|
|
|
|
|
|
|
|
|
: 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.
|
|
|
|
|
2dup length fixnum>= [
|
|
|
|
|
>r 1 fixnum+ r>
|
|
|
|
|
2dup underlying length fixnum> [
|
|
|
|
|
over 2 fixnum* over grow
|
|
|
|
|
] when
|
|
|
|
|
set-capacity
|
|
|
|
|
] [
|
|
|
|
|
2drop
|
|
|
|
|
] ifte ;
|