2 \ ** ficl/softwords/string.fr
3 \ A useful dynamic string class
4 \ John Sadler 14 Sep 1998
7 \ counted string, buffer sized dynamically
10 \ s" arf arf!!" str --> set
11 \ s" woof woof woof " str --> cat
17 object subclass c-string
23 : get-count ( 2:this -- count ) my=[ .count get ] ;
24 : set-count ( count 2:this -- ) my=[ .count set ] ;
26 : ?empty ( 2:this -- flag ) --> get-count 0= ;
28 : get-buflen ( 2:this -- len ) my=[ .buflen get ] ;
29 : set-buflen ( len 2:this -- ) my=[ .buflen set ] ;
31 : get-buf ( 2:this -- ptr ) my=[ .buf get-ptr ] ;
32 : set-buf { ptr len 2:this -- }
33 ptr this my=[ .buf set-ptr ]
34 len this my=> set-buflen
37 \ set buffer to null and buflen to zero
38 : clr-buf ( 2:this -- )
39 0 0 2over my=> set-buf
43 \ free the buffer if there is one, set buf pointer to null
44 : free-buf { 2:this -- }
48 abort" c-string free failed"
53 \ guarantee buffer is large enough to hold size chars
54 : size-buf { size 2:this -- }
55 size 0< abort" need positive size for size-buf"
57 this --> free-buf exit
60 \ force buflen to be a positive multiple of min-buf chars
61 my=> min-buf size over / 1+ * chars to size
63 \ if buffer is null, allocate one, else resize it
64 this --> get-buflen 0=
69 size this --> set-buflen
73 size this --> get-buflen > if
74 this --> get-buf size resize
80 : set { c-addr u 2:this -- }
83 c-addr this --> get-buf u move
86 : get { 2:this -- c-addr u }
91 \ append string to existing one
92 : cat { c-addr u 2:this -- }
93 this --> get-count u + dup >r
95 c-addr this --> get-buf this --> get-count + u move
100 this --> ?empty if ." (empty) " exit endif
101 this --> .buf --> get-ptr
102 this --> .count --> get
106 : compare ( 2string 2:this -- n )
113 : hashcode ( 2:this -- hashcode )
117 \ destructor method (overrides object --> free)
118 : free ( 2:this -- ) 2dup --> free-buf object => free ;
122 c-string subclass c-hashstring
123 c-2byte obj: .hashcode
125 : set-hashcode { 2:this -- }
126 this --> super --> hashcode
127 this --> .hashcode --> set
130 : get-hashcode ( 2:this -- hashcode )
131 --> .hashcode --> get
134 : set ( c-addr u 2:this -- )
135 2swap 2over --> super --> set
139 : cat ( c-addr u 2:this -- )
140 2swap 2over --> super --> cat