r8005: Automated commit for kmrcl debian-version-1.58-1
[kmrcl.git] / strings.lisp
1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          strings.lisp
6 ;;;; Purpose:       Strings utility functions for KMRCL package
7 ;;;; Programmer:    Kevin M. Rosenberg
8 ;;;; Date Started:  Apr 2000
9 ;;;;
10 ;;;; $Id$
11 ;;;;
12 ;;;; This file, part of KMRCL, is Copyright (c) 2002 by Kevin M. Rosenberg
13 ;;;;
14 ;;;; KMRCL users are granted the rights to distribute and use this software
15 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
16 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
17 ;;;; *************************************************************************
18
19
20 (in-package #:kmrcl)
21
22 ;;; Strings
23
24 (defmacro string-append (outputstr &rest args)
25   `(setq ,outputstr (concatenate 'string ,outputstr ,@args)))
26
27 (defun list-to-string (lst)
28   "Converts a list to a string, doesn't include any delimiters between elements"
29   (format nil "~{~A~}" lst))
30
31 (defun count-string-words (str)
32   (declare (simple-string str)
33            (optimize (speed 3) (safety 0) (space 0)))
34   (let ((n-words 0)
35         (in-word nil))
36     (declare (fixnum n-words))
37     (do* ((len (length str))
38           (i 0 (1+ i)))
39         ((= i len) n-words)
40       (declare (fixnum i))
41       (if (alphanumericp (schar str i))
42           (unless in-word
43             (incf n-words)
44             (setq in-word t))
45         (setq in-word nil)))))
46
47 ;; From Larry Hunter with modifications
48 (defun position-char (char string start max)
49   (declare (optimize (speed 3) (safety 0) (space 0))
50            (fixnum start max) (simple-string string))
51   (do* ((i start (1+ i)))
52        ((= i max) nil)
53     (declare (fixnum i))
54     (when (char= char (schar string i)) (return i))))
55
56 (defun position-not-char (char string start max)
57   (declare (optimize (speed 3) (safety 0) (space 0))
58            (fixnum start max) (simple-string string))
59   (do* ((i start (1+ i)))
60        ((= i max) nil)
61     (declare (fixnum i))
62     (when (char/= char (schar string i)) (return i))))
63
64 (defun delimited-string-to-list (string &optional (separator #\space) 
65                                                   skip-terminal)
66   "split a string with delimiter"
67   (declare (optimize (speed 3) (safety 0) (space 0) (compilation-speed 0))
68            (type string string)
69            (type character separator))
70   (do* ((len (length string))
71         (output '())
72         (pos 0)
73         (end (position-char separator string pos len)
74              (position-char separator string pos len)))
75        ((null end)
76         (if (< pos len)
77             (push (subseq string pos) output)
78             (when (or (not skip-terminal) (zerop len))
79               (push "" output)))
80         (nreverse output))
81     (declare (type fixnum pos len)
82              (type (or null fixnum) end))
83     (push (subseq string pos end) output)
84     (setq pos (1+ end))))
85
86
87 (defun list-to-delimited-string (list &optional (separator " "))
88   (format nil (concatenate 'string "~{~A~^" (string separator) "~}") list))
89
90 (defun string-invert (str)
91   "Invert case of a string"
92   (declare (optimize (speed 3) (compilation-speed 0) (debug 0) (safety 0))
93            (simple-string str))
94   (let ((up nil) (down nil))
95     (block skip
96       (loop for char of-type character across str do
97             (cond ((upper-case-p char)
98                    (if down (return-from skip str) (setf up t)))
99                   ((lower-case-p char)
100                    (if up   (return-from skip str) (setf down t)))))
101       (if up (string-downcase str) (string-upcase str)))))
102
103 (defun add-sql-quotes (s)
104   (substitute-string-for-char s #\' "''"))
105
106 (defun escape-backslashes (s)
107   (substitute-string-for-char s #\\ "\\\\"))
108
109 (defun substitute-string-for-char (procstr match-char subst-str) 
110   "Substitutes a string for a single matching character of a string"
111   (substitute-chars-strings procstr (list (cons match-char subst-str))))
112
113 (defun string-substitute (string substring replacement-string)
114   "String substitute by Larry Hunter. Obtained from Google"
115   (let ((substring-length (length substring))
116         (last-end 0)
117         (new-string ""))
118     (do ((next-start
119           (search substring string)
120           (search substring string :start2 last-end)))
121         ((null next-start)
122          (concatenate 'string new-string (subseq string last-end)))
123       (setq new-string
124         (concatenate 'string
125           new-string
126           (subseq string last-end next-start)
127           replacement-string))
128       (setq last-end (+ next-start substring-length)))))
129
130 (defun string-trim-last-character (s)
131   "Return the string less the last character"
132   (let ((len (length s)))
133     (if (plusp len)
134         (subseq s 0 (1- len))
135         s)))
136
137 (defun nstring-trim-last-character (s)
138   "Return the string less the last character"
139   (let ((len (length s)))
140     (if (plusp len)
141         (nsubseq s 0 (1- len))
142         s)))
143
144 (defun string-hash (str &optional (bitmask 65535))
145   (let ((hash 0))
146     (declare (fixnum hash)
147              (simple-string str))
148     (dotimes (i (length str))
149       (declare (fixnum i))
150       (setq hash (+ hash (char-code (char str i)))))
151     (logand hash bitmask)))
152
153 (defun is-string-empty (str)
154   (zerop (length str)))
155
156 (defvar *whitespace-chars* '(#\space #\tab #\return #\linefeed))
157
158 (defun is-char-whitespace (c) 
159   (declare (character c) (optimize (speed 3) (safety 0)))
160   (or (char= c #\Space) (char= c #\Tab) (char= c #\Return)
161       (char= c #\Linefeed)))
162
163 (defun is-string-whitespace (str)
164   "Return t if string is all whitespace"
165   (every #'is-char-whitespace str))
166
167 (defun string-right-trim-whitespace (str)
168   (string-right-trim *whitespace-chars* str))
169
170 (defun string-left-trim-whitespace (str)
171   (string-left-trim *whitespace-chars* str))
172
173 (defun string-trim-whitespace (str)
174   (string-trim *whitespace-chars* str))
175
176 (defun replaced-string-length (str repl-alist)
177   (declare (simple-string str)
178            (optimize (speed 3) (safety 0) (space 0)))
179     (do* ((i 0 (1+ i))
180           (orig-len (length str))
181           (new-len orig-len))
182          ((= i orig-len) new-len)
183       (declare (fixnum i orig-len new-len))
184       (let* ((c (char str i))
185              (match (assoc c repl-alist :test #'char=)))
186         (declare (character c))
187         (when match
188           (incf new-len (1- (length
189                              (the simple-string (cdr match)))))))))
190
191 (defun substitute-chars-strings (str repl-alist)
192   "Replace all instances of a chars with a string. repl-alist is an assoc
193 list of characters and replacement strings."
194   (declare (simple-string str)
195            (optimize (speed 3) (safety 0) (space 0)))
196   (do* ((orig-len (length str))
197         (new-string (make-string (replaced-string-length str repl-alist)))
198         (spos 0 (1+ spos))
199         (dpos 0))
200       ((>= spos orig-len)
201        new-string)
202     (declare (fixnum spos dpos) (simple-string new-string))
203     (let* ((c (char str spos))
204            (match (assoc c repl-alist :test #'char=)))
205       (declare (character c))
206       (if match
207           (let* ((subst (cdr match))
208                  (len (length subst)))
209             (declare (fixnum len)
210                      (simple-string subst))
211             (dotimes (j len)
212               (declare (fixnum j))
213               (setf (char new-string dpos) (char subst j))
214               (incf dpos)))
215         (progn
216           (setf (char new-string dpos) c)
217           (incf dpos))))))
218
219 (defun escape-xml-string (string)
220   "Escape invalid XML characters"
221   (substitute-chars-strings string '((#\& . "&amp;") (#\< . "&lt;"))))
222
223 (defun make-usb8-array (len)
224   (make-array len :element-type '(unsigned-byte 8)))
225
226 (defun usb8-array-to-string (vec)
227   (declare (type (simple-array (unsigned-byte 8) (*)) vec))
228   (let* ((len (length vec))
229          (str (make-string len)))
230     (declare (fixnum len)
231              (simple-string str)
232              (optimize (speed 3)))
233     (do ((i 0 (1+ i)))
234         ((= i len) str)
235       (declare (fixnum i))
236       (setf (schar str i) (code-char (aref vec i))))))
237
238 (defun string-to-usb8-array (str)
239   (declare (simple-string str))
240   (let* ((len (length str))
241          (vec (make-usb8-array len)))
242     (declare (fixnum len)
243              (type (simple-array (unsigned-byte 8) (*)) vec)
244              (optimize (speed 3)))
245     (do ((i 0 (1+ i)))
246         ((= i len) vec)
247       (declare (fixnum i))
248       (setf (aref vec i) (char-code (schar str i))))))
249
250 (defun concat-separated-strings (separator &rest lists)
251   (format nil (concatenate 'string "~{~A~^" (string separator) "~}")
252           (append-sublists lists)))
253
254 (defun only-null-list-elements-p (lst)
255   (or (null lst) (every #'null lst)))
256
257 (defun print-separated-strings (strm separator &rest lists)
258   (declare (optimize (speed 3) (safety 0) (space 0) (debug 0)
259                      (compilation-speed 0)))
260   (do* ((rest-lists lists (cdr rest-lists))
261         (list (car rest-lists) (car rest-lists))
262         (last-list (only-null-list-elements-p (cdr rest-lists))
263                    (only-null-list-elements-p (cdr rest-lists))))
264        ((null rest-lists) strm)
265     (do* ((lst list (cdr lst))
266           (elem (car lst) (car lst))
267           (last-elem (null (cdr lst)) (null (cdr lst))))
268          ((null lst))
269       (write-string elem strm)
270       (unless (and last-elem last-list)
271         (write-string separator strm)))))
272
273 (defun prefixed-fixnum-string (num pchar len)
274   "Outputs a string of LEN digit with an optional initial character PCHAR.
275 Leading zeros are present."
276   (declare (optimize (speed 3) (safety 0) (space 0))
277            (type fixnum num len))
278   (when pchar
279     (incf len))
280   (do* ((zero-code (char-code #\0))
281         (result (make-string len :initial-element #\0))
282         (minus? (minusp num))
283         (val (if minus? (- num) num)
284              (nth-value 0 (floor val 10)))
285         (pos (1- len) (1- pos))
286         (mod (mod val 10) (mod val 10)))
287       ((or (zerop val) (minusp pos))
288        (when pchar
289          (setf (schar result 0) pchar))
290        (when minus? (setf (schar result (if pchar 1 0)) #\-))
291        result)
292     (declare (fixnum val mod zero-code pos) (simple-string result))
293     (setf (schar result pos) (code-char (+ zero-code mod)))))
294
295 (defun integer-string (num len)
296   "Outputs a string of LEN digit with an optional initial character PCHAR.
297 Leading zeros are present."
298   (declare (optimize (speed 3) (safety 0) (space 0))
299            (type fixnum len)
300            (type integer num))
301   (do* ((zero-code (char-code #\0))
302         (result (make-string len :initial-element #\0))
303         (minus? (minusp num))
304         (val (if minus? (- 0 num) num)
305              (nth-value 0 (floor val 10)))
306         (pos (1- len) (1- pos))
307         (mod (mod val 10) (mod val 10)))
308       ((or (zerop val) (minusp pos))
309        (when minus? (setf (schar result 0) #\-))
310        result)
311     (declare (fixnum mod zero-code pos) (simple-string result) (integer val))
312     (setf (schar result pos) (code-char (+ zero-code mod)))))
313
314 (defun fast-string-search (substr str substr-length startpos endpos)
315   "Optimized search for a substring in a simple-string"
316   (declare (simple-string substr str)
317            (fixnum substr-length startpos endpos)
318            (optimize (speed 3) (space 0) (safety 0)))
319   (do* ((pos startpos (1+ pos))
320         (lastpos (- endpos substr-length)))
321        ((> pos lastpos) nil)
322     (declare (fixnum pos lastpos))
323     (do ((i 0 (1+ i)))
324         ((= i substr-length)
325          (return-from fast-string-search pos))
326       (declare (fixnum i))
327       (unless (char= (schar str (+ i pos)) (schar substr i))
328         (return nil)))))
329
330 (defun string-delimited-string-to-list (str substr)
331   "splits a string delimited by substr into a list of strings"
332   (declare (simple-string str substr)
333            (optimize (speed 3) (safety 0) (space 0) (compilation-speed 0)
334                      (debug 0)))
335   (do* ((substr-len (length substr))
336         (strlen (length str))
337         (output '())
338         (pos 0)
339         (end (fast-string-search substr str substr-len pos strlen)
340              (fast-string-search substr str substr-len pos strlen)))
341        ((null end)
342         (when (< pos strlen)
343           (push (subseq str pos) output))
344         (nreverse output))
345     (declare (fixnum strlen substr-len pos)
346              (type (or fixnum null) end))
347     (push (subseq str pos end) output)
348     (setq pos (+ end substr-len))))
349   
350 (defun string-to-list-skip-delimiter (str &optional (delim #\space))
351   "Return a list of strings, delimited by spaces, skipping spaces."
352   (declare (simple-string str)
353            (optimize (speed 0) (space 0) (safety 0)))
354   (do* ((results '())
355         (end (length str))
356         (i (position-not-char delim str 0 end)
357            (position-not-char delim str j end))
358         (j (when i (position-char delim str i end))
359            (when i (position-char delim str i end))))
360        ((or (null i) (null j))
361         (when (and i (< i end))
362           (push (subseq str i end) results))
363         (nreverse results))
364     (declare (fixnum end)
365              (type (or fixnum null) i j))
366     (push (subseq str i j) results)))
367
368 (defun string-starts-with (start str)
369   (and (>= (length str) (length start))
370        (string-equal start str :end2 (length start))))
371
372 (defun count-string-char (s c)
373   "Return a count of the number of times a character appears in a string"
374   (declare (simple-string s)
375            (character c)
376            (optimize (speed 3) (safety 0)))
377   (do ((len (length s))
378        (i 0 (1+ i))
379        (count 0))
380       ((= i len) count)
381     (declare (fixnum i len count))
382     (when (char= (schar s i) c)
383       (incf count))))
384
385 (defun count-string-char-if (pred s)
386   "Return a count of the number of times a predicate is true
387 for characters in a string"
388   (declare (simple-string s)
389            (type (or function symbol) pred)
390            (optimize (speed 3) (safety 0) (space 0)))
391   (do ((len (length s))
392        (i 0 (1+ i))
393        (count 0))
394       ((= i len) count)
395     (declare (fixnum i len count))
396     (when (funcall pred (schar s i))
397       (incf count))))
398
399
400 ;;; URL Encoding
401
402 (defun non-alphanumericp (ch)
403   (not (alphanumericp ch)))
404
405 (defvar +hex-chars+ "0123456789ABCDEF")
406 (declaim (type simple-string +hex-chars+))
407
408 (defun hexchar (n)
409   (declare (type (integer 0 15) n))
410   (schar +hex-chars+ n))
411
412 (defconstant +char-code-lower-a+ (char-code #\a))
413 (defconstant +char-code-upper-a+ (char-code #\A))
414 (defconstant +char-code-0+ (char-code #\0))
415 (declaim (type fixnum +char-code-0+ +char-code-upper-a+
416                +char-code-0))
417
418 (defun charhex (ch)
419   "convert hex character to decimal"
420   (let ((code (char-code (char-upcase ch))))
421     (declare (fixnum ch)) 
422     (if (>= code +char-code-upper-a+)
423         (+ 10 (- code +char-code-upper-a+))
424         (- code +char-code-0+))))
425
426 (defun uriencode-string (query)
427   "Escape non-alphanumeric characters for URI fields"
428   (declare (simple-string query)
429            (optimize (speed 3) (safety 0) (space 0)))
430   (do* ((count (count-string-char-if #'non-alphanumericp query))
431         (len (length query))
432         (new-len (+ len (* 2 count)))
433         (str (make-string new-len))
434         (spos 0 (1+ spos))
435         (dpos 0 (1+ dpos)))
436       ((= spos len) str)
437     (declare (fixnum count len new-len spos dpos)
438              (simple-string str))
439     (let ((ch (schar query spos)))
440       (if (non-alphanumericp ch)
441           (let ((c (char-code ch)))
442             (setf (schar str dpos) #\%)
443             (incf dpos)
444             (setf (schar str dpos) (hexchar (logand (ash c -4) 15)))
445             (incf dpos)
446             (setf (schar str dpos) (hexchar (logand c 15))))
447         (setf (schar str dpos) ch)))))
448
449 (defun uridecode-string (query)
450   "Unescape non-alphanumeric characters for URI fields"
451   (declare (simple-string query)
452            (optimize (speed 3) (safety 0) (space 0)))
453   (do* ((count (count-string-char query #\%))
454         (len (length query))
455         (new-len (- len (* 2 count)))
456         (str (make-string new-len))
457         (spos 0 (1+ spos))
458         (dpos 0 (1+ dpos)))
459       ((= spos len) str)
460     (declare (fixnum count len new-len spos dpos)
461              (simple-string str))
462     (let ((ch (schar query spos)))
463       (if (char= #\% ch)
464           (let ((c1 (charhex (schar query (1+ spos))))
465                 (c2 (charhex (schar query (+ spos 2)))))
466             (declare (fixnum c1 c2))
467             (setf (schar str dpos)
468                   (code-char (logior c2 (ash c1 4))))
469             (incf spos 2))
470         (setf (schar str dpos) ch)))))
471
472
473
474 (eval-when (:compile-toplevel :load-toplevel :execute)
475   (defvar +unambigous-charset+
476     "abcdefghjkmnpqrstuvwxyz123456789ABCDEFGHJKLMNPQSRTUVWXYZ")
477   (defconstant +unambigous-length+ (length +unambigous-charset+)))
478
479 (defun random-char (&optional (set :lower-alpha))
480   (ecase set
481     (:lower-alpha
482      (code-char (+ +char-code-lower-a+ (random 26))))
483     (:lower-alphanumeric
484      (let ((n (random 36)))
485        (if (>= n 26)
486            (code-char (+ +char-code-0+ (- n 26)))
487          (code-char (+ +char-code-lower-a+ n)))))
488     (:upper-alpha
489      (code-char (+ +char-code-upper-a+ (random 26))))
490     (:unambigous
491      (schar +unambigous-charset+ (random +unambigous-length+)))
492     (:upper-lower-alpha
493      (let ((n (random 52)))
494        (if (>= n 26)
495            (code-char (+ +char-code-upper-a+ (- n 26)))
496          (code-char (+ +char-code-lower-a+ n)))))))
497      
498
499 (defun random-string (&key (length 10) (set :lower-alpha))
500   "Returns a random lower-case string."
501   (declare (optimize (speed 3)))
502   (let ((s (make-string length)))
503     (declare (simple-string s))
504     (dotimes (i length s)
505       (setf (schar s i) (random-char set)))))
506
507
508 (defun first-char (s)
509   (declare (simple-string s))
510   (when (and (stringp s) (plusp (length s)))
511     (schar s 0)))
512
513 (defun last-char (s)
514   (declare (simple-string s))
515   (when (stringp s)
516     (let ((len (length s)))
517       (when (plusp len))
518       (schar s (1- len)))))
519
520 (defun ensure-string (v)
521   (typecase v
522     (string v)
523     (character (string v))
524     (symbol (symbol-name v))
525     (otherwise (write-to-string v))))
526
527 (defun string-right-trim-one-char (char str)
528   (declare (simple-string str))
529   (let* ((len (length str))
530          (last (1- len)))
531     (declare (fixnum len last))
532     (if (char= char (schar str last))
533         (subseq str 0 last)
534       str)))
535
536
537 (defun string-strip-ending (str endings)
538   (if (stringp endings)
539       (setq endings (list endings)))
540   (let ((len (length str)))
541     (dolist (ending endings str)
542       (when (and (>= len (length ending))
543                  (string-equal ending
544                                (subseq str (- len
545                                               (length ending)))))
546         (return-from string-strip-ending
547           (subseq str 0 (- len (length ending))))))))
548        
549
550 (defun string-maybe-shorten (str maxlen)
551   (let ((len (length str)))
552     (if (<= len maxlen)
553         str
554       (concatenate 'string (subseq str 0 (- maxlen 3)) "..."))))
555
556
557 (defun shrink-vector (str size)
558   #+allegro
559   (excl::.primcall 'sys::shrink-svector str size)
560   #+cmu
561   (lisp::shrink-vector str size)
562   #+lispworks
563   (system::shrink-vector$vector str size)
564   #+sbcl
565   (sb-kernel:shrink-vector str size)
566   #+scl
567   (common-lisp::shrink-vector str size)
568   #-(or allegro cmu lispworks sbcl scl)
569   (setq str (subseq str 0 size))
570   str)
571
572 (defun lex-string (string &key (whitespace '(#\space #\newline)))
573   "Separates a string at whitespace and returns a list of strings"
574   (flet ((is-sep (char) (member char whitespace :test #'char=)))
575     (let ((tokens nil))
576       (do* ((token-start
577              (position-if-not #'is-sep string) 
578              (when token-end
579                (position-if-not #'is-sep string :start (1+ token-end))))
580             (token-end
581              (when token-start
582                (position-if #'is-sep string :start token-start))
583              (when token-start
584                (position-if #'is-sep string :start token-start))))
585            ((null token-start) (nreverse tokens))
586         (push (subseq string token-start token-end) tokens)))))
587
588 (defun split-alphanumeric-string (string)
589   "Separates a string at any non-alphanumeric chararacter"
590   (flet ((is-sep (char) (non-alphanumericp char)))
591     (let ((tokens nil))
592       (do* ((token-start
593              (position-if-not #'is-sep string) 
594              (when token-end
595                (position-if-not #'is-sep string :start (1+ token-end))))
596             (token-end
597              (when token-start
598                (position-if #'is-sep string :start token-start))
599              (when token-start
600                (position-if #'is-sep string :start token-start))))
601            ((null token-start) (nreverse tokens))
602         (push (subseq string token-start token-end) tokens)))))
603
604
605