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