]> gitweb.factorcode.org Git - factor.git/blob - core/strings/strings.factor
8761335c6fa82c575c003332491483042aa744b9
[factor.git] / core / strings / strings.factor
1 ! Copyright (C) 2003, 2010 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien.accessors byte-arrays kernel
4 kernel.private math math.private sequences sequences.private
5 slots.private ;
6 IN: strings
7
8 BUILTIN: string { length array-capacity read-only initial: 0 } aux ;
9
10 <PRIVATE
11
12 : string-hashcode ( str -- n ) 3 slot ; inline
13
14 : set-string-hashcode ( n str -- ) 3 set-slot ; inline
15
16 : reset-string-hashcode ( str -- )
17     f swap set-string-hashcode ; inline
18
19 : rehash-string ( str -- )
20     1 over sequence-hashcode swap set-string-hashcode ; inline
21
22 : (aux) ( n string -- byte-array m )
23     aux>> { byte-array } declare swap 1 fixnum-shift-fast ; inline
24
25 : small-char? ( ch -- ? )
26     dup 0 fixnum>= [ 0x7f fixnum<= ] [ drop f ] if ; inline
27
28 : string-nth ( n string -- ch )
29     2dup string-nth-fast dup small-char?
30     [ 2nip ] [
31         [ (aux) alien-unsigned-2 7 fixnum-shift-fast ] dip
32         fixnum-bitxor
33     ] if ; inline
34
35 : ensure-aux ( string -- string )
36     dup aux>> [ dup length 2 * (byte-array) >>aux ] unless ; inline
37
38 : set-string-nth-slow ( ch n string -- )
39     [ [ 0x80 fixnum-bitor ] 2dip set-string-nth-fast ]
40     [
41         ensure-aux
42         [ -7 fixnum-shift-fast 1 fixnum-bitxor ] 2dip
43         (aux) set-alien-unsigned-2
44     ] 3bi ;
45
46 : set-string-nth ( ch n string -- )
47     pick small-char?
48     [ set-string-nth-fast ] [ set-string-nth-slow ] if ; inline
49
50 PRIVATE>
51
52 M: string equal?
53     over string? [
54         2dup [ hashcode ] bi@ eq?
55         [ sequence= ] [ 2drop f ] if
56     ] [
57         2drop f
58     ] if ;
59
60 M: string hashcode*
61     nip
62     dup string-hashcode
63     [ ] [ dup rehash-string string-hashcode ] ?if ;
64
65 M: string length
66     length>> ; inline
67
68 M: string nth-unsafe
69     [ integer>fixnum ] dip string-nth ; inline
70
71 M: string set-nth-unsafe
72     dup reset-string-hashcode
73     [ integer>fixnum ] [ integer>fixnum ] [ ] tri* set-string-nth ; inline
74
75 M: string clone
76     (clone) [ clone ] change-aux ; inline
77
78 M: string clone-like
79     over string? [ drop clone ] [ call-next-method ] if ; inline
80
81 M: string resize resize-string ; inline
82
83 : 1string ( ch -- str ) 1 swap <string> ; inline
84
85 : >string ( seq -- str ) "" clone-like ; inline
86
87 M: string new-sequence drop 0 <string> ; inline
88
89 INSTANCE: string sequence