]> gitweb.factorcode.org Git - factor.git/blob - core/strings/strings.factor
4bbf642ca0d3312f2fd3508527200a591ed98bc1
[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 PRIMITIVE: <string> ( n ch -- string )
11 PRIMITIVE: resize-string ( n str -- newstr )
12
13 <PRIVATE
14 PRIMITIVE: set-string-nth-fast ( ch n string -- )
15 PRIMITIVE: string-nth-fast ( n string -- ch )
16
17 : string-hashcode ( str -- n ) 3 slot ; inline
18
19 : set-string-hashcode ( n str -- ) 3 set-slot ; inline
20
21 : reset-string-hashcode ( str -- )
22     f swap set-string-hashcode ; inline
23
24 : rehash-string ( str -- )
25     1 over sequence-hashcode swap set-string-hashcode ; inline
26
27 : (aux) ( n string -- byte-array m )
28     aux>> { byte-array } declare swap 1 fixnum-shift-fast ; inline
29
30 : small-char? ( ch -- ? )
31     dup 0 fixnum>= [ 0x7f fixnum<= ] [ drop f ] if ; inline
32
33 : string-nth ( n string -- ch )
34     2dup string-nth-fast dup small-char?
35     [ 2nip ] [
36         [ (aux) alien-unsigned-2 7 fixnum-shift-fast ] dip
37         fixnum-bitxor
38     ] if ; inline
39
40 : ensure-aux ( string -- string )
41     dup aux>> [ dup length 2 * (byte-array) >>aux ] unless ; inline
42
43 : set-string-nth-slow ( ch n string -- )
44     [ [ 0x80 fixnum-bitor ] 2dip set-string-nth-fast ]
45     [
46         ensure-aux
47         [ -7 fixnum-shift-fast 1 fixnum-bitxor ] 2dip
48         (aux) set-alien-unsigned-2
49     ] 3bi ;
50
51 : set-string-nth ( ch n string -- )
52     pick small-char?
53     [ set-string-nth-fast ] [ set-string-nth-slow ] if ; inline
54
55 PRIVATE>
56
57 M: string equal?
58     over string? [
59         2dup [ hashcode ] bi@ eq?
60         [ sequence= ] [ 2drop f ] if
61     ] [
62         2drop f
63     ] if ;
64
65 M: string hashcode*
66     nip
67     dup string-hashcode
68     [ ] [ dup rehash-string string-hashcode ] ?if ;
69
70 M: string length
71     length>> ; inline
72
73 M: string nth-unsafe
74     [ integer>fixnum ] dip string-nth ; inline
75
76 M: string set-nth-unsafe
77     dup reset-string-hashcode
78     [ integer>fixnum ] [ integer>fixnum ] [ ] tri* set-string-nth ; inline
79
80 M: string clone
81     (clone) [ clone ] change-aux ; inline
82
83 M: string clone-like
84     over string? [ drop clone ] [ call-next-method ] if ; inline
85
86 M: string resize resize-string ; inline
87
88 : 1string ( ch -- str ) 1 swap <string> ; inline
89
90 : >string ( seq -- str ) "" clone-like ; inline
91
92 M: string new-sequence drop 0 <string> ; inline
93
94 INSTANCE: string sequence