Debian Codegraph @

%3a152/portable.scm

raw symbols SCIP
1 ;;; SRFI 130 string library reference implementation -*- Scheme -*-
2 ;;; Olin Shivers 7/2000
3 ;;; John Cowan 4/2016
4 ;;;
5 ;;; Copyright (c) 1988-1994 Massachusetts Institute of Technology.
6 ;;; Copyright (c) 1998, 1999, 2000 Olin Shivers.
7 ;;; Copyright (c) 2016 John Cowan.
8 ;;; The details of the copyrights appear at the end of the file. Short
9 ;;; summary: BSD-style open source.
10
11 ;;; Imports
12 ;;; This is a fairly large library. While it was written for portability, you
13 ;;; must be aware of its dependencies in order to run it in a given scheme
14 ;;; implementation. Here is a complete list of the dependencies it has and the
15 ;;; assumptions it makes beyond stock R5RS Scheme:
16 ;;;
17 ;;; This code has the following non-R5RS dependencies:
18 ;;; - (RECEIVE (var ...) mv-exp body ...) multiple-value binding macro;
19 ;;;
20 ;;; - An n-ary ERROR procedure;
21 ;;;
22 ;;; - A simple CHECK-ARG procedure for checking parameter values; it is
23 ;;; Inserted here
24 (define check-arg
25 (lambda (pred val proc)
26 (if (pred val) val (error "Bad arg" val pred proc))))
27
28 ;;; - LET-OPTIONALS* macro for parsing, defaulting &
29 ;;; type-checking optional parameters from a rest argument;
30 ;;;
31 ;;; The code depends upon a small set of core string primitives from R5RS:
32 ;;; MAKE-STRING STRING-REF STRING? STRING-LENGTH SUBSTRING
33 ;;; (Actually, SUBSTRING is not a primitive, but we assume that an
34 ;;; implementation's native version is probably faster than one we could
35 ;;; define, so we import it from R5RS.)
36 ;;;
37 ;;;
38
39 (define (add1 n) (+ 1 n))
40
41 ;;; Enough introductory blather. On to the source code. (But see the end of
42 ;;; the file for further notes on porting & performance tuning.)
43
44
45 ;;; Support for START/END substring specs
46 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
47 ;;; This macro parses optional start/end arguments from arg lists, defaulting
48 ;;; them to 0/(string-length s), and checks them for correctness.
49
50 (define-syntax let-string-start+end
51 (syntax-rules ()
52 ((let-string-start+end (start end) proc s-exp args-exp body ...)
53 (receive (start end) (string-parse-final-start+end proc s-exp args-exp)
54 body ...))
55 ((let-string-start+end (start end rest) proc s-exp args-exp body ...)
56 (receive (rest start end) (string-parse-start+end proc s-exp args-exp)
57 body ...))))
58
59 ;;; This one parses out a *pair* of final start/end indices.
60 ;;; Not exported; for internal use.
61 (define-syntax let-string-start+end2
62 (syntax-rules ()
63 ((l-s-s+e2 (start1 end1 start2 end2) proc s1 s2 args body ...)
64 (let ((procv proc)) ; Make sure PROC is only evaluated once.
65 (let-string-start+end (start1 end1 rest) procv s1 args
66 (let-string-start+end (start2 end2) procv s2 rest
67 body ...))))))
68
69
70 ;;; Returns three values: rest start end
71
72 (define (string-parse-start+end proc s args)
73 (if (not (string? s)) (error "Non-string value" proc s))
74 (let ((slen (string-length s)))
75 (if (pair? args)
76
77 (let ((start (car args))
78 (args (cdr args)))
79 (if (and (integer? start) (exact? start) (>= start 0))
80 (receive (end args)
81 (if (pair? args)
82 (let ((end (car args))
83 (args (cdr args)))
84 (if (and (integer? end) (exact? end) (<= end slen))
85 (values end args)
86 (error "Illegal substring END spec" proc end s)))
87 (values slen args))
88 (if (<= start end) (values args start end)
89 (error "Illegal substring START/END spec"
90 proc start end s)))
91 (error "Illegal substring START spec" proc start s)))
92
93 (values '() 0 slen))))
94
95 (define (string-parse-final-start+end proc s args)
96 (receive (rest start end) (string-parse-start+end proc s args)
97 (if (pair? rest) (error "Extra arguments to procedure" proc rest)
98 (values start end))))
99
100 (define (substring-spec-ok? s start end)
101 (and (string? s)
102 (integer? start)
103 (exact? start)
104 (integer? end)
105 (exact? end)
106 (<= 0 start)
107 (<= start end)
108 (<= end (string-length s))))
109
110 (define (check-substring-spec proc s start end)
111 (if (not (substring-spec-ok? s start end))
112 (error "Illegal substring spec." proc s start end)))
113
114
115 ;;; Defined by R5RS, so commented out here.
116 ;(define (string . chars)
117 ; (let* ((len (length chars))
118 ; (ans (make-string len)))
119 ; (do ((i 0 (+ i 1))
120 ; (chars chars (cdr chars)))
121 ; ((>= i len))
122 ; (string-set! ans i (car chars)))
123 ; ans))
124 ;
125 ;(define (string . chars) (string-unfold null? car cdr chars))
126
127
128
129 ;;; substring S START [END]
130 ;;; string-copy S [START END]
131 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
132
133 ;;; All this goop is just arg parsing & checking surrounding a call to the
134 ;;; actual primitive, %SUBSTRING.
135
136 ;;; Split out so that other routines in this library can avoid arg-parsing
137 ;;; overhead for END parameter.
138 (define (%substring s start end)
139 (if (and (zero? start) (= end (string-length s))) s
140 (substring s start end)))
141
142 ;;; Basic iterators and other higher-order abstractions
143 ;;; (string-fold kons knil s [start end])
144 ;;; (string-fold-right kons knil s [start end])
145 ;;; (string-unfold p f g seed [base make-final])
146 ;;; (string-unfold-right p f g seed [base make-final])
147 ;;; (string-for-each proc s [start end])
148 ;;; (string-every char/pred s [start end])
149 ;;; (string-any char/pred s [start end])
150 ;;; (string-tabulate proc len)
151 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
152 ;;; You want compiler support for high-level transforms on fold and unfold ops.
153 ;;; You'd at least like a lot of inlining for clients of these procedures.
154 ;;; Don't hold your breath.
155
156 (define (string-fold kons knil s . maybe-start+end)
157 (check-arg procedure? kons string-fold)
158 (let-string-start+end (start end) string-fold s maybe-start+end
159 (let lp ((v knil) (i start))
160 (if (< i end) (lp (kons (string-ref s i) v) (+ i 1))
161 v))))
162
163 (define (string-fold-right kons knil s . maybe-start+end)
164 (check-arg procedure? kons string-fold-right)
165 (let-string-start+end (start end) string-fold-right s maybe-start+end
166 (let lp ((v knil) (i (- end 1)))
167 (if (>= i start) (lp (kons (string-ref s i) v) (- i 1))
168 v))))
169
170 ;;; (string-unfold p f g seed [base make-final])
171 ;;; This is the fundamental constructor for strings.
172 ;;; - G is used to generate a series of "seed" values from the initial seed:
173 ;;; SEED, (G SEED), (G^2 SEED), (G^3 SEED), ...
174 ;;; - P tells us when to stop -- when it returns true when applied to one
175 ;;; of these seed values.
176 ;;; - F maps each seed value to the corresponding character
177 ;;; in the result string. These chars are assembled into the
178 ;;; string in a left-to-right order.
179 ;;; - BASE is the optional initial/leftmost portion of the constructed string;
180 ;;; it defaults to the empty string "".
181 ;;; - MAKE-FINAL is applied to the terminal seed value (on which P returns
182 ;;; true) to produce the final/rightmost portion of the constructed string.
183 ;;; It defaults to (LAMBDA (X) "").
184 ;;;
185 ;;; In other words, the following (simple, inefficient) definition holds:
186 ;;; (define (string-unfold p f g seed base make-final)
187 ;;; (string-append base
188 ;;; (let recur ((seed seed))
189 ;;; (if (p seed) (make-final seed)
190 ;;; (string-append (string (f seed))
191 ;;; (recur (g seed)))))))
192 ;;;
193 ;;; STRING-UNFOLD is a fairly powerful constructor -- you can use it to
194 ;;; reverse a string, copy a string, convert a list to a string, read
195 ;;; a port into a string, and so forth. Examples:
196 ;;; (port->string port) =
197 ;;; (string-unfold (compose eof-object? peek-char)
198 ;;; read-char values port)
199 ;;;
200 ;;; (list->string lis) = (string-unfold null? car cdr lis)
201 ;;;
202 ;;; (tabulate-string f size) = (string-unfold (lambda (i) (= i size)) f add1 0)
203
204 ;;; A problem with the following simple formulation is that it pushes one
205 ;;; stack frame for every char in the result string -- an issue if you are
206 ;;; using it to read a 100kchar string. So we don't use it -- but I include
207 ;;; it to give a clear, straightforward description of what the function
208 ;;; does.
209
210 ;(define (string-unfold p f g seed base make-final)
211 ; (let ((ans (let recur ((seed seed) (i (string-length base)))
212 ; (if (p seed)
213 ; (let* ((final (make-final seed))
214 ; (ans (make-string (+ i (string-length final)))))
215 ; (string-copy! ans i final)
216 ; ans)
217 ;
218 ; (let* ((c (f seed))
219 ; (s (recur (g seed) (+ i 1))))
220 ; (string-set! s i c)
221 ; s)))))
222 ; (string-copy! ans 0 base)
223 ; ans))
224
225 ;;; The strategy is to allocate a series of chunks into which we stash the
226 ;;; chars as we generate them. Chunk size goes up in powers of two starting
227 ;;; with 40 and levelling out at 4k, i.e.
228 ;;; 40 40 80 160 320 640 1280 2560 4096 4096 4096 4096 4096...
229 ;;; This should work pretty well for short strings, 1-line (80 char) strings,
230 ;;; and longer ones. When done, we allocate an answer string and copy the
231 ;;; chars over from the chunk buffers.
232
233 (define (string-unfold p f g seed . base+make-final)
234 (check-arg procedure? p string-unfold)
235 (check-arg procedure? f string-unfold)
236 (check-arg procedure? g string-unfold)
237 (let-optionals* base+make-final
238 ((base "" (string? base))
239 (make-final (lambda (x) "") (procedure? make-final)))
240 (let lp ((chunks '()) ; Previously filled chunks
241 (nchars 0) ; Number of chars in CHUNKS
242 (chunk (make-string 40)) ; Current chunk into which we write
243 (chunk-len 40)
244 (i 0) ; Number of chars written into CHUNK
245 (seed seed))
246 (let lp2 ((i i) (seed seed))
247 (if (not (p seed))
248 (let ((c (f seed))
249 (seed (g seed)))
250 (if (< i chunk-len)
251 (begin (string-set! chunk i c)
252 (lp2 (+ i 1) seed))
253
254 (let* ((nchars2 (+ chunk-len nchars))
255 (chunk-len2 (min 4096 nchars2))
256 (new-chunk (make-string chunk-len2)))
257 (string-set! new-chunk 0 c)
258 (lp (cons chunk chunks) (+ nchars chunk-len)
259 new-chunk chunk-len2 1 seed))))
260
261 ;; We're done. Make the answer string & install the bits.
262 (let* ((final (make-final seed))
263 (flen (string-length final))
264 (base-len (string-length base))
265 (j (+ base-len nchars i))
266 (ans (make-string (+ j flen))))
267 (%string-copy! ans j final 0 flen) ; Install FINAL.
268 (let ((j (- j i)))
269 (%string-copy! ans j chunk 0 i) ; Install CHUNK[0,I).
270 (let lp ((j j) (chunks chunks)) ; Install CHUNKS.
271 (if (pair? chunks)
272 (let* ((chunk (car chunks))
273 (chunks (cdr chunks))
274 (chunk-len (string-length chunk))
275 (j (- j chunk-len)))
276 (%string-copy! ans j chunk 0 chunk-len)
277 (lp j chunks)))))
278 (%string-copy! ans 0 base 0 base-len) ; Install BASE.
279 ans))))))
280
281 (define (string-unfold-right p f g seed . base+make-final)
282 (let-optionals* base+make-final
283 ((base "" (string? base))
284 (make-final (lambda (x) "") (procedure? make-final)))
285 (let lp ((chunks '()) ; Previously filled chunks
286 (nchars 0) ; Number of chars in CHUNKS
287 (chunk (make-string 40)) ; Current chunk into which we write
288 (chunk-len 40)
289 (i 40) ; Number of chars available in CHUNK
290 (seed seed))
291 (let lp2 ((i i) (seed seed)) ; Fill up CHUNK from right
292 (if (not (p seed)) ; to left.
293 (let ((c (f seed))
294 (seed (g seed)))
295 (if (> i 0)
296 (let ((i (- i 1)))
297 (string-set! chunk i c)
298 (lp2 i seed))
299
300 (let* ((nchars2 (+ chunk-len nchars))
301 (chunk-len2 (min 4096 nchars2))
302 (new-chunk (make-string chunk-len2))
303 (i (- chunk-len2 1)))
304 (string-set! new-chunk i c)
305 (lp (cons chunk chunks) (+ nchars chunk-len)
306 new-chunk chunk-len2 i seed))))
307
308 ;; We're done. Make the answer string & install the bits.
309 (let* ((final (make-final seed))
310 (flen (string-length final))
311 (base-len (string-length base))
312 (chunk-used (- chunk-len i))
313 (j (+ base-len nchars chunk-used))
314 (ans (make-string (+ j flen))))
315 (%string-copy! ans 0 final 0 flen) ; Install FINAL.
316 (%string-copy! ans flen chunk i chunk-len); Install CHUNK[I,).
317 (let lp ((j (+ flen chunk-used)) ; Install CHUNKS.
318 (chunks chunks))
319 (if (pair? chunks)
320 (let* ((chunk (car chunks))
321 (chunks (cdr chunks))
322 (chunk-len (string-length chunk)))
323 (%string-copy! ans j chunk 0 chunk-len)
324 (lp (+ j chunk-len) chunks))
325 (%string-copy! ans j base 0 base-len))); Install BASE.
326 ans))))))
327
328
329 (define (string-every criterion s . maybe-start+end)
330 (let-string-start+end (start end) string-every s maybe-start+end
331 (or (= start end) ; final (PRED S[END-1]) call
332 (let lp ((i start)) ; is a tail call.
333 (let ((c (string-ref s i))
334 (i1 (+ i 1)))
335 (if (= i1 end) (criterion c) ; Tail call.
336 (and (criterion c) (lp i1))))))))
337
338
339
340 (define (string-any criterion s . maybe-start+end)
341 (let-string-start+end (start end) string-any s maybe-start+end
342 (and (< start end) ; final (PRED S[END-1]) call
343 (let lp ((i start)) ; is a tail call.
344 (let ((c (string-ref s i))
345 (i1 (+ i 1)))
346 (if (= i1 end) (criterion c) ; Tail call
347 (or (criterion c) (lp i1))))))))
348
349
350
351 (define (string-tabulate proc len)
352 (check-arg procedure? proc string-tabulate)
353 (check-arg (lambda (val) (and (integer? val) (exact? val) (<= 0 val)))
354 len string-tabulate)
355 (let ((s (make-string len)))
356 (do ((i (- len 1) (- i 1)))
357 ((< i 0))
358 (string-set! s i (proc i)))
359 s))
360
361
362
363 ;;; string-prefix-length s1 s2 [start1 end1 start2 end2]
364 ;;; string-suffix-length s1 s2 [start1 end1 start2 end2]
365 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
366 ;;; Find the length of the common prefix/suffix.
367 ;;; It is not required that the two substrings passed be of equal length.
368 ;;; This was microcode in MIT Scheme -- a very tightly bummed primitive.
369 ;;; %STRING-PREFIX-LENGTH is the core routine of all string-comparisons,
370 ;;; so should be as tense as possible.
371
372 (define (%string-prefix-length s1 start1 end1 s2 start2 end2)
373 (let* ((delta (min (- end1 start1) (- end2 start2)))
374 (end1 (+ start1 delta)))
375
376 (if (and (eq? s1 s2) (= start1 start2)) ; EQ fast path
377 delta
378
379 (let lp ((i start1) (j start2)) ; Regular path
380 (if (or (>= i end1)
381 (not (char=? (string-ref s1 i)
382 (string-ref s2 j))))
383 (- i start1)
384 (lp (+ i 1) (+ j 1)))))))
385
386 (define (%string-suffix-length s1 start1 end1 s2 start2 end2)
387 (let* ((delta (min (- end1 start1) (- end2 start2)))
388 (start1 (- end1 delta)))
389
390 (if (and (eq? s1 s2) (= end1 end2)) ; EQ fast path
391 delta
392
393 (let lp ((i (- end1 1)) (j (- end2 1))) ; Regular path
394 (if (or (< i start1)
395 (not (char=? (string-ref s1 i)
396 (string-ref s2 j))))
397 (- (- end1 i) 1)
398 (lp (- i 1) (- j 1)))))))
399
400 (define (string-prefix-length s1 s2 . maybe-starts+ends)
401 (let-string-start+end2 (start1 end1 start2 end2)
402 string-prefix-length s1 s2 maybe-starts+ends
403 (%string-prefix-length s1 start1 end1 s2 start2 end2)))
404
405 (define (string-suffix-length s1 s2 . maybe-starts+ends)
406 (let-string-start+end2 (start1 end1 start2 end2)
407 string-suffix-length s1 s2 maybe-starts+ends
408 (%string-suffix-length s1 start1 end1 s2 start2 end2)))
409
410 ;;; string-prefix? s1 s2 [start1 end1 start2 end2]
411 ;;; string-suffix? s1 s2 [start1 end1 start2 end2]
412 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
413 ;;; These are all simple derivatives of the previous counting funs.
414
415 (define (string-prefix? s1 s2 . maybe-starts+ends)
416 (let-string-start+end2 (start1 end1 start2 end2)
417 string-prefix? s1 s2 maybe-starts+ends
418 (%string-prefix? s1 start1 end1 s2 start2 end2)))
419
420 (define (string-suffix? s1 s2 . maybe-starts+ends)
421 (let-string-start+end2 (start1 end1 start2 end2)
422 string-suffix? s1 s2 maybe-starts+ends
423 (%string-suffix? s1 start1 end1 s2 start2 end2)))
424
425 ;;; Here are the internal routines that do the real work.
426
427 (define (%string-prefix? s1 start1 end1 s2 start2 end2)
428 (let ((len1 (- end1 start1)))
429 (and (<= len1 (- end2 start2)) ; Quick check
430 (= (%string-prefix-length s1 start1 end1
431 s2 start2 end2)
432 len1))))
433
434 (define (%string-suffix? s1 start1 end1 s2 start2 end2)
435 (let ((len1 (- end1 start1)))
436 (and (<= len1 (- end2 start2)) ; Quick check
437 (= len1 (%string-suffix-length s1 start1 end1
438 s2 start2 end2)))))
439
440
441
442 ;;; Cutting & pasting strings
443 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
444 ;;; string-take string nchars
445 ;;; string-drop string nchars
446 ;;;
447 ;;; string-take-right string nchars
448 ;;; string-drop-right string nchars
449 ;;;
450 ;;; string-pad string k [char start end]
451 ;;; string-pad-right string k [char start end]
452 ;;;
453 ;;; string-trim string [char/char-set/pred start end]
454 ;;; string-trim-right string [char/char-set/pred start end]
455 ;;; string-trim-both string [char/char-set/pred start end]
456 ;;;
457 ;;; These trimmers invert the char-set meaning from MIT Scheme -- you
458 ;;; say what you want to trim.
459
460 (define (string-take s n)
461 (check-arg string? s string-take)
462 (check-arg (lambda (val) (and (integer? n) (exact? n)
463 (<= 0 n (string-length s))))
464 n string-take)
465 (%substring s 0 n))
466
467 (define (string-take-right s n)
468 (check-arg string? s string-take-right)
469 (let ((len (string-length s)))
470 (check-arg (lambda (val) (and (integer? n) (exact? n) (<= 0 n len)))
471 n string-take-right)
472 (%substring s (- len n) len)))
473
474 (define (string-drop s n)
475 (check-arg string? s string-drop)
476 (let ((len (string-length s)))
477 (check-arg (lambda (val) (and (integer? n) (exact? n) (<= 0 n len)))
478 n string-drop)
479 (%substring s n len)))
480
481 (define (string-drop-right s n)
482 (check-arg string? s string-drop-right)
483 (let ((len (string-length s)))
484 (check-arg (lambda (val) (and (integer? n) (exact? n) (<= 0 n len)))
485 n string-drop-right)
486 (%substring s 0 (- len n))))
487
488
489 (define (string-trim s . criterion+start+end)
490 (let-optionals* criterion+start+end ((criterion char-whitespace?) rest)
491 (let-string-start+end (start end) string-trim s rest
492 (cond ((string-skip s criterion start end) =>
493 (lambda (i) (%substring s i end)))
494 (else "")))))
495
496 (define (string-trim-right s . criterion+start+end)
497 (let-optionals* criterion+start+end ((criterion char-whitespace?) rest)
498 (let-string-start+end (start end) string-trim-right s rest
499 (cond ((string-skip-right s criterion start end) =>
500 (lambda (i) (%substring s start (+ 1 i))))
501 (else "")))))
502
503 (define (string-trim-both s . criterion+start+end)
504 (let-optionals* criterion+start+end ((criterion char-whitespace?) rest)
505 (let-string-start+end (start end) string-trim-both s rest
506 (cond ((string-skip s criterion start end) =>
507 (lambda (i)
508 (%substring s i (+ 1 (string-skip-right s criterion i end)))))
509 (else "")))))
510
511
512 (define (string-pad-right s n . char+start+end)
513 (let-optionals* char+start+end ((char #\space (char? char)) rest)
514 (let-string-start+end (start end) string-pad-right s rest
515 (check-arg (lambda (n) (and (integer? n) (exact? n) (<= 0 n)))
516 n string-pad-right)
517 (let ((len (- end start)))
518 (if (<= n len)
519 (%substring s start (+ start n))
520 (let ((ans (make-string n char)))
521 (%string-copy! ans 0 s start end)
522 ans))))))
523
524 (define (string-pad s n . char+start+end)
525 (let-optionals* char+start+end ((char #\space (char? char)) rest)
526 (let-string-start+end (start end) string-pad s rest
527 (check-arg (lambda (n) (and (integer? n) (exact? n) (<= 0 n)))
528 n string-pad)
529 (let ((len (- end start)))
530 (if (<= n len)
531 (%substring s (- end n) end)
532 (let ((ans (make-string n char)))
533 (%string-copy! ans (- n len) s start end)
534 ans))))))
535
536
537 ;;; Filtering strings
538 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
539 ;;; string-remove char/pred string [start end]
540 ;;; string-filter char/pred string [start end]
541 ;;;
542 ;;; If the criterion is a predicate, we don't do this double-scan strategy,
543 ;;; because the predicate might have side-effects or be very expensive to
544 ;;; compute. So we preallocate a temp buffer pessimistically, and only do
545 ;;; one scan over S. This is likely to be faster and more space-efficient
546 ;;; than consing a list.
547
548 (define (string-remove criterion s . maybe-start+end)
549 (let-string-start+end (start end) string-remove s maybe-start+end
550 (let* ((slen (- end start))
551 (temp (make-string slen))
552 (ans-len (string-fold (lambda (c i)
553 (if (criterion c) i
554 (begin (string-set! temp i c)
555 (+ i 1))))
556 0 s start end)))
557 (if (= ans-len slen) temp (substring temp 0 ans-len)))))
558
559
560
561 (define (string-filter criterion s . maybe-start+end)
562 (let-string-start+end (start end) string-filter s maybe-start+end
563 (let* ((slen (- end start))
564 (temp (make-string slen))
565 (ans-len (string-fold (lambda (c i)
566 (if (criterion c)
567 (begin (string-set! temp i c)
568 (+ i 1))
569 i))
570 0 s start end)))
571 (if (= ans-len slen) temp (substring temp 0 ans-len)))))
572
573
574
575
576 ;;; String search
577 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
578 ;;; string-index string char/pred [start end]
579 ;;; string-index-right string char/pred [start end]
580 ;;; string-skip string char/pred [start end]
581 ;;; string-skip-right string char/pred [start end]
582 ;;; string-count string char/pred [start end]
583 ;;; There's a lot of replicated code here for efficiency.
584
585 (define (string-index str criterion . maybe-start+end)
586 (let-string-start+end (start end) string-index str maybe-start+end
587 (let lp ((i start))
588 (and (< i end)
589 (if (criterion (string-ref str i)) i
590 (lp (+ i 1)))))))
591
592 (define (string-index-right str criterion . maybe-start+end)
593 (let-string-start+end (start end) string-index-right str maybe-start+end
594 (let lp ((i (- end 1)))
595 (and (>= i start)
596 (if (criterion (string-ref str i)) i
597 (lp (- i 1)))))))
598
599 (define (string-skip str criterion . maybe-start+end)
600 (let-string-start+end (start end) string-skip str maybe-start+end
601 (let lp ((i start))
602 (and (< i end)
603 (if (criterion (string-ref str i)) (lp (+ i 1))
604 i)))))
605
606 (define (string-skip-right str criterion . maybe-start+end)
607 (let-string-start+end (start end) string-skip-right str maybe-start+end
608 (let lp ((i (- end 1)))
609 (and (>= i start)
610 (if (criterion (string-ref str i)) (lp (- i 1))
611 i)))))
612
613 ;;; Useful hacks added for SRFI 152
614
615 (define (string-take-while s criterion . maybe-start+end)
616 (let-string-start+end (start end) string-take-while s maybe-start+end
617 (let ((idx (string-skip s criterion start end)))
618 (if idx
619 (%substring s 0 idx)
620 ""))))
621
622 (define (string-take-while-right s criterion . maybe-start+end)
623 (let-string-start+end (start end) string-take-while s maybe-start+end
624 (let ((idx (string-skip-right s criterion start end)))
625 (if idx
626 (%substring s (+ idx 1) (string-length s))
627 ""))))
628
629 (define (string-drop-while s criterion . maybe-start+end)
630 (let-string-start+end (start end) string-drop-while s maybe-start+end
631 (let ((idx (string-skip s criterion start end)))
632 (if idx
633 (%substring s idx (string-length s))
634 s))))
635
636 (define (string-drop-while-right s criterion . maybe-start+end)
637 (let-string-start+end (start end) string-drop-while s maybe-start+end
638 (let ((idx (string-skip-right s criterion start end)))
639 (if idx
640 (%substring s 0 (+ idx 1))
641 s))))
642
643 (define (string-span s criterion . maybe-start+end)
644 (let-string-start+end (start end) string-span s maybe-start+end
645 (let ((idx (string-skip s criterion start end)))
646 (if idx
647 (values (%substring s 0 idx) (%substring s idx (string-length s)))
648 (values "" s)))))
649
650 (define (string-break s criterion . maybe-start+end)
651 (let-string-start+end (start end) string-break s maybe-start+end
652 (let ((idx (string-index s criterion start end)))
653 (if idx
654 (values (%substring s 0 idx) (%substring s idx (string-length s)))
655 (values s "")))))
656
657 (define (string-count s criterion . maybe-start+end)
658 (let-string-start+end (start end) string-count s maybe-start+end
659 (do ((i start (+ i 1))
660 (count 0 (if (criterion (string-ref s i)) (+ count 1) count)))
661 ((>= i end) count))))
662
663
664
665
666 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
667 ;;; %string-copy! to tstart from [fstart fend]
668 ;;; Guaranteed to work, even if s1 eq s2.
669 ;;; Library-internal routine
670 (define (%string-copy! to tstart from fstart fend)
671 (if (> fstart tstart)
672 (do ((i fstart (+ i 1))
673 (j tstart (+ j 1)))
674 ((>= i fend))
675 (string-set! to j (string-ref from i)))
676
677 (do ((i (- fend 1) (- i 1))
678 (j (+ -1 tstart (- fend fstart)) (- j 1)))
679 ((< i fstart))
680 (string-set! to j (string-ref from i)))))
681
682
683
684 ;;; Returns starting-position in STRING or #f if not true.
685 ;;; This implementation is slow & simple. It is useful as a "spec" or for
686 ;;; comparison testing with fancier implementations.
687 ;;; See below for fast KMP version.
688
689 ;(define (string-contains string substring . maybe-starts+ends)
690 ; (let-string-start+end2 (start1 end1 start2 end2)
691 ; string-contains string substring maybe-starts+ends
692 ; (let* ((len (- end2 start2))
693 ; (i-bound (- end1 len)))
694 ; (let lp ((i start1))
695 ; (and (< i i-bound)
696 ; (if (string= string substring i (+ i len) start2 end2)
697 ; i
698 ; (lp (+ i 1))))))))
699
700
701 ;;; Searching for an occurrence of a substring
702 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
703
704 (define (string-contains text pattern . maybe-starts+ends)
705 (let-string-start+end2 (t-start t-end p-start p-end)
706 string-contains text pattern maybe-starts+ends
707 (%kmp-search pattern text char=? p-start p-end t-start t-end)))
708
709 (define (string-contains-right text pattern . maybe-starts+ends)
710 (let-string-start+end2 (t-start t-end p-start p-end)
711 string-contains-right text pattern maybe-starts+ends
712 (let* ((t-len (string-length text))
713 (p-len (string-length pattern))
714 (p-size (- p-end p-start))
715 (rt-start (- t-len t-end))
716 (rt-end (- t-len t-start))
717 (rp-start (- p-len p-end))
718 (rp-end (- p-len p-start))
719 (res (%kmp-search (string-reverse pattern)
720 (string-reverse text)
721 char=? rp-start rp-end rt-start rt-end)))
722 (if res
723 (- t-len res p-size)
724 #f))))
725
726
727 ;;; Knuth-Morris-Pratt string searching
728 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
729 ;;; See
730 ;;; "Fast pattern matching in strings"
731 ;;; SIAM J. Computing 6(2):323-350 1977
732 ;;; D. E. Knuth, J. H. Morris and V. R. Pratt
733 ;;; also described in
734 ;;; "Pattern matching in strings"
735 ;;; Alfred V. Aho
736 ;;; Formal Language Theory - Perspectives and Open Problems
737 ;;; Ronald V. Brook (editor)
738 ;;; This algorithm is O(m + n) where m and n are the
739 ;;; lengths of the pattern and string respectively
740
741 ;;; KMP search source[start,end) for PATTERN. Return starting index of
742 ;;; leftmost match or #f.
743
744 (define (%kmp-search pattern text c= p-start p-end t-start t-end)
745 (let ((plen (- p-end p-start))
746 (rv (make-kmp-restart-vector pattern c= p-start p-end)))
747
748 ;; The search loop. TJ & PJ are redundant state.
749 (let lp ((ti t-start) (pi 0)
750 (tj (- t-end t-start)) ; (- tlen ti) -- how many chars left.
751 (pj plen)) ; (- plen pi) -- how many chars left.
752
753 (if (= pi plen)
754 (- ti plen) ; Win.
755 (and (<= pj tj) ; Lose.
756 (if (c= (string-ref text ti) ; Search.
757 (string-ref pattern (+ p-start pi)))
758 (lp (+ 1 ti) (+ 1 pi) (- tj 1) (- pj 1)) ; Advance.
759
760 (let ((pi (vector-ref rv pi))) ; Retreat.
761 (if (= pi -1)
762 (lp (+ ti 1) 0 (- tj 1) plen) ; Punt.
763 (lp ti pi tj (- plen pi))))))))))
764
765 ;;; (make-kmp-restart-vector pattern [c= start end]) -> integer-vector
766 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
767 ;;; Compute the KMP restart vector RV for string PATTERN. If
768 ;;; we have matched chars 0..i-1 of PATTERN against a search string S, and
769 ;;; PATTERN[i] doesn't match S[k], then reset i := RV[i], and try again to
770 ;;; match S[k]. If RV[i] = -1, then punt S[k] completely, and move on to
771 ;;; S[k+1] and PATTERN[0] -- no possible match of PAT[0..i] contains S[k].
772 ;;;
773 ;;; In other words, if you have matched the first i chars of PATTERN, but
774 ;;; the i+1'th char doesn't match, RV[i] tells you what the next-longest
775 ;;; prefix of PATTERN is that you have matched.
776 ;;;
777 ;;; - C= (default CHAR=?) is used to compare characters for equality.
778 ;;; Pass in CHAR-CI=? for case-folded string search.
779 ;;;
780 ;;; - START & END restrict the pattern to the indicated substring; the
781 ;;; returned vector will be of length END - START. The numbers stored
782 ;;; in the vector will be values in the range [0,END-START) -- that is,
783 ;;; they are valid indices into the restart vector; you have to add START
784 ;;; to them to use them as indices into PATTERN.
785 ;;;
786 ;;; I've split this out as a separate function in case other constant-string
787 ;;; searchers might want to use it.
788 ;;;
789 ;;; E.g.:
790 ;;; a b d a b x
791 ;;; #(-1 0 0 -1 1 2)
792
793 #;(define (make-kmp-restart-vector pattern . maybe-c=+start+end)
794 (let-optionals* maybe-c=+start+end
795 ((c= char=? (procedure? c=))
796 ((start end) (lambda (args)
797 (string-parse-start+end make-kmp-restart-vector
798 pattern args))))
799 (let* ((rvlen (- end start))
800 (rv (make-vector rvlen -1)))
801 (if (> rvlen 0)
802 (let ((rvlen-1 (- rvlen 1))
803 (c0 (string-ref pattern start)))
804
805 ;; Here's the main loop. We have set rv[0] ... rv[i].
806 ;; K = I + START -- it is the corresponding index into PATTERN.
807 (let lp1 ((i 0) (j -1) (k start))
808 (if (< i rvlen-1)
809 ;; lp2 invariant:
810 ;; pat[(k-j) .. k-1] matches pat[start .. start+j-1]
811 ;; or j = -1.
812 (let lp2 ((j j))
813 (cond ((= j -1)
814 (let ((i1 (+ 1 i)))
815 (if (not (c= (string-ref pattern (+ k 1)) c0))
816 (vector-set! rv i1 0))
817 (lp1 i1 0 (+ k 1))))
818 ;; pat[(k-j) .. k] matches pat[start..start+j].
819 ((c= (string-ref pattern k) (string-ref pattern (+ j start)))
820 (let* ((i1 (+ 1 i))
821 (j1 (+ 1 j)))
822 (vector-set! rv i1 j1)
823 (lp1 i1 j1 (+ k 1))))
824
825 (else (lp2 (vector-ref rv j)))))))))
826 rv)))
827
828
829 (define (make-kmp-restart-vector pattern . maybe-c=+start+end)
830 (let-optionals* maybe-c=+start+end
831 ((c= char=?) rest) ; (procedure? c=))
832 (receive (rest2 start end) (string-parse-start+end make-kmp-restart-vector pattern rest)
833 (let* ((rvlen (- end start))
834 (rv (make-vector rvlen -1)))
835 (if (> rvlen 0)
836 (let ((rvlen-1 (- rvlen 1))
837 (c0 (string-ref pattern start)))
838
839 ;; Here's the main loop. We have set rv[0] ... rv[i].
840 ;; K = I + START -- it is the corresponding index into PATTERN.
841 (let lp1 ((i 0) (j -1) (k start))
842 (if (< i rvlen-1)
843
844 ;; lp2 invariant:
845 ;; pat[(k-j) .. k-1] matches pat[start .. start+j-1]
846 ;; or j = -1.
847 (let lp2 ((j j))
848
849 (cond ((= j -1)
850 (let ((i1 (+ i 1))
851 (ck+1 (string-ref pattern (add1 k))))
852 (vector-set! rv i1 (if (c= ck+1 c0) -1 0))
853 (lp1 i1 0 (+ k 1))))
854
855 ;; pat[(k-j) .. k] matches pat[start..start+j].
856 ((c= (string-ref pattern k)
857 (string-ref pattern (+ j start)))
858 (let* ((i1 (+ 1 i))
859 (j1 (+ 1 j)))
860 (vector-set! rv i1 j1)
861 (lp1 i1 j1 (+ k 1))))
862
863 (else (lp2 (vector-ref rv j)))))))))
864 rv))))
865
866
867 ;;; We've matched I chars from PAT. C is the next char from the search string.
868 ;;; Return the new I after handling C.
869 ;;;
870 ;;; The pattern is (VECTOR-LENGTH RV) chars long, beginning at index PAT-START
871 ;;; in PAT (PAT-START is usually 0). The I chars of the pattern we've matched
872 ;;; are
873 ;;; PAT[PAT-START .. PAT-START + I].
874 ;;;
875 ;;; It's *not* an oversight that there is no friendly error checking or
876 ;;; defaulting of arguments. This is a low-level, inner-loop procedure
877 ;;; that we want integrated/inlined into the point of call.
878
879 (define (kmp-step pat rv c i c= p-start)
880 (let lp ((i i))
881 (if (c= c (string-ref pat (+ i p-start))) ; Match =>
882 (+ i 1) ; Done.
883 (let ((i (vector-ref rv i))) ; Back up in PAT.
884 (if (= i -1) 0 ; Can't back up further.
885 (lp i)))))) ; Keep trying for match.
886
887 ;;; Zip through S[start,end), looking for a match of PAT. Assume we've
888 ;;; already matched the first I chars of PAT when we commence at S[start].
889 ;;; - <0: If we find a match *ending* at index J, return -J.
890 ;;; - >=0: If we get to the end of the S[start,end) span without finding
891 ;;; a complete match, return the number of chars from PAT we'd matched
892 ;;; when we ran off the end.
893 ;;;
894 ;;; This is useful for searching *across* buffers -- that is, when your
895 ;;; input comes in chunks of text. We hand-integrate the KMP-STEP loop
896 ;;; for speed.
897
898 (define (string-kmp-partial-search pat rv s i . c=+p-start+s-start+s-end)
899 ; (check-arg vector? rv string-kmp-partial-search)
900 (let-optionals* c=+p-start+s-start+s-end
901 ((c= char=?) ; (procedure? c=))
902 (p-start 0) rest) ; (and (integer? p-start) (exact? p-start) (<= 0 p-start)))
903 (receive (rest2 s-start s-end) (string-parse-start+end string-kmp-partial-search s rest)
904 ;; Enough prelude. Here's the actual code.
905 (let ((patlen (vector-length rv)))
906 (let lp ((si s-start) ; An index into S.
907 (vi i)) ; An index into RV.
908 (cond ((= vi patlen) (- si)) ; Win.
909 ((= si s-end) vi) ; Ran off the end.
910 (else ; Match s[si] & loop.
911 (let ((c (string-ref s si)))
912 (lp (+ si 1)
913 (let lp2 ((vi vi)) ; This is just KMP-STEP.
914 (if (c= c (string-ref pat (+ vi p-start)))
915 (+ vi 1)
916 (let ((vi (vector-ref rv vi)))
917 (if (= vi -1) 0
918 (lp2 vi))))))))))))) )
919
920
921 ;;; Misc
922 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
923 ;;; (string-null? s)
924 ;;; (reverse-list->string clist)
925 ;;; (string->list s [start end])
926
927 (define (string-null? s) (zero? (string-length s)))
928
929 (define (string-reverse s . maybe-start+end)
930 (let-string-start+end (start end) string-reverse s maybe-start+end
931 (let* ((len (- end start))
932 (ans (make-string len)))
933 (do ((i start (+ i 1))
934 (j (- len 1) (- j 1)))
935 ((< j 0))
936 (string-set! ans j (string-ref s i)))
937 ans)))
938
939 (define (reverse-list->string clist)
940 (let* ((len (length clist))
941 (s (make-string len)))
942 (do ((i (- len 1) (- i 1)) (clist clist (cdr clist)))
943 ((not (pair? clist)))
944 (string-set! s i (car clist)))
945 s))
946
947
948 ;;; Defined by R5RS, so commented out here.
949 ;(define (list->string lis) (string-unfold null? car cdr lis))
950
951
952 ;;; string-concatenate string-list -> string
953 ;;; string-concatenate/shared string-list -> string
954 ; Alas, Scheme 48's APPLY blows up if you have many, many arguments.
955 ;(define (string-concatenate strings) (apply string-append strings))
956
957 ;;; Here it is written out. I avoid using REDUCE to add up string lengths
958 ;;; to avoid non-R5RS dependencies.
959 (define (string-concatenate strings)
960 (let* ((total (do ((strings strings (cdr strings))
961 (i 0 (+ i (string-length (car strings)))))
962 ((not (pair? strings)) i)))
963 (ans (make-string total)))
964 (let lp ((i 0) (strings strings))
965 (if (pair? strings)
966 (let* ((s (car strings))
967 (slen (string-length s)))
968 (%string-copy! ans i s 0 slen)
969 (lp (+ i slen) (cdr strings)))))
970 ans))
971
972
973 ;;; Defined by R5RS, so commented out here.
974 ;(define (string-append . strings) (string-concatenate strings))
975
976 ;;; string-concatenate-reverse string-list [final-string end] -> string
977 ;;; string-concatenate-reverse/shared string-list [final-string end] -> string
978 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
979 ;;; Return
980 ;;; (string-concatenate
981 ;;; (reverse
982 ;;; (cons (substring final-string 0 end) string-list)))
983
984 (define (string-concatenate-reverse string-list . maybe-final+end)
985 (let-optionals* maybe-final+end ((final "" (string? final))
986 (end (string-length final)
987 (and (integer? end)
988 (exact? end)
989 (<= 0 end (string-length final)))))
990 (let ((len (let lp ((sum 0) (lis string-list))
991 (if (pair? lis)
992 (lp (+ sum (string-length (car lis))) (cdr lis))
993 sum))))
994
995 (%finish-string-concatenate-reverse len string-list final end))))
996
997 (define (%finish-string-concatenate-reverse len string-list final end)
998 (let ((ans (make-string (+ end len))))
999 (%string-copy! ans len final 0 end)
1000 (let lp ((i len) (lis string-list))
1001 (if (pair? lis)
1002 (let* ((s (car lis))
1003 (lis (cdr lis))
1004 (slen (string-length s))
1005 (i (- i slen)))
1006 (%string-copy! ans i s 0 slen)
1007 (lp i lis))))
1008 ans))
1009
1010
1011
1012
1013 ;;; string-replace s1 s2 start1 end1 [start2 end2] -> string
1014 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1015 ;;; Replace S1[START1,END1) with S2[START2,END2).
1016
1017 (define (string-replace s1 s2 start1 end1 . maybe-start+end)
1018 (check-substring-spec string-replace s1 start1 end1)
1019 (let-string-start+end (start2 end2) string-replace s2 maybe-start+end
1020 (let* ((slen1 (string-length s1))
1021 (sublen2 (- end2 start2))
1022 (alen (+ (- slen1 (- end1 start1)) sublen2))
1023 (ans (make-string alen)))
1024 (%string-copy! ans 0 s1 0 start1)
1025 (%string-copy! ans start1 s2 start2 end2)
1026 (%string-copy! ans (+ start1 sublen2) s1 end1 slen1)
1027 ans)))
1028
1029
1030 ;;; string-split s delimiter [grammar limit start end] -> list
1031 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1032 ;;; Returns a list of the words contained in the substring of string from
1033 ;;; start (inclusive) to end (exclusive). Delimiter specifies a string
1034 ;;; whose characters are to be used as the word separator. The returned
1035 ;;; list will then have one more item than the number of non-overlapping
1036 ;;; occurrences of the delimiter in the string. If delimiter is an
1037 ;;; empty string, then the returned list contains a list of strings,
1038 ;;; each of which contains a single character. Grammar is a symbol with
1039 ;;; the same meaning as in the string-join procedure. If it is infix,
1040 ;;; which is the default, processing is done as described above, except
1041 ;;; that an empty s produces the empty list; if it is strict-infix,
1042 ;;; an empty s signals an error. The values prefix and suffix cause a
1043 ;;; leading/trailing empty string in the result to be suppressed.
1044 ;;;
1045 ;;; If limit is a non-negative exact integer, at most that many splits
1046 ;;; occur, and the remainder of string is returned as the final element
1047 ;;; of the list (thus, the result will have at most limit+1 elements). If
1048 ;;; limit is not specified or is #f, then as many splits as possible
1049 ;;; are made. It is an error if limit is any other value.
1050 ;;;
1051 ;;; Thanks to Shiro Kawai for the following code.
1052
1053 (define (string-split s delimiter . args)
1054 ;; The argument checking part might be refactored with other srfi-130
1055 ;; routines.
1056 (if (not (string? s)) (error "string expected" s))
1057 (if (not (string? delimiter)) (error "string expected" delimiter))
1058 (let ((slen (string-length s)))
1059 (receive (grammar limit no-limit start end)
1060 (if (pair? args)
1061 (if (pair? (cdr args))
1062 (if (pair? (cddr args))
1063 (if (pair? (cdddr args))
1064 (values (car args) (cadr args) #f (caddr args) (cadddr args))
1065 (values (car args) (cadr args) #f (caddr args) slen))
1066 (values (car args) (cadr args) #f 0 slen))
1067 (values (car args) #f #t 0 slen))
1068 (values 'infix #f #t 0 slen))
1069 (if (not (memq grammar '(infix strict-infix prefix suffix)))
1070 (error "grammar must be one of (infix strict-infix prefix suffix)" grammar))
1071 (if (not limit) (set! no-limit #t))
1072 (if (not (or no-limit
1073 (and (integer? limit) (exact? limit) (>= limit 0))))
1074 (error "limit must be exact nonnegative integer or #f" limit))
1075 (if (not (and (integer? start) (exact? start)))
1076 (error "start argument must be exact integer" start))
1077 (if (not (<= 0 start slen))
1078 (error "start argument out of range" start))
1079 (if (not (<= 0 end slen))
1080 (error "end argument out of range" end))
1081 (if (not (<= start end))
1082 (error "start argument is greater than end argument" (list start end)))
1083
1084 (cond ((= start end)
1085 (if (eq? grammar 'strict-infix)
1086 (error "empty string cannot be spilt with strict-infix grammar")
1087 '()))
1088 ((string-null? delimiter)
1089 (%string-split-chars s start end limit))
1090 (else (%string-split s start end delimiter grammar limit))))))
1091
1092 (define (%string-split-chars s start end limit)
1093 (if (not limit)
1094 (map string (string->list s start end))
1095 (let loop ((r '()) (c start) (n 0))
1096 (cond ((= c end) (reverse r))
1097 ((>= n limit) (reverse (cons (substring s c end) r)))
1098 (else (loop (cons (string (string-ref s c)) r)
1099 (+ c 1)
1100 (+ n 1)))))))
1101
1102 (define (%string-split s start end delimiter grammar limit)
1103 (let ((dlen (string-length delimiter)))
1104 (define (finish r c)
1105 (let ((rest (substring s c end)))
1106 (if (and (eq? grammar 'suffix) (string-null? rest))
1107 (reverse r)
1108 (reverse (cons rest r)))))
1109 (define (scan r c n)
1110 (if (and limit (>= n limit))
1111 (finish r c)
1112 (let ((i (string-contains s delimiter c end)))
1113 (if i
1114 (let ((fragment (substring s c i)))
1115 (if (and (= n 0) (eq? grammar 'prefix) (string-null? fragment))
1116 (scan r (+ i dlen) (+ n 1))
1117 (scan (cons fragment r)
1118 (+ i dlen)
1119 (+ n 1))))
1120 (finish r c)))))
1121 (scan '() start 0)))
1122
1123
1124
1125 ;;; string-replicate s from [to start end] -> string
1126 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1127 ;;; S is a string; START and END are optional arguments that demarcate
1128 ;;; a substring of S, defaulting to 0 and the length of S (e.g., the whole
1129 ;;; string). Replicate this substring up and down index space, in both the
1130 ;; positive and negative directions. For example, if S = "abcdefg", START=3,
1131 ;;; and END=6, then we have the conceptual bidirectionally-infinite string
1132 ;;; ... d e f d e f d e f d e f d e f d e f d e f ...
1133 ;;; ... -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 ...
1134 ;;; XSUBSTRING returns the substring of this string beginning at index FROM,
1135 ;;; and ending at TO (which defaults to FROM+(END-START)).
1136 ;;;
1137 ;;; You can use XSUBSTRING in many ways:
1138 ;;; - To rotate a string left: (string-replicate "abcdef" 2) => "cdefab"
1139 ;;; - To rotate a string right: (string-replicate "abcdef" -2) => "efabcd"
1140 ;;; - To replicate a string: (string-replicate "abc" 0 7) => "abcabca"
1141 ;;;
1142 ;;; Note that
1143 ;;; - The FROM/TO indices give a half-open range -- the characters from
1144 ;;; index FROM up to, but not including index TO.
1145 ;;; - The FROM/TO indices are not in terms of the index space for string S.
1146 ;;; They are in terms of the replicated index space of the substring
1147 ;;; defined by S, START, and END.
1148 ;;;
1149 ;;; It is an error if START=END -- although this is allowed by special
1150 ;;; dispensation when FROM=TO.
1151
1152 (define (string-replicate s from . maybe-to+start+end)
1153 (check-arg (lambda (val) (and (integer? val) (exact? val)))
1154 from string-replicate)
1155 (receive (to start end)
1156 (if (pair? maybe-to+start+end)
1157 (let-string-start+end (start end) string-replicate s (cdr maybe-to+start+end)
1158 (let ((to (car maybe-to+start+end)))
1159 (check-arg (lambda (val) (and (integer? val)
1160 (exact? val)
1161 (<= from val)))
1162 to string-replicate)
1163 (values to start end)))
1164 (let ((slen (string-length (check-arg string? s string-replicate))))
1165 (values (+ from slen) 0 slen)))
1166 (let ((slen (- end start))
1167 (anslen (- to from)))
1168 (cond ((zero? anslen) "")
1169 ((zero? slen) (error "Cannot replicate empty (sub)string"
1170 string-replicate s from to start end))
1171
1172 ((= 1 slen) ; Fast path for 1-char replication.
1173 (make-string anslen (string-ref s start)))
1174
1175 ;; Selected text falls entirely within one span.
1176 ((= (floor (/ from slen)) (floor (/ to slen)))
1177 (substring s (+ start (modulo from slen))
1178 (+ start (modulo to slen))))
1179
1180 ;; Selected text requires multiple spans.
1181 (else (let ((ans (make-string anslen)))
1182 (%multispan-repcopy! ans 0 s from to start end)
1183 ans))))))
1184
1185
1186 ;;; This is the core copying loop for XSUBSTRING and STRING-XCOPY!
1187 ;;; Internal -- not exported, no careful arg checking.
1188 (define (%multispan-repcopy! target tstart s sfrom sto start end)
1189 (let* ((slen (- end start))
1190 (i0 (+ start (modulo sfrom slen)))
1191 (total-chars (- sto sfrom)))
1192
1193 ;; Copy the partial span ! the beginning
1194 (%string-copy! target tstart s i0 end)
1195
1196 (let* ((ncopied (- end i0)) ; We've copied this many.
1197 (nleft (- total-chars ncopied)) ; # chars left to copy.
1198 (nspans (quotient nleft slen))) ; # whole spans to copy
1199
1200 ;; Copy the whole spans in the middle.
1201 (do ((i (+ tstart ncopied) (+ i slen)) ; Current target index.
1202 (nspans nspans (- nspans 1))) ; # spans to copy
1203 ((zero? nspans)
1204 ;; Copy the partial-span ! the end & we're done.
1205 (%string-copy! target i s start (+ start (- total-chars (- i tstart)))))
1206
1207 (%string-copy! target i s start end))))); Copy a whole span.
1208
1209
1210
1211 ;;; (string-join string-list [delimiter grammar]) => string
1212 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1213 ;;; Paste strings together using the delimiter string.
1214 ;;;
1215 ;;; (string-join '("foo" "bar" "baz") ":") => "foo:bar:baz"
1216 ;;;
1217 ;;; DELIMITER defaults to a single space " "
1218 ;;; GRAMMAR is one of the symbols {prefix, infix, strict-infix, suffix}
1219 ;;; and defaults to 'infix.
1220 ;;;
1221 ;;; I could rewrite this more efficiently -- precompute the length of the
1222 ;;; answer string, then allocate & fill it in iteratively. Using
1223 ;;; STRING-CONCATENATE is less efficient.
1224
1225 (define (string-join strings . delim+grammar)
1226 (let-optionals* delim+grammar ((delim " " (string? delim))
1227 (grammar 'infix))
1228 (let ((buildit (lambda (lis final)
1229 (let recur ((lis lis))
1230 (if (pair? lis)
1231 (cons delim (cons (car lis) (recur (cdr lis))))
1232 final)))))
1233
1234 (cond ((pair? strings)
1235 (string-concatenate
1236 (case grammar
1237
1238 ((infix strict-infix)
1239 (cons (car strings) (buildit (cdr strings) '())))
1240
1241 ((prefix) (buildit strings '()))
1242
1243 ((suffix)
1244 (cons (car strings) (buildit (cdr strings) (list delim))))
1245
1246 (else (error "Illegal join grammar"
1247 grammar string-join)))))
1248
1249 ((not (null? strings))
1250 (error "STRINGS parameter not list." strings string-join))
1251
1252 ;; STRINGS is ()
1253
1254 ((eq? grammar 'strict-infix)
1255 (error "Empty list cannot be joined with STRICT-INFIX grammar."
1256 string-join))
1257
1258 (else ""))))) ; Special-cased for infix grammar.
1259
1260 (define (string-segment str k)
1261 (if (< k 1) (error "minimum segment size is 1" k))
1262 (let ((len (string-length str)))
1263 (let loop ((start 0)
1264 (result '()))
1265 (if (= start len)
1266 (reverse result)
1267 (let ((end (min (+ start k) len)))
1268 (loop end (cons (%substring str start end) result)))))))
1269
1270
1271 ;;; Porting & performance-tuning notes
1272 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1273 ;;; See the section at the beginning of this file on external dependencies.
1274 ;;;
1275 ;;; The biggest issue with respect to porting is the LET-OPTIONALS* macro.
1276 ;;; There are many, many optional arguments in this library; the complexity
1277 ;;; of parsing, defaulting & type-testing these parameters is handled with the
1278 ;;; aid of this macro. There are about 15 uses of LET-OPTIONALS*. You can
1279 ;;; rewrite the uses, port the hairy macro definition (which is implemented
1280 ;;; using a Clinger-Rees low-level explicit-renaming macro system), or port
1281 ;;; the simple, high-level definition, which is less efficient.
1282 ;;;
1283 ;;; There is a fair amount of argument checking. This is, strictly speaking,
1284 ;;; unnecessary -- the actual body of the procedures will blow up if, say, a
1285 ;;; START/END index is improper. However, the error message will not be as
1286 ;;; good as if the error were caught at the "higher level." Also, a very, very
1287 ;;; smart Scheme compiler may be able to exploit having the type checks done
1288 ;;; early, so that the actual body of the procedures can assume proper values.
1289 ;;; This isn't likely; this kind of compiler technology isn't common any
1290 ;;; longer.
1291 ;;;
1292 ;;; The overhead of optional-argument parsing is irritating. The optional
1293 ;;; arguments must be consed into a rest list on entry, and then parsed out.
1294 ;;; Function call should be a matter of a few register moves and a jump; it
1295 ;;; should not involve heap allocation! Your Scheme system may have a superior
1296 ;;; non-R5RS optional-argument system that can eliminate this overhead. If so,
1297 ;;; then this is a prime candidate for optimising these procedures,
1298 ;;; *especially* the many optional START/END index parameters.
1299 ;;;
1300 ;;; Note that optional arguments are also a barrier to procedure integration.
1301 ;;; If your Scheme system permits you to specify alternate entry points
1302 ;;; for a call when the number of optional arguments is known in a manner
1303 ;;; that enables inlining/integration, this can provide performance
1304 ;;; improvements.
1305 ;;;
1306 ;;; There is enough *explicit* error checking that *all* string-index
1307 ;;; operations should *never* produce a bounds error. Period. Feel like
1308 ;;; living dangerously? *Big* performance win to be had by replacing
1309 ;;; STRING-REF's and STRING-SET!'s with unsafe equivalents in the loops.
1310 ;;; Similarly, fixnum-specific operators can speed up the arithmetic done on
1311 ;;; the index values in the inner loops. The only arguments that are not
1312 ;;; completely error checked are
1313 ;;; - string lists (complete checking requires time proportional to the
1314 ;;; length of the list)
1315 ;;; - procedure arguments, such as char->char maps & predicates.
1316 ;;; There is no way to check the range & domain of procedures in Scheme.
1317 ;;; Procedures that take these parameters cannot fully check their
1318 ;;; arguments. But all other types to all other procedures are fully
1319 ;;; checked.
1320 ;;;
1321 ;;; This does open up the alternate possibility of simply *removing* these
1322 ;;; checks, and letting the safe primitives raise the errors. On a dumb
1323 ;;; Scheme system, this would provide speed (by eliminating the redundant
1324 ;;; error checks) at the cost of error-message clarity.
1325 ;;;
1326 ;;; See the comments preceding the hash function code for notes on tuning
1327 ;;; the default bound so that the code never overflows your implementation's
1328 ;;; fixnum size into bignum calculation.
1329 ;;;
1330 ;;; In an interpreted Scheme, some of these procedures, or the internal
1331 ;;; routines with % prefixes, are excellent candidates for being rewritten
1332 ;;; in C. Consider STRING-HASH, %STRING-COMPARE, the
1333 ;;; %STRING-{SUF,PRE}FIX-LENGTH routines, STRING-COPY!, STRING-INDEX &
1334 ;;; STRING-SKIP (char case), SUBSTRING and SUBSTRING,
1335 ;;; %KMP-SEARCH, and %MULTISPAN-REPCOPY!.
1336 ;;;
1337 ;;; It would also be nice to have the ability to mark some of these
1338 ;;; routines as candidates for inlining/integration.
1339 ;;;
1340 ;;; All the %-prefixed routines in this source code are written
1341 ;;; to be called internally to this library. They do *not* perform
1342 ;;; friendly error checks on the inputs; they assume everything is
1343 ;;; proper. They also do not take optional arguments. These two properties
1344 ;;; save calling overhead and enable procedure integration -- but they
1345 ;;; are not appropriate for exported routines.
1346
1347
1348 ;;; Copyright details
1349 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1350 ;;; The prefix/suffix and comparison routines in this code had (extremely
1351 ;;; distant) origins in MIT Scheme's string lib, and was substantially
1352 ;;; reworked by Olin Shivers ([email protected]) 9/98. As such, it is
1353 ;;; covered by MIT Scheme's open source copyright. See below for details.
1354 ;;;
1355 ;;; The KMP string-search code was influenced by implementations written
1356 ;;; by Stephen Bevan, Brian Dehneyer and Will Fitzgerald. However, this
1357 ;;; version was written from scratch by myself.
1358 ;;;
1359 ;;; The remainder of this code was written from scratch by myself for scsh.
1360 ;;; The scsh copyright is a BSD-style open source copyright. See below for
1361 ;;; details.
1362 ;;; -Olin Shivers
1363
1364 ;;; MIT Scheme copyright terms
1365 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1366 ;;; This material was developed by the Scheme project at the Massachusetts
1367 ;;; Institute of Technology, Department of Electrical Engineering and
1368 ;;; Computer Science. Permission to copy and modify this software, to
1369 ;;; redistribute either the original software or a modified version, and
1370 ;;; to use this software for any purpose is granted, subject to the
1371 ;;; following restrictions and understandings.
1372 ;;;
1373 ;;; 1. Any copy made of this software must include this copyright notice
1374 ;;; in full.
1375 ;;;
1376 ;;; 2. Users of this software agree to make their best efforts (a) to
1377 ;;; return to the MIT Scheme project any improvements or extensions that
1378 ;;; they make, so that these may be included in future releases; and (b)
1379 ;;; to inform MIT of noteworthy uses of this software.
1380 ;;;
1381 ;;; 3. All materials developed as a consequence of the use of this
1382 ;;; software shall duly acknowledge such use, in accordance with the usual
1383 ;;; standards of acknowledging credit in academic research.
1384 ;;;
1385 ;;; 4. MIT has made no warrantee or representation that the operation of
1386 ;;; this software will be error-free, and MIT is under no obligation to
1387 ;;; provide any services, by way of maintenance, update, or otherwise.
1388 ;;;
1389 ;;; 5. In conjunction with products arising from the use of this material,
1390 ;;; there shall be no use of the name of the Massachusetts Institute of
1391 ;;; Technology nor of any adaptation thereof in any advertising,
1392 ;;; promotional, or sales literature without prior written consent from
1393 ;;; MIT in each case.
1394
1395 ;;; Scsh copyright terms
1396 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1397 ;;; All rights reserved.
1398 ;;;
1399 ;;; Redistribution and use in source and binary forms, with or without
1400 ;;; modification, are permitted provided that the following conditions
1401 ;;; are met:
1402 ;;; 1. Redistributions of source code must retain the above copyright
1403 ;;; notice, this list of conditions and the following disclaimer.
1404 ;;; 2. Redistributions in binary form must reproduce the above copyright
1405 ;;; notice, this list of conditions and the following disclaimer in the
1406 ;;; documentation and/or other materials provided with the distribution.
1407 ;;; 3. The name of the authors may not be used to endorse or promote products
1408 ;;; derived from this software without specific prior written permission.
1409 ;;;
1410 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
1411 ;;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1412 ;;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1413 ;;; IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
1414 ;;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
1415 ;;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1416 ;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1417 ;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1418 ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
1419 ;;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.