Debian Codegraph @

%3a13/srfi-13.scm

raw
1 ;;; SRFI 13 string library reference implementation -*- Scheme -*-
2 ;;; Olin Shivers 7/2000
3 ;;;
4 ;;; Copyright (c) 1988-1994 Massachusetts Institute of Technology.
5 ;;; Copyright (c) 1998, 1999, 2000 Olin Shivers. All rights reserved.
6 ;;; The details of the copyrights appear at the end of the file. Short
7 ;;; summary: BSD-style open source.
8
9 ;;; Exports:
10 ;;; string-map string-map!
11 ;;; string-fold string-unfold
12 ;;; string-fold-right string-unfold-right
13 ;;; string-tabulate string-for-each string-for-each-index
14 ;;; string-every string-any
15 ;;; string-hash string-hash-ci
16 ;;; string-compare string-compare-ci
17 ;;; string= string< string> string<= string>= string<>
18 ;;; string-ci= string-ci< string-ci> string-ci<= string-ci>= string-ci<>
19 ;;; string-downcase string-upcase string-titlecase
20 ;;; string-downcase! string-upcase! string-titlecase!
21 ;;; string-take string-take-right
22 ;;; string-drop string-drop-right
23 ;;; string-pad string-pad-right
24 ;;; string-trim string-trim-right string-trim-both
25 ;;; string-filter string-delete
26 ;;; string-index string-index-right
27 ;;; string-skip string-skip-right
28 ;;; string-count
29 ;;; string-prefix-length string-prefix-length-ci
30 ;;; string-suffix-length string-suffix-length-ci
31 ;;; string-prefix? string-prefix-ci?
32 ;;; string-suffix? string-suffix-ci?
33 ;;; string-contains string-contains-ci
34 ;;; string-copy! substring/shared
35 ;;; string-reverse string-reverse! reverse-list->string
36 ;;; string-concatenate string-concatenate/shared string-concatenate-reverse
37 ;;; string-append/shared
38 ;;; xsubstring string-xcopy!
39 ;;; string-null?
40 ;;; string-join
41 ;;; string-tokenize
42 ;;; string-replace
43 ;;;
44 ;;; R5RS extended:
45 ;;; string->list string-copy string-fill!
46 ;;;
47 ;;; R5RS re-exports:
48 ;;; string? make-string string-length string-ref string-set!
49 ;;;
50 ;;; R5RS re-exports (also defined here but commented-out):
51 ;;; string string-append list->string
52 ;;;
53 ;;; Low-level routines:
54 ;;; make-kmp-restart-vector string-kmp-partial-search kmp-step
55 ;;; string-parse-start+end
56 ;;; string-parse-final-start+end
57 ;;; let-string-start+end
58 ;;; check-substring-spec
59 ;;; substring-spec-ok?
60
61 ;;; Imports
62 ;;; This is a fairly large library. While it was written for portability, you
63 ;;; must be aware of its dependencies in order to run it in a given scheme
64 ;;; implementation. Here is a complete list of the dependencies it has and the
65 ;;; assumptions it makes beyond stock R5RS Scheme:
66 ;;;
67 ;;; This code has the following non-R5RS dependencies:
68 ;;; - (RECEIVE (var ...) mv-exp body ...) multiple-value binding macro;
69 ;;;
70 ;;; - Various imports from the char-set library for the routines that can
71 ;;; take char-set arguments;
72 ;;;
73 ;;; - An n-ary ERROR procedure;
74 ;;;
75 ;;; - BITWISE-AND for the hash functions;
76 ;;;
77 ;;; - A simple CHECK-ARG procedure for checking parameter values; it is
78 ;;; (lambda (pred val proc)
79 ;;; (if (pred val) val (error "Bad arg" val pred proc)))
80 ;;;
81 ;;; - :OPTIONAL and LET-OPTIONALS* macros for parsing, defaulting &
82 ;;; type-checking optional parameters from a rest argument;
83 ;;;
84 ;;; - CHAR-CASED? and CHAR-TITLECASE for the STRING-TITLECASE &
85 ;;; STRING-TITLECASE! procedures. The former returns true iff a character is
86 ;;; one that has case distinctions; in ASCII it returns true on a-z and A-Z.
87 ;;; CHAR-TITLECASE is analagous to CHAR-UPCASE and CHAR-DOWNCASE. In ASCII &
88 ;;; Latin-1, it is the same as CHAR-UPCASE.
89 ;;;
90 ;;; The code depends upon a small set of core string primitives from R5RS:
91 ;;; MAKE-STRING STRING-REF STRING-SET! STRING? STRING-LENGTH SUBSTRING
92 ;;; (Actually, SUBSTRING is not a primitive, but we assume that an
93 ;;; implementation's native version is probably faster than one we could
94 ;;; define, so we import it from R5RS.)
95 ;;;
96 ;;; The code depends upon a small set of R5RS character primitives:
97 ;;; char? char=? char-ci=? char<? char-ci<?
98 ;;; char-upcase char-downcase
99 ;;; char->integer (for the hash functions)
100 ;;;
101 ;;; We assume the following:
102 ;;; - CHAR-DOWNCASE o CHAR-UPCASE = CHAR-DOWNCASE
103 ;;; - CHAR-CI=? is equivalent to
104 ;;; (lambda (c1 c2) (char=? (char-downcase (char-upcase c1))
105 ;;; (char-downcase (char-upcase c2))))
106 ;;; - CHAR-UPCASE, CHAR-DOWNCASE and CHAR-TITLECASE are locale-insensitive
107 ;;; and consistent with Unicode's 1-1 char-mapping spec.
108 ;;; These things are typically true, but if not, you would need to modify
109 ;;; the case-mapping and case-insensitive routines.
110
111 ;;; Enough introductory blather. On to the source code. (But see the end of
112 ;;; the file for further notes on porting & performance tuning.)
113
114
115 ;;; Support for START/END substring specs
116 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
117 ;;; This macro parses optional start/end arguments from arg lists, defaulting
118 ;;; them to 0/(string-length s), and checks them for correctness.
119
120 (define-syntax let-string-start+end
121 (syntax-rules ()
122 ((let-string-start+end (start end) proc s-exp args-exp body ...)
123 (receive (start end) (string-parse-final-start+end proc s-exp args-exp)
124 body ...))
125 ((let-string-start+end (start end rest) proc s-exp args-exp body ...)
126 (receive (rest start end) (string-parse-start+end proc s-exp args-exp)
127 body ...))))
128
129 ;;; This one parses out a *pair* of final start/end indices.
130 ;;; Not exported; for internal use.
131 (define-syntax let-string-start+end2
132 (syntax-rules ()
133 ((l-s-s+e2 (start1 end1 start2 end2) proc s1 s2 args body ...)
134 (let ((procv proc)) ; Make sure PROC is only evaluated once.
135 (let-string-start+end (start1 end1 rest) procv s1 args
136 (let-string-start+end (start2 end2) procv s2 rest
137 body ...))))))
138
139
140 ;;; Returns three values: rest start end
141
142 (define (string-parse-start+end proc s args)
143 (if (not (string? s)) (error "Non-string value" proc s))
144 (let ((slen (string-length s)))
145 (if (pair? args)
146
147 (let ((start (car args))
148 (args (cdr args)))
149 (if (and (integer? start) (exact? start) (>= start 0))
150 (receive (end args)
151 (if (pair? args)
152 (let ((end (car args))
153 (args (cdr args)))
154 (if (and (integer? end) (exact? end) (<= end slen))
155 (values end args)
156 (error "Illegal substring END spec" proc end s)))
157 (values slen args))
158 (if (<= start end) (values args start end)
159 (error "Illegal substring START/END spec"
160 proc start end s)))
161 (error "Illegal substring START spec" proc start s)))
162
163 (values '() 0 slen))))
164
165 (define (string-parse-final-start+end proc s args)
166 (receive (rest start end) (string-parse-start+end proc s args)
167 (if (pair? rest) (error "Extra arguments to procedure" proc rest)
168 (values start end))))
169
170 (define (substring-spec-ok? s start end)
171 (and (string? s)
172 (integer? start)
173 (exact? start)
174 (integer? end)
175 (exact? end)
176 (<= 0 start)
177 (<= start end)
178 (<= end (string-length s))))
179
180 (define (check-substring-spec proc s start end)
181 (if (not (substring-spec-ok? s start end))
182 (error "Illegal substring spec." proc s start end)))
183
184
185 ;;; Defined by R5RS, so commented out here.
186 ;(define (string . chars)
187 ; (let* ((len (length chars))
188 ; (ans (make-string len)))
189 ; (do ((i 0 (+ i 1))
190 ; (chars chars (cdr chars)))
191 ; ((>= i len))
192 ; (string-set! ans i (car chars)))
193 ; ans))
194 ;
195 ;(define (string . chars) (string-unfold null? car cdr chars))
196
197
198
199 ;;; substring/shared S START [END]
200 ;;; string-copy S [START END]
201 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
202
203 ;;; All this goop is just arg parsing & checking surrounding a call to the
204 ;;; actual primitive, %SUBSTRING/SHARED.
205
206 (define (substring/shared s start . maybe-end)
207 (check-arg string? s substring/shared)
208 (let ((slen (string-length s)))
209 (check-arg (lambda (start) (and (integer? start) (exact? start) (<= 0 start)))
210 start substring/shared)
211 (%substring/shared s start
212 (:optional maybe-end slen
213 (lambda (end) (and (integer? end)
214 (exact? end)
215 (<= start end)
216 (<= end slen)))))))
217
218 ;;; Split out so that other routines in this library can avoid arg-parsing
219 ;;; overhead for END parameter.
220 (define (%substring/shared s start end)
221 (if (and (zero? start) (= end (string-length s))) s
222 (substring s start end)))
223
224 (define (string-copy s . maybe-start+end)
225 (let-string-start+end (start end) string-copy s maybe-start+end
226 (substring s start end)))
227
228 ;This library uses the R5RS SUBSTRING, but doesn't export it.
229 ;Here is a definition, just for completeness.
230 ;(define (substring s start end)
231 ; (check-substring-spec substring s start end)
232 ; (let* ((slen (- end start))
233 ; (ans (make-string slen)))
234 ; (do ((i 0 (+ i 1))
235 ; (j start (+ j 1)))
236 ; ((>= i slen) ans)
237 ; (string-set! ans i (string-ref s j)))))
238
239 ;;; Basic iterators and other higher-order abstractions
240 ;;; (string-map proc s [start end])
241 ;;; (string-map! proc s [start end])
242 ;;; (string-fold kons knil s [start end])
243 ;;; (string-fold-right kons knil s [start end])
244 ;;; (string-unfold p f g seed [base make-final])
245 ;;; (string-unfold-right p f g seed [base make-final])
246 ;;; (string-for-each proc s [start end])
247 ;;; (string-for-each-index proc s [start end])
248 ;;; (string-every char-set/char/pred s [start end])
249 ;;; (string-any char-set/char/pred s [start end])
250 ;;; (string-tabulate proc len)
251 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
252 ;;; You want compiler support for high-level transforms on fold and unfold ops.
253 ;;; You'd at least like a lot of inlining for clients of these procedures.
254 ;;; Don't hold your breath.
255
256 (define (string-map proc s . maybe-start+end)
257 (check-arg procedure? proc string-map)
258 (let-string-start+end (start end) string-map s maybe-start+end
259 (%string-map proc s start end)))
260
261 (define (%string-map proc s start end) ; Internal utility
262 (let* ((len (- end start))
263 (ans (make-string len)))
264 (do ((i (- end 1) (- i 1))
265 (j (- len 1) (- j 1)))
266 ((< j 0))
267 (string-set! ans j (proc (string-ref s i))))
268 ans))
269
270 (define (string-map! proc s . maybe-start+end)
271 (check-arg procedure? proc string-map!)
272 (let-string-start+end (start end) string-map! s maybe-start+end
273 (%string-map! proc s start end)))
274
275 (define (%string-map! proc s start end)
276 (do ((i (- end 1) (- i 1)))
277 ((< i start))
278 (string-set! s i (proc (string-ref s i)))))
279
280 (define (string-fold kons knil s . maybe-start+end)
281 (check-arg procedure? kons string-fold)
282 (let-string-start+end (start end) string-fold s maybe-start+end
283 (let lp ((v knil) (i start))
284 (if (< i end) (lp (kons (string-ref s i) v) (+ i 1))
285 v))))
286
287 (define (string-fold-right kons knil s . maybe-start+end)
288 (check-arg procedure? kons string-fold-right)
289 (let-string-start+end (start end) string-fold-right s maybe-start+end
290 (let lp ((v knil) (i (- end 1)))
291 (if (>= i start) (lp (kons (string-ref s i) v) (- i 1))
292 v))))
293
294 ;;; (string-unfold p f g seed [base make-final])
295 ;;; This is the fundamental constructor for strings.
296 ;;; - G is used to generate a series of "seed" values from the initial seed:
297 ;;; SEED, (G SEED), (G^2 SEED), (G^3 SEED), ...
298 ;;; - P tells us when to stop -- when it returns true when applied to one
299 ;;; of these seed values.
300 ;;; - F maps each seed value to the corresponding character
301 ;;; in the result string. These chars are assembled into the
302 ;;; string in a left-to-right order.
303 ;;; - BASE is the optional initial/leftmost portion of the constructed string;
304 ;;; it defaults to the empty string "".
305 ;;; - MAKE-FINAL is applied to the terminal seed value (on which P returns
306 ;;; true) to produce the final/rightmost portion of the constructed string.
307 ;;; It defaults to (LAMBDA (X) "").
308 ;;;
309 ;;; In other words, the following (simple, inefficient) definition holds:
310 ;;; (define (string-unfold p f g seed base make-final)
311 ;;; (string-append base
312 ;;; (let recur ((seed seed))
313 ;;; (if (p seed) (make-final seed)
314 ;;; (string-append (string (f seed))
315 ;;; (recur (g seed)))))))
316 ;;;
317 ;;; STRING-UNFOLD is a fairly powerful constructor -- you can use it to
318 ;;; reverse a string, copy a string, convert a list to a string, read
319 ;;; a port into a string, and so forth. Examples:
320 ;;; (port->string port) =
321 ;;; (string-unfold (compose eof-object? peek-char)
322 ;;; read-char values port)
323 ;;;
324 ;;; (list->string lis) = (string-unfold null? car cdr lis)
325 ;;;
326 ;;; (tabulate-string f size) = (string-unfold (lambda (i) (= i size)) f add1 0)
327
328 ;;; A problem with the following simple formulation is that it pushes one
329 ;;; stack frame for every char in the result string -- an issue if you are
330 ;;; using it to read a 100kchar string. So we don't use it -- but I include
331 ;;; it to give a clear, straightforward description of what the function
332 ;;; does.
333
334 ;(define (string-unfold p f g seed base make-final)
335 ; (let ((ans (let recur ((seed seed) (i (string-length base)))
336 ; (if (p seed)
337 ; (let* ((final (make-final seed))
338 ; (ans (make-string (+ i (string-length final)))))
339 ; (string-copy! ans i final)
340 ; ans)
341 ;
342 ; (let* ((c (f seed))
343 ; (s (recur (g seed) (+ i 1))))
344 ; (string-set! s i c)
345 ; s)))))
346 ; (string-copy! ans 0 base)
347 ; ans))
348
349 ;;; The strategy is to allocate a series of chunks into which we stash the
350 ;;; chars as we generate them. Chunk size goes up in powers of two starting
351 ;;; with 40 and levelling out at 4k, i.e.
352 ;;; 40 40 80 160 320 640 1280 2560 4096 4096 4096 4096 4096...
353 ;;; This should work pretty well for short strings, 1-line (80 char) strings,
354 ;;; and longer ones. When done, we allocate an answer string and copy the
355 ;;; chars over from the chunk buffers.
356
357 (define (string-unfold p f g seed . base+make-final)
358 (check-arg procedure? p string-unfold)
359 (check-arg procedure? f string-unfold)
360 (check-arg procedure? g string-unfold)
361 (let-optionals* base+make-final
362 ((base "" (string? base))
363 (make-final (lambda (x) "") (procedure? make-final)))
364 (let lp ((chunks '()) ; Previously filled chunks
365 (nchars 0) ; Number of chars in CHUNKS
366 (chunk (make-string 40)) ; Current chunk into which we write
367 (chunk-len 40)
368 (i 0) ; Number of chars written into CHUNK
369 (seed seed))
370 (let lp2 ((i i) (seed seed))
371 (if (not (p seed))
372 (let ((c (f seed))
373 (seed (g seed)))
374 (if (< i chunk-len)
375 (begin (string-set! chunk i c)
376 (lp2 (+ i 1) seed))
377
378 (let* ((nchars2 (+ chunk-len nchars))
379 (chunk-len2 (min 4096 nchars2))
380 (new-chunk (make-string chunk-len2)))
381 (string-set! new-chunk 0 c)
382 (lp (cons chunk chunks) (+ nchars chunk-len)
383 new-chunk chunk-len2 1 seed))))
384
385 ;; We're done. Make the answer string & install the bits.
386 (let* ((final (make-final seed))
387 (flen (string-length final))
388 (base-len (string-length base))
389 (j (+ base-len nchars i))
390 (ans (make-string (+ j flen))))
391 (%string-copy! ans j final 0 flen) ; Install FINAL.
392 (let ((j (- j i)))
393 (%string-copy! ans j chunk 0 i) ; Install CHUNK[0,I).
394 (let lp ((j j) (chunks chunks)) ; Install CHUNKS.
395 (if (pair? chunks)
396 (let* ((chunk (car chunks))
397 (chunks (cdr chunks))
398 (chunk-len (string-length chunk))
399 (j (- j chunk-len)))
400 (%string-copy! ans j chunk 0 chunk-len)
401 (lp j chunks)))))
402 (%string-copy! ans 0 base 0 base-len) ; Install BASE.
403 ans))))))
404
405 (define (string-unfold-right p f g seed . base+make-final)
406 (let-optionals* base+make-final
407 ((base "" (string? base))
408 (make-final (lambda (x) "") (procedure? make-final)))
409 (let lp ((chunks '()) ; Previously filled chunks
410 (nchars 0) ; Number of chars in CHUNKS
411 (chunk (make-string 40)) ; Current chunk into which we write
412 (chunk-len 40)
413 (i 40) ; Number of chars available in CHUNK
414 (seed seed))
415 (let lp2 ((i i) (seed seed)) ; Fill up CHUNK from right
416 (if (not (p seed)) ; to left.
417 (let ((c (f seed))
418 (seed (g seed)))
419 (if (> i 0)
420 (let ((i (- i 1)))
421 (string-set! chunk i c)
422 (lp2 i seed))
423
424 (let* ((nchars2 (+ chunk-len nchars))
425 (chunk-len2 (min 4096 nchars2))
426 (new-chunk (make-string chunk-len2))
427 (i (- chunk-len2 1)))
428 (string-set! new-chunk i c)
429 (lp (cons chunk chunks) (+ nchars chunk-len)
430 new-chunk chunk-len2 i seed))))
431
432 ;; We're done. Make the answer string & install the bits.
433 (let* ((final (make-final seed))
434 (flen (string-length final))
435 (base-len (string-length base))
436 (chunk-used (- chunk-len i))
437 (j (+ base-len nchars chunk-used))
438 (ans (make-string (+ j flen))))
439 (%string-copy! ans 0 final 0 flen) ; Install FINAL.
440 (%string-copy! ans flen chunk i chunk-len); Install CHUNK[I,).
441 (let lp ((j (+ flen chunk-used)) ; Install CHUNKS.
442 (chunks chunks))
443 (if (pair? chunks)
444 (let* ((chunk (car chunks))
445 (chunks (cdr chunks))
446 (chunk-len (string-length chunk)))
447 (%string-copy! ans j chunk 0 chunk-len)
448 (lp (+ j chunk-len) chunks))
449 (%string-copy! ans j base 0 base-len))); Install BASE.
450 ans))))))
451
452
453 (define (string-for-each proc s . maybe-start+end)
454 (check-arg procedure? proc string-for-each)
455 (let-string-start+end (start end) string-for-each s maybe-start+end
456 (let lp ((i start))
457 (if (< i end)
458 (begin (proc (string-ref s i))
459 (lp (+ i 1)))))))
460
461 (define (string-for-each-index proc s . maybe-start+end)
462 (check-arg procedure? proc string-for-each-index)
463 (let-string-start+end (start end) string-for-each-index s maybe-start+end
464 (let lp ((i start))
465 (if (< i end) (begin (proc i) (lp (+ i 1)))))))
466
467 (define (string-every criterion s . maybe-start+end)
468 (let-string-start+end (start end) string-every s maybe-start+end
469 (cond ((char? criterion)
470 (let lp ((i start))
471 (or (>= i end)
472 (and (char=? criterion (string-ref s i))
473 (lp (+ i 1))))))
474
475 ((char-set? criterion)
476 (let lp ((i start))
477 (or (>= i end)
478 (and (char-set-contains? criterion (string-ref s i))
479 (lp (+ i 1))))))
480
481 ((procedure? criterion) ; Slightly funky loop so that
482 (or (= start end) ; final (PRED S[END-1]) call
483 (let lp ((i start)) ; is a tail call.
484 (let ((c (string-ref s i))
485 (i1 (+ i 1)))
486 (if (= i1 end) (criterion c) ; Tail call.
487 (and (criterion c) (lp i1)))))))
488
489 (else (error "Second param is neither char-set, char, or predicate procedure."
490 string-every criterion)))))
491
492
493 (define (string-any criterion s . maybe-start+end)
494 (let-string-start+end (start end) string-any s maybe-start+end
495 (cond ((char? criterion)
496 (let lp ((i start))
497 (and (< i end)
498 (or (char=? criterion (string-ref s i))
499 (lp (+ i 1))))))
500
501 ((char-set? criterion)
502 (let lp ((i start))
503 (and (< i end)
504 (or (char-set-contains? criterion (string-ref s i))
505 (lp (+ i 1))))))
506
507 ((procedure? criterion) ; Slightly funky loop so that
508 (and (< start end) ; final (PRED S[END-1]) call
509 (let lp ((i start)) ; is a tail call.
510 (let ((c (string-ref s i))
511 (i1 (+ i 1)))
512 (if (= i1 end) (criterion c) ; Tail call
513 (or (criterion c) (lp i1)))))))
514
515 (else (error "Second param is neither char-set, char, or predicate procedure."
516 string-any criterion)))))
517
518
519 (define (string-tabulate proc len)
520 (check-arg procedure? proc string-tabulate)
521 (check-arg (lambda (val) (and (integer? val) (exact? val) (<= 0 val)))
522 len string-tabulate)
523 (let ((s (make-string len)))
524 (do ((i (- len 1) (- i 1)))
525 ((< i 0))
526 (string-set! s i (proc i)))
527 s))
528
529
530
531 ;;; string-prefix-length[-ci] s1 s2 [start1 end1 start2 end2]
532 ;;; string-suffix-length[-ci] s1 s2 [start1 end1 start2 end2]
533 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
534 ;;; Find the length of the common prefix/suffix.
535 ;;; It is not required that the two substrings passed be of equal length.
536 ;;; This was microcode in MIT Scheme -- a very tightly bummed primitive.
537 ;;; %STRING-PREFIX-LENGTH is the core routine of all string-comparisons,
538 ;;; so should be as tense as possible.
539
540 (define (%string-prefix-length s1 start1 end1 s2 start2 end2)
541 (let* ((delta (min (- end1 start1) (- end2 start2)))
542 (end1 (+ start1 delta)))
543
544 (if (and (eq? s1 s2) (= start1 start2)) ; EQ fast path
545 delta
546
547 (let lp ((i start1) (j start2)) ; Regular path
548 (if (or (>= i end1)
549 (not (char=? (string-ref s1 i)
550 (string-ref s2 j))))
551 (- i start1)
552 (lp (+ i 1) (+ j 1)))))))
553
554 (define (%string-suffix-length s1 start1 end1 s2 start2 end2)
555 (let* ((delta (min (- end1 start1) (- end2 start2)))
556 (start1 (- end1 delta)))
557
558 (if (and (eq? s1 s2) (= end1 end2)) ; EQ fast path
559 delta
560
561 (let lp ((i (- end1 1)) (j (- end2 1))) ; Regular path
562 (if (or (< i start1)
563 (not (char=? (string-ref s1 i)
564 (string-ref s2 j))))
565 (- (- end1 i) 1)
566 (lp (- i 1) (- j 1)))))))
567
568 (define (%string-prefix-length-ci s1 start1 end1 s2 start2 end2)
569 (let* ((delta (min (- end1 start1) (- end2 start2)))
570 (end1 (+ start1 delta)))
571
572 (if (and (eq? s1 s2) (= start1 start2)) ; EQ fast path
573 delta
574
575 (let lp ((i start1) (j start2)) ; Regular path
576 (if (or (>= i end1)
577 (not (char-ci=? (string-ref s1 i)
578 (string-ref s2 j))))
579 (- i start1)
580 (lp (+ i 1) (+ j 1)))))))
581
582 (define (%string-suffix-length-ci s1 start1 end1 s2 start2 end2)
583 (let* ((delta (min (- end1 start1) (- end2 start2)))
584 (start1 (- end1 delta)))
585
586 (if (and (eq? s1 s2) (= end1 end2)) ; EQ fast path
587 delta
588
589 (let lp ((i (- end1 1)) (j (- end2 1))) ; Regular path
590 (if (or (< i start1)
591 (not (char-ci=? (string-ref s1 i)
592 (string-ref s2 j))))
593 (- (- end1 i) 1)
594 (lp (- i 1) (- j 1)))))))
595
596
597 (define (string-prefix-length s1 s2 . maybe-starts+ends)
598 (let-string-start+end2 (start1 end1 start2 end2)
599 string-prefix-length s1 s2 maybe-starts+ends
600 (%string-prefix-length s1 start1 end1 s2 start2 end2)))
601
602 (define (string-suffix-length s1 s2 . maybe-starts+ends)
603 (let-string-start+end2 (start1 end1 start2 end2)
604 string-suffix-length s1 s2 maybe-starts+ends
605 (%string-suffix-length s1 start1 end1 s2 start2 end2)))
606
607 (define (string-prefix-length-ci s1 s2 . maybe-starts+ends)
608 (let-string-start+end2 (start1 end1 start2 end2)
609 string-prefix-length-ci s1 s2 maybe-starts+ends
610 (%string-prefix-length-ci s1 start1 end1 s2 start2 end2)))
611
612 (define (string-suffix-length-ci s1 s2 . maybe-starts+ends)
613 (let-string-start+end2 (start1 end1 start2 end2)
614 string-suffix-length-ci s1 s2 maybe-starts+ends
615 (%string-suffix-length-ci s1 start1 end1 s2 start2 end2)))
616
617
618 ;;; string-prefix? s1 s2 [start1 end1 start2 end2]
619 ;;; string-suffix? s1 s2 [start1 end1 start2 end2]
620 ;;; string-prefix-ci? s1 s2 [start1 end1 start2 end2]
621 ;;; string-suffix-ci? s1 s2 [start1 end1 start2 end2]
622 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
623 ;;; These are all simple derivatives of the previous counting funs.
624
625 (define (string-prefix? s1 s2 . maybe-starts+ends)
626 (let-string-start+end2 (start1 end1 start2 end2)
627 string-prefix? s1 s2 maybe-starts+ends
628 (%string-prefix? s1 start1 end1 s2 start2 end2)))
629
630 (define (string-suffix? s1 s2 . maybe-starts+ends)
631 (let-string-start+end2 (start1 end1 start2 end2)
632 string-suffix? s1 s2 maybe-starts+ends
633 (%string-suffix? s1 start1 end1 s2 start2 end2)))
634
635 (define (string-prefix-ci? s1 s2 . maybe-starts+ends)
636 (let-string-start+end2 (start1 end1 start2 end2)
637 string-prefix-ci? s1 s2 maybe-starts+ends
638 (%string-prefix-ci? s1 start1 end1 s2 start2 end2)))
639
640 (define (string-suffix-ci? s1 s2 . maybe-starts+ends)
641 (let-string-start+end2 (start1 end1 start2 end2)
642 string-suffix-ci? s1 s2 maybe-starts+ends
643 (%string-suffix-ci? s1 start1 end1 s2 start2 end2)))
644
645
646 ;;; Here are the internal routines that do the real work.
647
648 (define (%string-prefix? s1 start1 end1 s2 start2 end2)
649 (let ((len1 (- end1 start1)))
650 (and (<= len1 (- end2 start2)) ; Quick check
651 (= (%string-prefix-length s1 start1 end1
652 s2 start2 end2)
653 len1))))
654
655 (define (%string-suffix? s1 start1 end1 s2 start2 end2)
656 (let ((len1 (- end1 start1)))
657 (and (<= len1 (- end2 start2)) ; Quick check
658 (= len1 (%string-suffix-length s1 start1 end1
659 s2 start2 end2)))))
660
661 (define (%string-prefix-ci? s1 start1 end1 s2 start2 end2)
662 (let ((len1 (- end1 start1)))
663 (and (<= len1 (- end2 start2)) ; Quick check
664 (= len1 (%string-prefix-length-ci s1 start1 end1
665 s2 start2 end2)))))
666
667 (define (%string-suffix-ci? s1 start1 end1 s2 start2 end2)
668 (let ((len1 (- end1 start1)))
669 (and (<= len1 (- end2 start2)) ; Quick check
670 (= len1 (%string-suffix-length-ci s1 start1 end1
671 s2 start2 end2)))))
672
673
674 ;;; string-compare s1 s2 proc< proc= proc> [start1 end1 start2 end2]
675 ;;; string-compare-ci s1 s2 proc< proc= proc> [start1 end1 start2 end2]
676 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
677 ;;; Primitive string-comparison functions.
678 ;;; Continuation order is different from MIT Scheme.
679 ;;; Continuations are applied to s1's mismatch index;
680 ;;; in the case of equality, this is END1.
681
682 (define (%string-compare s1 start1 end1 s2 start2 end2
683 proc< proc= proc>)
684 (let ((size1 (- end1 start1))
685 (size2 (- end2 start2)))
686 (let ((match (%string-prefix-length s1 start1 end1 s2 start2 end2)))
687 (if (= match size1)
688 ((if (= match size2) proc= proc<) end1)
689 ((if (= match size2)
690 proc>
691 (if (char<? (string-ref s1 (+ start1 match))
692 (string-ref s2 (+ start2 match)))
693 proc< proc>))
694 (+ match start1))))))
695
696 (define (%string-compare-ci s1 start1 end1 s2 start2 end2
697 proc< proc= proc>)
698 (let ((size1 (- end1 start1))
699 (size2 (- end2 start2)))
700 (let ((match (%string-prefix-length-ci s1 start1 end1 s2 start2 end2)))
701 (if (= match size1)
702 ((if (= match size2) proc= proc<) end1)
703 ((if (= match size2) proc>
704 (if (char-ci<? (string-ref s1 (+ start1 match))
705 (string-ref s2 (+ start2 match)))
706 proc< proc>))
707 (+ start1 match))))))
708
709 (define (string-compare s1 s2 proc< proc= proc> . maybe-starts+ends)
710 (check-arg procedure? proc< string-compare)
711 (check-arg procedure? proc= string-compare)
712 (check-arg procedure? proc> string-compare)
713 (let-string-start+end2 (start1 end1 start2 end2)
714 string-compare s1 s2 maybe-starts+ends
715 (%string-compare s1 start1 end1 s2 start2 end2 proc< proc= proc>)))
716
717 (define (string-compare-ci s1 s2 proc< proc= proc> . maybe-starts+ends)
718 (check-arg procedure? proc< string-compare-ci)
719 (check-arg procedure? proc= string-compare-ci)
720 (check-arg procedure? proc> string-compare-ci)
721 (let-string-start+end2 (start1 end1 start2 end2)
722 string-compare-ci s1 s2 maybe-starts+ends
723 (%string-compare-ci s1 start1 end1 s2 start2 end2 proc< proc= proc>)))
724
725
726
727 ;;; string= string<> string-ci= string-ci<>
728 ;;; string< string> string-ci< string-ci>
729 ;;; string<= string>= string-ci<= string-ci>=
730 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
731 ;;; Simple definitions in terms of the previous comparison funs.
732 ;;; I sure hope the %STRING-COMPARE calls get integrated.
733
734 (define (string= s1 s2 . maybe-starts+ends)
735 (let-string-start+end2 (start1 end1 start2 end2)
736 string= s1 s2 maybe-starts+ends
737 (and (= (- end1 start1) (- end2 start2)) ; Quick filter
738 (or (and (eq? s1 s2) (= start1 start2)) ; Fast path
739 (%string-compare s1 start1 end1 s2 start2 end2 ; Real test
740 (lambda (i) #f)
741 values
742 (lambda (i) #f))))))
743
744 (define (string<> s1 s2 . maybe-starts+ends)
745 (let-string-start+end2 (start1 end1 start2 end2)
746 string<> s1 s2 maybe-starts+ends
747 (or (not (= (- end1 start1) (- end2 start2))) ; Fast path
748 (and (not (and (eq? s1 s2) (= start1 start2))) ; Quick filter
749 (%string-compare s1 start1 end1 s2 start2 end2 ; Real test
750 values
751 (lambda (i) #f)
752 values)))))
753
754 (define (string< s1 s2 . maybe-starts+ends)
755 (let-string-start+end2 (start1 end1 start2 end2)
756 string< s1 s2 maybe-starts+ends
757 (if (and (eq? s1 s2) (= start1 start2)) ; Fast path
758 (< end1 end2)
759
760 (%string-compare s1 start1 end1 s2 start2 end2 ; Real test
761 values
762 (lambda (i) #f)
763 (lambda (i) #f)))))
764
765 (define (string> s1 s2 . maybe-starts+ends)
766 (let-string-start+end2 (start1 end1 start2 end2)
767 string> s1 s2 maybe-starts+ends
768 (if (and (eq? s1 s2) (= start1 start2)) ; Fast path
769 (> end1 end2)
770
771 (%string-compare s1 start1 end1 s2 start2 end2 ; Real test
772 (lambda (i) #f)
773 (lambda (i) #f)
774 values))))
775
776 (define (string<= s1 s2 . maybe-starts+ends)
777 (let-string-start+end2 (start1 end1 start2 end2)
778 string<= s1 s2 maybe-starts+ends
779 (if (and (eq? s1 s2) (= start1 start2)) ; Fast path
780 (<= end1 end2)
781
782 (%string-compare s1 start1 end1 s2 start2 end2 ; Real test
783 values
784 values
785 (lambda (i) #f)))))
786
787 (define (string>= s1 s2 . maybe-starts+ends)
788 (let-string-start+end2 (start1 end1 start2 end2)
789 string>= s1 s2 maybe-starts+ends
790 (if (and (eq? s1 s2) (= start1 start2)) ; Fast path
791 (>= end1 end2)
792
793 (%string-compare s1 start1 end1 s2 start2 end2 ; Real test
794 (lambda (i) #f)
795 values
796 values))))
797
798 (define (string-ci= s1 s2 . maybe-starts+ends)
799 (let-string-start+end2 (start1 end1 start2 end2)
800 string-ci= s1 s2 maybe-starts+ends
801 (and (= (- end1 start1) (- end2 start2)) ; Quick filter
802 (or (and (eq? s1 s2) (= start1 start2)) ; Fast path
803 (%string-compare-ci s1 start1 end1 s2 start2 end2 ; Real test
804 (lambda (i) #f)
805 values
806 (lambda (i) #f))))))
807
808 (define (string-ci<> s1 s2 . maybe-starts+ends)
809 (let-string-start+end2 (start1 end1 start2 end2)
810 string-ci<> s1 s2 maybe-starts+ends
811 (or (not (= (- end1 start1) (- end2 start2))) ; Fast path
812 (and (not (and (eq? s1 s2) (= start1 start2))) ; Quick filter
813 (%string-compare-ci s1 start1 end1 s2 start2 end2 ; Real test
814 values
815 (lambda (i) #f)
816 values)))))
817
818 (define (string-ci< s1 s2 . maybe-starts+ends)
819 (let-string-start+end2 (start1 end1 start2 end2)
820 string-ci< s1 s2 maybe-starts+ends
821 (if (and (eq? s1 s2) (= start1 start2)) ; Fast path
822 (< end1 end2)
823
824 (%string-compare-ci s1 start1 end1 s2 start2 end2 ; Real test
825 values
826 (lambda (i) #f)
827 (lambda (i) #f)))))
828
829 (define (string-ci> s1 s2 . maybe-starts+ends)
830 (let-string-start+end2 (start1 end1 start2 end2)
831 string-ci> s1 s2 maybe-starts+ends
832 (if (and (eq? s1 s2) (= start1 start2)) ; Fast path
833 (> end1 end2)
834
835 (%string-compare-ci s1 start1 end1 s2 start2 end2 ; Real test
836 (lambda (i) #f)
837 (lambda (i) #f)
838 values))))
839
840 (define (string-ci<= s1 s2 . maybe-starts+ends)
841 (let-string-start+end2 (start1 end1 start2 end2)
842 string-ci<= s1 s2 maybe-starts+ends
843 (if (and (eq? s1 s2) (= start1 start2)) ; Fast path
844 (<= end1 end2)
845
846 (%string-compare-ci s1 start1 end1 s2 start2 end2 ; Real test
847 values
848 values
849 (lambda (i) #f)))))
850
851 (define (string-ci>= s1 s2 . maybe-starts+ends)
852 (let-string-start+end2 (start1 end1 start2 end2)
853 string-ci>= s1 s2 maybe-starts+ends
854 (if (and (eq? s1 s2) (= start1 start2)) ; Fast path
855 (>= end1 end2)
856
857 (%string-compare-ci s1 start1 end1 s2 start2 end2 ; Real test
858 (lambda (i) #f)
859 values
860 values))))
861
862
863 ;;; Hash
864 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
865 ;;; Compute (c + 37 c + 37^2 c + ...) modulo BOUND, with sleaze thrown in
866 ;;; to keep the intermediate values small. (We do the calculation with just
867 ;;; enough bits to represent BOUND, masking off high bits at each step in
868 ;;; calculation. If this screws up any important properties of the hash
869 ;;; function I'd like to hear about it. -Olin)
870 ;;;
871 ;;; If you keep BOUND small enough, the intermediate calculations will
872 ;;; always be fixnums. How small is dependent on the underlying Scheme system;
873 ;;; we use a default BOUND of 2^22 = 4194304, which should hack it in
874 ;;; Schemes that give you at least 29 signed bits for fixnums. The core
875 ;;; calculation that you don't want to overflow is, worst case,
876 ;;; (+ 65535 (* 37 (- bound 1)))
877 ;;; where 65535 is the max character code. Choose the default BOUND to be the
878 ;;; biggest power of two that won't cause this expression to fixnum overflow,
879 ;;; and everything will be copacetic.
880
881 (define (%string-hash s char->int bound start end)
882 (let ((iref (lambda (s i) (char->int (string-ref s i))))
883 ;; Compute a 111...1 mask that will cover BOUND-1:
884 (mask (let lp ((i #x10000)) ; Let's skip first 16 iterations, eh?
885 (if (>= i bound) (- i 1) (lp (+ i i))))))
886 (let lp ((i start) (ans 0))
887 (if (>= i end) (modulo ans bound)
888 (lp (+ i 1) (bitwise-and mask (+ (* 37 ans) (iref s i))))))))
889
890 (define (string-hash s . maybe-bound+start+end)
891 (let-optionals* maybe-bound+start+end ((bound 4194304 (and (integer? bound)
892 (exact? bound)
893 (<= 0 bound)))
894 rest)
895 (let ((bound (if (zero? bound) 4194304 bound))) ; 0 means default.
896 (let-string-start+end (start end) string-hash s rest
897 (%string-hash s char->integer bound start end)))))
898
899 (define (string-hash-ci s . maybe-bound+start+end)
900 (let-optionals* maybe-bound+start+end ((bound 4194304 (and (integer? bound)
901 (exact? bound)
902 (<= 0 bound)))
903 rest)
904 (let ((bound (if (zero? bound) 4194304 bound))) ; 0 means default.
905 (let-string-start+end (start end) string-hash-ci s rest
906 (%string-hash s (lambda (c) (char->integer (char-downcase c)))
907 bound start end)))))
908
909 ;;; Case hacking
910 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
911 ;;; string-upcase s [start end]
912 ;;; string-upcase! s [start end]
913 ;;; string-downcase s [start end]
914 ;;; string-downcase! s [start end]
915 ;;;
916 ;;; string-titlecase s [start end]
917 ;;; string-titlecase! s [start end]
918 ;;; Capitalize every contiguous alpha sequence: capitalise
919 ;;; first char, lowercase rest.
920
921 (define (string-upcase s . maybe-start+end)
922 (let-string-start+end (start end) string-upcase s maybe-start+end
923 (%string-map char-upcase s start end)))
924
925 (define (string-upcase! s . maybe-start+end)
926 (let-string-start+end (start end) string-upcase! s maybe-start+end
927 (%string-map! char-upcase s start end)))
928
929 (define (string-downcase s . maybe-start+end)
930 (let-string-start+end (start end) string-downcase s maybe-start+end
931 (%string-map char-downcase s start end)))
932
933 (define (string-downcase! s . maybe-start+end)
934 (let-string-start+end (start end) string-downcase! s maybe-start+end
935 (%string-map! char-downcase s start end)))
936
937 (define (%string-titlecase! s start end)
938 (let lp ((i start))
939 (cond ((string-index s char-cased? i end) =>
940 (lambda (i)
941 (string-set! s i (char-titlecase (string-ref s i)))
942 (let ((i1 (+ i 1)))
943 (cond ((string-skip s char-cased? i1 end) =>
944 (lambda (j)
945 (string-downcase! s i1 j)
946 (lp (+ j 1))))
947 (else (string-downcase! s i1 end)))))))))
948
949 (define (string-titlecase! s . maybe-start+end)
950 (let-string-start+end (start end) string-titlecase! s maybe-start+end
951 (%string-titlecase! s start end)))
952
953 (define (string-titlecase s . maybe-start+end)
954 (let-string-start+end (start end) string-titlecase! s maybe-start+end
955 (let ((ans (substring s start end)))
956 (%string-titlecase! ans 0 (- end start))
957 ans)))
958
959
960 ;;; Cutting & pasting strings
961 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
962 ;;; string-take string nchars
963 ;;; string-drop string nchars
964 ;;;
965 ;;; string-take-right string nchars
966 ;;; string-drop-right string nchars
967 ;;;
968 ;;; string-pad string k [char start end]
969 ;;; string-pad-right string k [char start end]
970 ;;;
971 ;;; string-trim string [char/char-set/pred start end]
972 ;;; string-trim-right string [char/char-set/pred start end]
973 ;;; string-trim-both string [char/char-set/pred start end]
974 ;;;
975 ;;; These trimmers invert the char-set meaning from MIT Scheme -- you
976 ;;; say what you want to trim.
977
978 (define (string-take s n)
979 (check-arg string? s string-take)
980 (check-arg (lambda (val) (and (integer? n) (exact? n)
981 (<= 0 n (string-length s))))
982 n string-take)
983 (%substring/shared s 0 n))
984
985 (define (string-take-right s n)
986 (check-arg string? s string-take-right)
987 (let ((len (string-length s)))
988 (check-arg (lambda (val) (and (integer? n) (exact? n) (<= 0 n len)))
989 n string-take-right)
990 (%substring/shared s (- len n) len)))
991
992 (define (string-drop s n)
993 (check-arg string? s string-drop)
994 (let ((len (string-length s)))
995 (check-arg (lambda (val) (and (integer? n) (exact? n) (<= 0 n len)))
996 n string-drop)
997 (%substring/shared s n len)))
998
999 (define (string-drop-right s n)
1000 (check-arg string? s string-drop-right)
1001 (let ((len (string-length s)))
1002 (check-arg (lambda (val) (and (integer? n) (exact? n) (<= 0 n len)))
1003 n string-drop-right)
1004 (%substring/shared s 0 (- len n))))
1005
1006
1007 (define (string-trim s . criterion+start+end)
1008 (let-optionals* criterion+start+end ((criterion char-set:whitespace) rest)
1009 (let-string-start+end (start end) string-trim s rest
1010 (cond ((string-skip s criterion start end) =>
1011 (lambda (i) (%substring/shared s i end)))
1012 (else "")))))
1013
1014 (define (string-trim-right s . criterion+start+end)
1015 (let-optionals* criterion+start+end ((criterion char-set:whitespace) rest)
1016 (let-string-start+end (start end) string-trim-right s rest
1017 (cond ((string-skip-right s criterion start end) =>
1018 (lambda (i) (%substring/shared s 0 (+ 1 i))))
1019 (else "")))))
1020
1021 (define (string-trim-both s . criterion+start+end)
1022 (let-optionals* criterion+start+end ((criterion char-set:whitespace) rest)
1023 (let-string-start+end (start end) string-trim-both s rest
1024 (cond ((string-skip s criterion start end) =>
1025 (lambda (i)
1026 (%substring/shared s i (+ 1 (string-skip-right s criterion i end)))))
1027 (else "")))))
1028
1029
1030 (define (string-pad-right s n . char+start+end)
1031 (let-optionals* char+start+end ((char #\space (char? char)) rest)
1032 (let-string-start+end (start end) string-pad-right s rest
1033 (check-arg (lambda (n) (and (integer? n) (exact? n) (<= 0 n)))
1034 n string-pad-right)
1035 (let ((len (- end start)))
1036 (if (<= n len)
1037 (%substring/shared s start (+ start n))
1038 (let ((ans (make-string n char)))
1039 (%string-copy! ans 0 s start end)
1040 ans))))))
1041
1042 (define (string-pad s n . char+start+end)
1043 (let-optionals* char+start+end ((char #\space (char? char)) rest)
1044 (let-string-start+end (start end) string-pad s rest
1045 (check-arg (lambda (n) (and (integer? n) (exact? n) (<= 0 n)))
1046 n string-pad)
1047 (let ((len (- end start)))
1048 (if (<= n len)
1049 (%substring/shared s (- end n) end)
1050 (let ((ans (make-string n char)))
1051 (%string-copy! ans (- n len) s start end)
1052 ans))))))
1053
1054
1055
1056 ;;; Filtering strings
1057 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1058 ;;; string-delete char/char-set/pred string [start end]
1059 ;;; string-filter char/char-set/pred string [start end]
1060 ;;;
1061 ;;; If the criterion is a char or char-set, we scan the string twice with
1062 ;;; string-fold -- once to determine the length of the result string,
1063 ;;; and once to do the filtered copy.
1064 ;;; If the criterion is a predicate, we don't do this double-scan strategy,
1065 ;;; because the predicate might have side-effects or be very expensive to
1066 ;;; compute. So we preallocate a temp buffer pessimistically, and only do
1067 ;;; one scan over S. This is likely to be faster and more space-efficient
1068 ;;; than consing a list.
1069
1070 (define (string-delete criterion s . maybe-start+end)
1071 (let-string-start+end (start end) string-delete s maybe-start+end
1072 (if (procedure? criterion)
1073 (let* ((slen (- end start))
1074 (temp (make-string slen))
1075 (ans-len (string-fold (lambda (c i)
1076 (if (criterion c) i
1077 (begin (string-set! temp i c)
1078 (+ i 1))))
1079 0 s start end)))
1080 (if (= ans-len slen) temp (substring temp 0 ans-len)))
1081
1082 (let* ((cset (cond ((char-set? criterion) criterion)
1083 ((char? criterion) (char-set criterion))
1084 (else (error "string-delete criterion not predicate, char or char-set" criterion))))
1085 (len (string-fold (lambda (c i) (if (char-set-contains? cset c)
1086 i
1087 (+ i 1)))
1088 0 s start end))
1089 (ans (make-string len)))
1090 (string-fold (lambda (c i) (if (char-set-contains? cset c)
1091 i
1092 (begin (string-set! ans i c)
1093 (+ i 1))))
1094 0 s start end)
1095 ans))))
1096
1097 (define (string-filter criterion s . maybe-start+end)
1098 (let-string-start+end (start end) string-filter s maybe-start+end
1099 (if (procedure? criterion)
1100 (let* ((slen (- end start))
1101 (temp (make-string slen))
1102 (ans-len (string-fold (lambda (c i)
1103 (if (criterion c)
1104 (begin (string-set! temp i c)
1105 (+ i 1))
1106 i))
1107 0 s start end)))
1108 (if (= ans-len slen) temp (substring temp 0 ans-len)))
1109
1110 (let* ((cset (cond ((char-set? criterion) criterion)
1111 ((char? criterion) (char-set criterion))
1112 (else (error "string-delete criterion not predicate, char or char-set" criterion))))
1113
1114 (len (string-fold (lambda (c i) (if (char-set-contains? cset c)
1115 (+ i 1)
1116 i))
1117 0 s start end))
1118 (ans (make-string len)))
1119 (string-fold (lambda (c i) (if (char-set-contains? cset c)
1120 (begin (string-set! ans i c)
1121 (+ i 1))
1122 i))
1123 0 s start end)
1124 ans))))
1125
1126
1127 ;;; String search
1128 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1129 ;;; string-index string char/char-set/pred [start end]
1130 ;;; string-index-right string char/char-set/pred [start end]
1131 ;;; string-skip string char/char-set/pred [start end]
1132 ;;; string-skip-right string char/char-set/pred [start end]
1133 ;;; string-count string char/char-set/pred [start end]
1134 ;;; There's a lot of replicated code here for efficiency.
1135 ;;; For example, the char/char-set/pred discrimination has
1136 ;;; been lifted above the inner loop of each proc.
1137
1138 (define (string-index str criterion . maybe-start+end)
1139 (let-string-start+end (start end) string-index str maybe-start+end
1140 (cond ((char? criterion)
1141 (let lp ((i start))
1142 (and (< i end)
1143 (if (char=? criterion (string-ref str i)) i
1144 (lp (+ i 1))))))
1145 ((char-set? criterion)
1146 (let lp ((i start))
1147 (and (< i end)
1148 (if (char-set-contains? criterion (string-ref str i)) i
1149 (lp (+ i 1))))))
1150 ((procedure? criterion)
1151 (let lp ((i start))
1152 (and (< i end)
1153 (if (criterion (string-ref str i)) i
1154 (lp (+ i 1))))))
1155 (else (error "Second param is neither char-set, char, or predicate procedure."
1156 string-index criterion)))))
1157
1158 (define (string-index-right str criterion . maybe-start+end)
1159 (let-string-start+end (start end) string-index-right str maybe-start+end
1160 (cond ((char? criterion)
1161 (let lp ((i (- end 1)))
1162 (and (>= i start)
1163 (if (char=? criterion (string-ref str i)) i
1164 (lp (- i 1))))))
1165 ((char-set? criterion)
1166 (let lp ((i (- end 1)))
1167 (and (>= i start)
1168 (if (char-set-contains? criterion (string-ref str i)) i
1169 (lp (- i 1))))))
1170 ((procedure? criterion)
1171 (let lp ((i (- end 1)))
1172 (and (>= i start)
1173 (if (criterion (string-ref str i)) i
1174 (lp (- i 1))))))
1175 (else (error "Second param is neither char-set, char, or predicate procedure."
1176 string-index-right criterion)))))
1177
1178 (define (string-skip str criterion . maybe-start+end)
1179 (let-string-start+end (start end) string-skip str maybe-start+end
1180 (cond ((char? criterion)
1181 (let lp ((i start))
1182 (and (< i end)
1183 (if (char=? criterion (string-ref str i))
1184 (lp (+ i 1))
1185 i))))
1186 ((char-set? criterion)
1187 (let lp ((i start))
1188 (and (< i end)
1189 (if (char-set-contains? criterion (string-ref str i))
1190 (lp (+ i 1))
1191 i))))
1192 ((procedure? criterion)
1193 (let lp ((i start))
1194 (and (< i end)
1195 (if (criterion (string-ref str i)) (lp (+ i 1))
1196 i))))
1197 (else (error "Second param is neither char-set, char, or predicate procedure."
1198 string-skip criterion)))))
1199
1200 (define (string-skip-right str criterion . maybe-start+end)
1201 (let-string-start+end (start end) string-skip-right str maybe-start+end
1202 (cond ((char? criterion)
1203 (let lp ((i (- end 1)))
1204 (and (>= i start)
1205 (if (char=? criterion (string-ref str i))
1206 (lp (- i 1))
1207 i))))
1208 ((char-set? criterion)
1209 (let lp ((i (- end 1)))
1210 (and (>= i start)
1211 (if (char-set-contains? criterion (string-ref str i))
1212 (lp (- i 1))
1213 i))))
1214 ((procedure? criterion)
1215 (let lp ((i (- end 1)))
1216 (and (>= i start)
1217 (if (criterion (string-ref str i)) (lp (- i 1))
1218 i))))
1219 (else (error "CRITERION param is neither char-set or char."
1220 string-skip-right criterion)))))
1221
1222
1223 (define (string-count s criterion . maybe-start+end)
1224 (let-string-start+end (start end) string-count s maybe-start+end
1225 (cond ((char? criterion)
1226 (do ((i start (+ i 1))
1227 (count 0 (if (char=? criterion (string-ref s i))
1228 (+ count 1)
1229 count)))
1230 ((>= i end) count)))
1231
1232 ((char-set? criterion)
1233 (do ((i start (+ i 1))
1234 (count 0 (if (char-set-contains? criterion (string-ref s i))
1235 (+ count 1)
1236 count)))
1237 ((>= i end) count)))
1238
1239 ((procedure? criterion)
1240 (do ((i start (+ i 1))
1241 (count 0 (if (criterion (string-ref s i)) (+ count 1) count)))
1242 ((>= i end) count)))
1243
1244 (else (error "CRITERION param is neither char-set or char."
1245 string-count criterion)))))
1246
1247
1248
1249 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1250 ;;; string-fill! string char [start end]
1251 ;;;
1252 ;;; string-copy! to tstart from [fstart fend]
1253 ;;; Guaranteed to work, even if s1 eq s2.
1254
1255 (define (string-fill! s char . maybe-start+end)
1256 (check-arg char? char string-fill!)
1257 (let-string-start+end (start end) string-fill! s maybe-start+end
1258 (do ((i (- end 1) (- i 1)))
1259 ((< i start))
1260 (string-set! s i char))))
1261
1262 (define (string-copy! to tstart from . maybe-fstart+fend)
1263 (let-string-start+end (fstart fend) string-copy! from maybe-fstart+fend
1264 (check-arg integer? tstart string-copy!)
1265 (check-substring-spec string-copy! to tstart (+ tstart (- fend fstart)))
1266 (%string-copy! to tstart from fstart fend)))
1267
1268 ;;; Library-internal routine
1269 (define (%string-copy! to tstart from fstart fend)
1270 (if (> fstart tstart)
1271 (do ((i fstart (+ i 1))
1272 (j tstart (+ j 1)))
1273 ((>= i fend))
1274 (string-set! to j (string-ref from i)))
1275
1276 (do ((i (- fend 1) (- i 1))
1277 (j (+ -1 tstart (- fend fstart)) (- j 1)))
1278 ((< i fstart))
1279 (string-set! to j (string-ref from i)))))
1280
1281
1282
1283 ;;; Returns starting-position in STRING or #f if not true.
1284 ;;; This implementation is slow & simple. It is useful as a "spec" or for
1285 ;;; comparison testing with fancier implementations.
1286 ;;; See below for fast KMP version.
1287
1288 ;(define (string-contains string substring . maybe-starts+ends)
1289 ; (let-string-start+end2 (start1 end1 start2 end2)
1290 ; string-contains string substring maybe-starts+ends
1291 ; (let* ((len (- end2 start2))
1292 ; (i-bound (- end1 len)))
1293 ; (let lp ((i start1))
1294 ; (and (< i i-bound)
1295 ; (if (string= string substring i (+ i len) start2 end2)
1296 ; i
1297 ; (lp (+ i 1))))))))
1298
1299
1300 ;;; Searching for an occurrence of a substring
1301 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1302
1303 (define (string-contains text pattern . maybe-starts+ends)
1304 (let-string-start+end2 (t-start t-end p-start p-end)
1305 string-contains text pattern maybe-starts+ends
1306 (%kmp-search pattern text char=? p-start p-end t-start t-end)))
1307
1308 (define (string-contains-ci text pattern . maybe-starts+ends)
1309 (let-string-start+end2 (t-start t-end p-start p-end)
1310 string-contains-ci text pattern maybe-starts+ends
1311 (%kmp-search pattern text char-ci=? p-start p-end t-start t-end)))
1312
1313
1314 ;;; Knuth-Morris-Pratt string searching
1315 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1316 ;;; See
1317 ;;; "Fast pattern matching in strings"
1318 ;;; SIAM J. Computing 6(2):323-350 1977
1319 ;;; D. E. Knuth, J. H. Morris and V. R. Pratt
1320 ;;; also described in
1321 ;;; "Pattern matching in strings"
1322 ;;; Alfred V. Aho
1323 ;;; Formal Language Theory - Perspectives and Open Problems
1324 ;;; Ronald V. Brook (editor)
1325 ;;; This algorithm is O(m + n) where m and n are the
1326 ;;; lengths of the pattern and string respectively
1327
1328 ;;; KMP search source[start,end) for PATTERN. Return starting index of
1329 ;;; leftmost match or #f.
1330
1331 (define (%kmp-search pattern text c= p-start p-end t-start t-end)
1332 (let ((plen (- p-end p-start))
1333 (rv (make-kmp-restart-vector pattern c= p-start p-end)))
1334
1335 ;; The search loop. TJ & PJ are redundant state.
1336 (let lp ((ti t-start) (pi 0)
1337 (tj (- t-end t-start)) ; (- tlen ti) -- how many chars left.
1338 (pj plen)) ; (- plen pi) -- how many chars left.
1339
1340 (if (= pi plen)
1341 (- ti plen) ; Win.
1342 (and (<= pj tj) ; Lose.
1343 (if (c= (string-ref text ti) ; Search.
1344 (string-ref pattern (+ p-start pi)))
1345 (lp (+ 1 ti) (+ 1 pi) (- tj 1) (- pj 1)) ; Advance.
1346
1347 (let ((pi (vector-ref rv pi))) ; Retreat.
1348 (if (= pi -1)
1349 (lp (+ ti 1) 0 (- tj 1) plen) ; Punt.
1350 (lp ti pi tj (- plen pi))))))))))
1351
1352 ;;; (make-kmp-restart-vector pattern [c= start end]) -> integer-vector
1353 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1354 ;;; Compute the KMP restart vector RV for string PATTERN. If
1355 ;;; we have matched chars 0..i-1 of PATTERN against a search string S, and
1356 ;;; PATTERN[i] doesn't match S[k], then reset i := RV[i], and try again to
1357 ;;; match S[k]. If RV[i] = -1, then punt S[k] completely, and move on to
1358 ;;; S[k+1] and PATTERN[0] -- no possible match of PAT[0..i] contains S[k].
1359 ;;;
1360 ;;; In other words, if you have matched the first i chars of PATTERN, but
1361 ;;; the i+1'th char doesn't match, RV[i] tells you what the next-longest
1362 ;;; prefix of PATTERN is that you have matched.
1363 ;;;
1364 ;;; - C= (default CHAR=?) is used to compare characters for equality.
1365 ;;; Pass in CHAR-CI=? for case-folded string search.
1366 ;;;
1367 ;;; - START & END restrict the pattern to the indicated substring; the
1368 ;;; returned vector will be of length END - START. The numbers stored
1369 ;;; in the vector will be values in the range [0,END-START) -- that is,
1370 ;;; they are valid indices into the restart vector; you have to add START
1371 ;;; to them to use them as indices into PATTERN.
1372 ;;;
1373 ;;; I've split this out as a separate function in case other constant-string
1374 ;;; searchers might want to use it.
1375 ;;;
1376 ;;; E.g.:
1377 ;;; a b d a b x
1378 ;;; #(-1 0 0 -1 1 2)
1379
1380 (define (make-kmp-restart-vector pattern . maybe-c=+start+end)
1381 (let-optionals* maybe-c=+start+end
1382 ((c= char=? (procedure? c=))
1383 ((start end) (lambda (args)
1384 (string-parse-start+end make-kmp-restart-vector
1385 pattern args))))
1386 (let* ((rvlen (- end start))
1387 (rv (make-vector rvlen -1)))
1388 (if (> rvlen 0)
1389 (let ((rvlen-1 (- rvlen 1))
1390 (c0 (string-ref pattern start)))
1391
1392 ;; Here's the main loop. We have set rv[0] ... rv[i].
1393 ;; K = I + START -- it is the corresponding index into PATTERN.
1394 (let lp1 ((i 0) (j -1) (k start))
1395 (if (< i rvlen-1)
1396 ;; lp2 invariant:
1397 ;; pat[(k-j) .. k-1] matches pat[start .. start+j-1]
1398 ;; or j = -1.
1399 (let lp2 ((j j))
1400 (cond ((= j -1)
1401 (let ((i1 (+ 1 i)))
1402 (if (not (c= (string-ref pattern (+ k 1)) c0))
1403 (vector-set! rv i1 0))
1404 (lp1 i1 0 (+ k 1))))
1405 ;; pat[(k-j) .. k] matches pat[start..start+j].
1406 ((c= (string-ref pattern k) (string-ref pattern (+ j start)))
1407 (let* ((i1 (+ 1 i))
1408 (j1 (+ 1 j)))
1409 (vector-set! rv i1 j1)
1410 (lp1 i1 j1 (+ k 1))))
1411
1412 (else (lp2 (vector-ref rv j)))))))))
1413 rv)))
1414
1415
1416 ;;; We've matched I chars from PAT. C is the next char from the search string.
1417 ;;; Return the new I after handling C.
1418 ;;;
1419 ;;; The pattern is (VECTOR-LENGTH RV) chars long, beginning at index PAT-START
1420 ;;; in PAT (PAT-START is usually 0). The I chars of the pattern we've matched
1421 ;;; are
1422 ;;; PAT[PAT-START .. PAT-START + I].
1423 ;;;
1424 ;;; It's *not* an oversight that there is no friendly error checking or
1425 ;;; defaulting of arguments. This is a low-level, inner-loop procedure
1426 ;;; that we want integrated/inlined into the point of call.
1427
1428 (define (kmp-step pat rv c i c= p-start)
1429 (let lp ((i i))
1430 (if (c= c (string-ref pat (+ i p-start))) ; Match =>
1431 (+ i 1) ; Done.
1432 (let ((i (vector-ref rv i))) ; Back up in PAT.
1433 (if (= i -1) 0 ; Can't back up further.
1434 (lp i)))))) ; Keep trying for match.
1435
1436 ;;; Zip through S[start,end), looking for a match of PAT. Assume we've
1437 ;;; already matched the first I chars of PAT when we commence at S[start].
1438 ;;; - <0: If we find a match *ending* at index J, return -J.
1439 ;;; - >=0: If we get to the end of the S[start,end) span without finding
1440 ;;; a complete match, return the number of chars from PAT we'd matched
1441 ;;; when we ran off the end.
1442 ;;;
1443 ;;; This is useful for searching *across* buffers -- that is, when your
1444 ;;; input comes in chunks of text. We hand-integrate the KMP-STEP loop
1445 ;;; for speed.
1446
1447 (define (string-kmp-partial-search pat rv s i . c=+p-start+s-start+s-end)
1448 (check-arg vector? rv string-kmp-partial-search)
1449 (let-optionals* c=+p-start+s-start+s-end
1450 ((c= char=? (procedure? c=))
1451 (p-start 0 (and (integer? p-start) (exact? p-start) (<= 0 p-start)))
1452 ((s-start s-end) (lambda (args)
1453 (string-parse-start+end string-kmp-partial-search
1454 s args))))
1455 (let ((patlen (vector-length rv)))
1456 (check-arg (lambda (i) (and (integer? i) (exact? i) (<= 0 i) (< i patlen)))
1457 i string-kmp-partial-search)
1458
1459 ;; Enough prelude. Here's the actual code.
1460 (let lp ((si s-start) ; An index into S.
1461 (vi i)) ; An index into RV.
1462 (cond ((= vi patlen) (- si)) ; Win.
1463 ((= si s-end) vi) ; Ran off the end.
1464 (else ; Match s[si] & loop.
1465 (let ((c (string-ref s si)))
1466 (lp (+ si 1)
1467 (let lp2 ((vi vi)) ; This is just KMP-STEP.
1468 (if (c= c (string-ref pat (+ vi p-start)))
1469 (+ vi 1)
1470 (let ((vi (vector-ref rv vi)))
1471 (if (= vi -1) 0
1472 (lp2 vi)))))))))))))
1473
1474
1475 ;;; Misc
1476 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1477 ;;; (string-null? s)
1478 ;;; (string-reverse s [start end])
1479 ;;; (string-reverse! s [start end])
1480 ;;; (reverse-list->string clist)
1481 ;;; (string->list s [start end])
1482
1483 (define (string-null? s) (zero? (string-length s)))
1484
1485 (define (string-reverse s . maybe-start+end)
1486 (let-string-start+end (start end) string-reverse s maybe-start+end
1487 (let* ((len (- end start))
1488 (ans (make-string len)))
1489 (do ((i start (+ i 1))
1490 (j (- len 1) (- j 1)))
1491 ((< j 0))
1492 (string-set! ans j (string-ref s i)))
1493 ans)))
1494
1495 (define (string-reverse! s . maybe-start+end)
1496 (let-string-start+end (start end) string-reverse! s maybe-start+end
1497 (do ((i (- end 1) (- i 1))
1498 (j start (+ j 1)))
1499 ((<= i j))
1500 (let ((ci (string-ref s i)))
1501 (string-set! s i (string-ref s j))
1502 (string-set! s j ci)))))
1503
1504
1505 (define (reverse-list->string clist)
1506 (let* ((len (length clist))
1507 (s (make-string len)))
1508 (do ((i (- len 1) (- i 1)) (clist clist (cdr clist)))
1509 ((not (pair? clist)))
1510 (string-set! s i (car clist)))
1511 s))
1512
1513
1514 ;(define (string->list s . maybe-start+end)
1515 ; (apply string-fold-right cons '() s maybe-start+end))
1516
1517 (define (string->list s . maybe-start+end)
1518 (let-string-start+end (start end) string->list s maybe-start+end
1519 (do ((i (- end 1) (- i 1))
1520 (ans '() (cons (string-ref s i) ans)))
1521 ((< i start) ans))))
1522
1523 ;;; Defined by R5RS, so commented out here.
1524 ;(define (list->string lis) (string-unfold null? car cdr lis))
1525
1526
1527 ;;; string-concatenate string-list -> string
1528 ;;; string-concatenate/shared string-list -> string
1529 ;;; string-append/shared s ... -> string
1530 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1531 ;;; STRING-APPEND/SHARED has license to return a string that shares storage
1532 ;;; with any of its arguments. In particular, if there is only one non-empty
1533 ;;; string amongst its parameters, it is permitted to return that string as
1534 ;;; its result. STRING-APPEND, by contrast, always allocates new storage.
1535 ;;;
1536 ;;; STRING-CONCATENATE & STRING-CONCATENATE/SHARED are passed a list of
1537 ;;; strings, which they concatenate into a result string. STRING-CONCATENATE
1538 ;;; always allocates a fresh string; STRING-CONCATENATE/SHARED may (or may
1539 ;;; not) return a result that shares storage with any of its arguments. In
1540 ;;; particular, if it is applied to a singleton list, it is permitted to
1541 ;;; return the car of that list as its value.
1542
1543 (define (string-append/shared . strings) (string-concatenate/shared strings))
1544
1545 (define (string-concatenate/shared strings)
1546 (let lp ((strings strings) (nchars 0) (first #f))
1547 (cond ((pair? strings) ; Scan the args, add up total
1548 (let* ((string (car strings)) ; length, remember 1st
1549 (tail (cdr strings)) ; non-empty string.
1550 (slen (string-length string)))
1551 (if (zero? slen)
1552 (lp tail nchars first)
1553 (lp tail (+ nchars slen) (or first strings)))))
1554
1555 ((zero? nchars) "")
1556
1557 ;; Just one non-empty string! Return it.
1558 ((= nchars (string-length (car first))) (car first))
1559
1560 (else (let ((ans (make-string nchars)))
1561 (let lp ((strings first) (i 0))
1562 (if (pair? strings)
1563 (let* ((s (car strings))
1564 (slen (string-length s)))
1565 (%string-copy! ans i s 0 slen)
1566 (lp (cdr strings) (+ i slen)))))
1567 ans)))))
1568
1569
1570 ; Alas, Scheme 48's APPLY blows up if you have many, many arguments.
1571 ;(define (string-concatenate strings) (apply string-append strings))
1572
1573 ;;; Here it is written out. I avoid using REDUCE to add up string lengths
1574 ;;; to avoid non-R5RS dependencies.
1575 (define (string-concatenate strings)
1576 (let* ((total (do ((strings strings (cdr strings))
1577 (i 0 (+ i (string-length (car strings)))))
1578 ((not (pair? strings)) i)))
1579 (ans (make-string total)))
1580 (let lp ((i 0) (strings strings))
1581 (if (pair? strings)
1582 (let* ((s (car strings))
1583 (slen (string-length s)))
1584 (%string-copy! ans i s 0 slen)
1585 (lp (+ i slen) (cdr strings)))))
1586 ans))
1587
1588
1589 ;;; Defined by R5RS, so commented out here.
1590 ;(define (string-append . strings) (string-concatenate strings))
1591
1592 ;;; string-concatenate-reverse string-list [final-string end] -> string
1593 ;;; string-concatenate-reverse/shared string-list [final-string end] -> string
1594 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1595 ;;; Return
1596 ;;; (string-concatenate
1597 ;;; (reverse
1598 ;;; (cons (substring final-string 0 end) string-list)))
1599
1600 (define (string-concatenate-reverse string-list . maybe-final+end)
1601 (let-optionals* maybe-final+end ((final "" (string? final))
1602 (end (string-length final)
1603 (and (integer? end)
1604 (exact? end)
1605 (<= 0 end (string-length final)))))
1606 (let ((len (let lp ((sum 0) (lis string-list))
1607 (if (pair? lis)
1608 (lp (+ sum (string-length (car lis))) (cdr lis))
1609 sum))))
1610
1611 (%finish-string-concatenate-reverse len string-list final end))))
1612
1613 (define (string-concatenate-reverse/shared string-list . maybe-final+end)
1614 (let-optionals* maybe-final+end ((final "" (string? final))
1615 (end (string-length final)
1616 (and (integer? end)
1617 (exact? end)
1618 (<= 0 end (string-length final)))))
1619 ;; Add up the lengths of all the strings in STRING-LIST; also get a
1620 ;; pointer NZLIST into STRING-LIST showing where the first non-zero-length
1621 ;; string starts.
1622 (let lp ((len 0) (nzlist #f) (lis string-list))
1623 (if (pair? lis)
1624 (let ((slen (string-length (car lis))))
1625 (lp (+ len slen)
1626 (if (or nzlist (zero? slen)) nzlist lis)
1627 (cdr lis)))
1628
1629 (cond ((zero? len) (substring/shared final 0 end))
1630
1631 ;; LEN > 0, so NZLIST is non-empty.
1632
1633 ((and (zero? end) (= len (string-length (car nzlist))))
1634 (car nzlist))
1635
1636 (else (%finish-string-concatenate-reverse len nzlist final end)))))))
1637
1638 (define (%finish-string-concatenate-reverse len string-list final end)
1639 (let ((ans (make-string (+ end len))))
1640 (%string-copy! ans len final 0 end)
1641 (let lp ((i len) (lis string-list))
1642 (if (pair? lis)
1643 (let* ((s (car lis))
1644 (lis (cdr lis))
1645 (slen (string-length s))
1646 (i (- i slen)))
1647 (%string-copy! ans i s 0 slen)
1648 (lp i lis))))
1649 ans))
1650
1651
1652
1653
1654 ;;; string-replace s1 s2 start1 end1 [start2 end2] -> string
1655 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1656 ;;; Replace S1[START1,END1) with S2[START2,END2).
1657
1658 (define (string-replace s1 s2 start1 end1 . maybe-start+end)
1659 (check-substring-spec string-replace s1 start1 end1)
1660 (let-string-start+end (start2 end2) string-replace s2 maybe-start+end
1661 (let* ((slen1 (string-length s1))
1662 (sublen2 (- end2 start2))
1663 (alen (+ (- slen1 (- end1 start1)) sublen2))
1664 (ans (make-string alen)))
1665 (%string-copy! ans 0 s1 0 start1)
1666 (%string-copy! ans start1 s2 start2 end2)
1667 (%string-copy! ans (+ start1 sublen2) s1 end1 slen1)
1668 ans)))
1669
1670
1671 ;;; string-tokenize s [token-set start end] -> list
1672 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1673 ;;; Break S up into a list of token strings, where a token is a maximal
1674 ;;; non-empty contiguous sequence of chars belonging to TOKEN-SET.
1675 ;;; (string-tokenize "hello, world") => ("hello," "world")
1676
1677 (define (string-tokenize s . token-chars+start+end)
1678 (let-optionals* token-chars+start+end
1679 ((token-chars char-set:graphic (char-set? token-chars)) rest)
1680 (let-string-start+end (start end) string-tokenize s rest
1681 (let lp ((i end) (ans '()))
1682 (cond ((and (< start i) (string-index-right s token-chars start i)) =>
1683 (lambda (tend-1)
1684 (let ((tend (+ 1 tend-1)))
1685 (cond ((string-skip-right s token-chars start tend-1) =>
1686 (lambda (tstart-1)
1687 (lp tstart-1
1688 (cons (substring s (+ 1 tstart-1) tend)
1689 ans))))
1690 (else (cons (substring s start tend) ans))))))
1691 (else ans))))))
1692
1693
1694 ;;; xsubstring s from [to start end] -> string
1695 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1696 ;;; S is a string; START and END are optional arguments that demarcate
1697 ;;; a substring of S, defaulting to 0 and the length of S (e.g., the whole
1698 ;;; string). Replicate this substring up and down index space, in both the
1699 ;; positive and negative directions. For example, if S = "abcdefg", START=3,
1700 ;;; and END=6, then we have the conceptual bidirectionally-infinite string
1701 ;;; ... d e f d e f d e f d e f d e f d e f d e f ...
1702 ;;; ... -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 ...
1703 ;;; XSUBSTRING returns the substring of this string beginning at index FROM,
1704 ;;; and ending at TO (which defaults to FROM+(END-START)).
1705 ;;;
1706 ;;; You can use XSUBSTRING in many ways:
1707 ;;; - To rotate a string left: (xsubstring "abcdef" 2) => "cdefab"
1708 ;;; - To rotate a string right: (xsubstring "abcdef" -2) => "efabcd"
1709 ;;; - To replicate a string: (xsubstring "abc" 0 7) => "abcabca"
1710 ;;;
1711 ;;; Note that
1712 ;;; - The FROM/TO indices give a half-open range -- the characters from
1713 ;;; index FROM up to, but not including index TO.
1714 ;;; - The FROM/TO indices are not in terms of the index space for string S.
1715 ;;; They are in terms of the replicated index space of the substring
1716 ;;; defined by S, START, and END.
1717 ;;;
1718 ;;; It is an error if START=END -- although this is allowed by special
1719 ;;; dispensation when FROM=TO.
1720
1721 (define (xsubstring s from . maybe-to+start+end)
1722 (check-arg (lambda (val) (and (integer? val) (exact? val)))
1723 from xsubstring)
1724 (receive (to start end)
1725 (if (pair? maybe-to+start+end)
1726 (let-string-start+end (start end) xsubstring s (cdr maybe-to+start+end)
1727 (let ((to (car maybe-to+start+end)))
1728 (check-arg (lambda (val) (and (integer? val)
1729 (exact? val)
1730 (<= from val)))
1731 to xsubstring)
1732 (values to start end)))
1733 (let ((slen (string-length (check-arg string? s xsubstring))))
1734 (values (+ from slen) 0 slen)))
1735 (let ((slen (- end start))
1736 (anslen (- to from)))
1737 (cond ((zero? anslen) "")
1738 ((zero? slen) (error "Cannot replicate empty (sub)string"
1739 xsubstring s from to start end))
1740
1741 ((= 1 slen) ; Fast path for 1-char replication.
1742 (make-string anslen (string-ref s start)))
1743
1744 ;; Selected text falls entirely within one span.
1745 ((= (floor (/ from slen)) (floor (/ to slen)))
1746 (substring s (+ start (modulo from slen))
1747 (+ start (modulo to slen))))
1748
1749 ;; Selected text requires multiple spans.
1750 (else (let ((ans (make-string anslen)))
1751 (%multispan-repcopy! ans 0 s from to start end)
1752 ans))))))
1753
1754
1755 ;;; string-xcopy! target tstart s sfrom [sto start end] -> unspecific
1756 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1757 ;;; Exactly the same as xsubstring, but the extracted text is written
1758 ;;; into the string TARGET starting at index TSTART.
1759 ;;; This operation is not defined if (EQ? TARGET S) -- you cannot copy
1760 ;;; a string on top of itself.
1761
1762 (define (string-xcopy! target tstart s sfrom . maybe-sto+start+end)
1763 (check-arg (lambda (val) (and (integer? val) (exact? val)))
1764 sfrom string-xcopy!)
1765 (receive (sto start end)
1766 (if (pair? maybe-sto+start+end)
1767 (let-string-start+end (start end) string-xcopy! s (cdr maybe-sto+start+end)
1768 (let ((sto (car maybe-sto+start+end)))
1769 (check-arg (lambda (val) (and (integer? val) (exact? val)))
1770 sto string-xcopy!)
1771 (values sto start end)))
1772 (let ((slen (string-length s)))
1773 (values (+ sfrom slen) 0 slen)))
1774
1775 (let* ((tocopy (- sto sfrom))
1776 (tend (+ tstart tocopy))
1777 (slen (- end start)))
1778 (check-substring-spec string-xcopy! target tstart tend)
1779 (cond ((zero? tocopy))
1780 ((zero? slen) (error "Cannot replicate empty (sub)string"
1781 string-xcopy!
1782 target tstart s sfrom sto start end))
1783
1784 ((= 1 slen) ; Fast path for 1-char replication.
1785 (string-fill! target (string-ref s start) tstart tend))
1786
1787 ;; Selected text falls entirely within one span.
1788 ((= (floor (/ sfrom slen)) (floor (/ sto slen)))
1789 (%string-copy! target tstart s
1790 (+ start (modulo sfrom slen))
1791 (+ start (modulo sto slen))))
1792
1793 ;; Multi-span copy.
1794 (else (%multispan-repcopy! target tstart s sfrom sto start end))))))
1795
1796 ;;; This is the core copying loop for XSUBSTRING and STRING-XCOPY!
1797 ;;; Internal -- not exported, no careful arg checking.
1798 (define (%multispan-repcopy! target tstart s sfrom sto start end)
1799 (let* ((slen (- end start))
1800 (i0 (+ start (modulo sfrom slen)))
1801 (total-chars (- sto sfrom)))
1802
1803 ;; Copy the partial span @ the beginning
1804 (%string-copy! target tstart s i0 end)
1805
1806 (let* ((ncopied (- end i0)) ; We've copied this many.
1807 (nleft (- total-chars ncopied)) ; # chars left to copy.
1808 (nspans (quotient nleft slen))) ; # whole spans to copy
1809
1810 ;; Copy the whole spans in the middle.
1811 (do ((i (+ tstart ncopied) (+ i slen)) ; Current target index.
1812 (nspans nspans (- nspans 1))) ; # spans to copy
1813 ((zero? nspans)
1814 ;; Copy the partial-span @ the end & we're done.
1815 (%string-copy! target i s start (+ start (- total-chars (- i tstart)))))
1816
1817 (%string-copy! target i s start end))))); Copy a whole span.
1818
1819
1820
1821 ;;; (string-join string-list [delimiter grammar]) => string
1822 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1823 ;;; Paste strings together using the delimiter string.
1824 ;;;
1825 ;;; (string-join '("foo" "bar" "baz") ":") => "foo:bar:baz"
1826 ;;;
1827 ;;; DELIMITER defaults to a single space " "
1828 ;;; GRAMMAR is one of the symbols {prefix, infix, strict-infix, suffix}
1829 ;;; and defaults to 'infix.
1830 ;;;
1831 ;;; I could rewrite this more efficiently -- precompute the length of the
1832 ;;; answer string, then allocate & fill it in iteratively. Using
1833 ;;; STRING-CONCATENATE is less efficient.
1834
1835 (define (string-join strings . delim+grammar)
1836 (let-optionals* delim+grammar ((delim " " (string? delim))
1837 (grammar 'infix))
1838 (let ((buildit (lambda (lis final)
1839 (let recur ((lis lis))
1840 (if (pair? lis)
1841 (cons delim (cons (car lis) (recur (cdr lis))))
1842 final)))))
1843
1844 (cond ((pair? strings)
1845 (string-concatenate
1846 (case grammar
1847
1848 ((infix strict-infix)
1849 (cons (car strings) (buildit (cdr strings) '())))
1850
1851 ((prefix) (buildit strings '()))
1852
1853 ((suffix)
1854 (cons (car strings) (buildit (cdr strings) (list delim))))
1855
1856 (else (error "Illegal join grammar"
1857 grammar string-join)))))
1858
1859 ((not (null? strings))
1860 (error "STRINGS parameter not list." strings string-join))
1861
1862 ;; STRINGS is ()
1863
1864 ((eq? grammar 'strict-infix)
1865 (error "Empty list cannot be joined with STRICT-INFIX grammar."
1866 string-join))
1867
1868 (else ""))))) ; Special-cased for infix grammar.
1869
1870
1871 ;;; Porting & performance-tuning notes
1872 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1873 ;;; See the section at the beginning of this file on external dependencies.
1874 ;;;
1875 ;;; The biggest issue with respect to porting is the LET-OPTIONALS* macro.
1876 ;;; There are many, many optional arguments in this library; the complexity
1877 ;;; of parsing, defaulting & type-testing these parameters is handled with the
1878 ;;; aid of this macro. There are about 15 uses of LET-OPTIONALS*. You can
1879 ;;; rewrite the uses, port the hairy macro definition (which is implemented
1880 ;;; using a Clinger-Rees low-level explicit-renaming macro system), or port
1881 ;;; the simple, high-level definition, which is less efficient.
1882 ;;;
1883 ;;; There is a fair amount of argument checking. This is, strictly speaking,
1884 ;;; unnecessary -- the actual body of the procedures will blow up if, say, a
1885 ;;; START/END index is improper. However, the error message will not be as
1886 ;;; good as if the error were caught at the "higher level." Also, a very, very
1887 ;;; smart Scheme compiler may be able to exploit having the type checks done
1888 ;;; early, so that the actual body of the procedures can assume proper values.
1889 ;;; This isn't likely; this kind of compiler technology isn't common any
1890 ;;; longer.
1891 ;;;
1892 ;;; The overhead of optional-argument parsing is irritating. The optional
1893 ;;; arguments must be consed into a rest list on entry, and then parsed out.
1894 ;;; Function call should be a matter of a few register moves and a jump; it
1895 ;;; should not involve heap allocation! Your Scheme system may have a superior
1896 ;;; non-R5RS optional-argument system that can eliminate this overhead. If so,
1897 ;;; then this is a prime candidate for optimising these procedures,
1898 ;;; *especially* the many optional START/END index parameters.
1899 ;;;
1900 ;;; Note that optional arguments are also a barrier to procedure integration.
1901 ;;; If your Scheme system permits you to specify alternate entry points
1902 ;;; for a call when the number of optional arguments is known in a manner
1903 ;;; that enables inlining/integration, this can provide performance
1904 ;;; improvements.
1905 ;;;
1906 ;;; There is enough *explicit* error checking that *all* string-index
1907 ;;; operations should *never* produce a bounds error. Period. Feel like
1908 ;;; living dangerously? *Big* performance win to be had by replacing
1909 ;;; STRING-REF's and STRING-SET!'s with unsafe equivalents in the loops.
1910 ;;; Similarly, fixnum-specific operators can speed up the arithmetic done on
1911 ;;; the index values in the inner loops. The only arguments that are not
1912 ;;; completely error checked are
1913 ;;; - string lists (complete checking requires time proportional to the
1914 ;;; length of the list)
1915 ;;; - procedure arguments, such as char->char maps & predicates.
1916 ;;; There is no way to check the range & domain of procedures in Scheme.
1917 ;;; Procedures that take these parameters cannot fully check their
1918 ;;; arguments. But all other types to all other procedures are fully
1919 ;;; checked.
1920 ;;;
1921 ;;; This does open up the alternate possibility of simply *removing* these
1922 ;;; checks, and letting the safe primitives raise the errors. On a dumb
1923 ;;; Scheme system, this would provide speed (by eliminating the redundant
1924 ;;; error checks) at the cost of error-message clarity.
1925 ;;;
1926 ;;; See the comments preceding the hash function code for notes on tuning
1927 ;;; the default bound so that the code never overflows your implementation's
1928 ;;; fixnum size into bignum calculation.
1929 ;;;
1930 ;;; In an interpreted Scheme, some of these procedures, or the internal
1931 ;;; routines with % prefixes, are excellent candidates for being rewritten
1932 ;;; in C. Consider STRING-HASH, %STRING-COMPARE, the
1933 ;;; %STRING-{SUF,PRE}FIX-LENGTH routines, STRING-COPY!, STRING-INDEX &
1934 ;;; STRING-SKIP (char-set & char cases), SUBSTRING and SUBSTRING/SHARED,
1935 ;;; %KMP-SEARCH, and %MULTISPAN-REPCOPY!.
1936 ;;;
1937 ;;; It would also be nice to have the ability to mark some of these
1938 ;;; routines as candidates for inlining/integration.
1939 ;;;
1940 ;;; All the %-prefixed routines in this source code are written
1941 ;;; to be called internally to this library. They do *not* perform
1942 ;;; friendly error checks on the inputs; they assume everything is
1943 ;;; proper. They also do not take optional arguments. These two properties
1944 ;;; save calling overhead and enable procedure integration -- but they
1945 ;;; are not appropriate for exported routines.
1946
1947
1948 ;;; Copyright details
1949 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1950 ;;; The prefix/suffix and comparison routines in this code had (extremely
1951 ;;; distant) origins in MIT Scheme's string lib, and was substantially
1952 ;;; reworked by Olin Shivers ([email protected]) 9/98. As such, it is
1953 ;;; covered by MIT Scheme's open source copyright. See below for details.
1954 ;;;
1955 ;;; The KMP string-search code was influenced by implementations written
1956 ;;; by Stephen Bevan, Brian Dehneyer and Will Fitzgerald. However, this
1957 ;;; version was written from scratch by myself.
1958 ;;;
1959 ;;; The remainder of this code was written from scratch by myself for scsh.
1960 ;;; The scsh copyright is a BSD-style open source copyright. See below for
1961 ;;; details.
1962 ;;; -Olin Shivers
1963
1964 ;;; MIT Scheme copyright terms
1965 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1966 ;;; This material was developed by the Scheme project at the Massachusetts
1967 ;;; Institute of Technology, Department of Electrical Engineering and
1968 ;;; Computer Science. Permission to copy and modify this software, to
1969 ;;; redistribute either the original software or a modified version, and
1970 ;;; to use this software for any purpose is granted, subject to the
1971 ;;; following restrictions and understandings.
1972 ;;;
1973 ;;; 1. Any copy made of this software must include this copyright notice
1974 ;;; in full.
1975 ;;;
1976 ;;; 2. Users of this software agree to make their best efforts (a) to
1977 ;;; return to the MIT Scheme project any improvements or extensions that
1978 ;;; they make, so that these may be included in future releases; and (b)
1979 ;;; to inform MIT of noteworthy uses of this software.
1980 ;;;
1981 ;;; 3. All materials developed as a consequence of the use of this
1982 ;;; software shall duly acknowledge such use, in accordance with the usual
1983 ;;; standards of acknowledging credit in academic research.
1984 ;;;
1985 ;;; 4. MIT has made no warrantee or representation that the operation of
1986 ;;; this software will be error-free, and MIT is under no obligation to
1987 ;;; provide any services, by way of maintenance, update, or otherwise.
1988 ;;;
1989 ;;; 5. In conjunction with products arising from the use of this material,
1990 ;;; there shall be no use of the name of the Massachusetts Institute of
1991 ;;; Technology nor of any adaptation thereof in any advertising,
1992 ;;; promotional, or sales literature without prior written consent from
1993 ;;; MIT in each case.
1994
1995 ;;; Scsh copyright terms
1996 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1997 ;;; All rights reserved.
1998 ;;;
1999 ;;; Redistribution and use in source and binary forms, with or without
2000 ;;; modification, are permitted provided that the following conditions
2001 ;;; are met:
2002 ;;; 1. Redistributions of source code must retain the above copyright
2003 ;;; notice, this list of conditions and the following disclaimer.
2004 ;;; 2. Redistributions in binary form must reproduce the above copyright
2005 ;;; notice, this list of conditions and the following disclaimer in the
2006 ;;; documentation and/or other materials provided with the distribution.
2007 ;;; 3. The name of the authors may not be used to endorse or promote products
2008 ;;; derived from this software without specific prior written permission.
2009 ;;;
2010 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
2011 ;;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
2012 ;;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
2013 ;;; IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
2014 ;;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
2015 ;;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2016 ;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2017 ;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2018 ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2019 ;;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.