r5408: *** empty log message ***
[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: strings.lisp,v 1.50 2003/07/21 00:52:56 kevin Exp $
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 string-not-null? (str)
154   (and str (not (zerop (length str)))))
155   
156 (defun whitespace? (c) 
157   (declare (character c))
158   (locally (declare (optimize (speed 3) (safety 0)))
159     (or (char= c #\Space) (char= c #\Tab) (char= c #\Return)
160         (char= c #\Linefeed))))
161
162 (defun not-whitespace? (c)
163   (not (whitespace? c)))
164
165 (defun string-ws? (str)
166   "Return t if string is all whitespace"
167   (when (stringp str)
168     (null (find-if #'not-whitespace? str))))
169
170 (defun replaced-string-length (str repl-alist)
171   (declare (simple-string str)
172            (optimize (speed 3) (safety 0) (space 0)))
173     (do* ((i 0 (1+ i))
174           (orig-len (length str))
175           (new-len orig-len))
176          ((= i orig-len) new-len)
177       (declare (fixnum i orig-len new-len))
178       (let* ((c (char str i))
179              (match (assoc c repl-alist :test #'char=)))
180         (declare (character c))
181         (when match
182           (incf new-len (1- (length
183                              (the simple-string (cdr match)))))))))
184
185 (defun substitute-chars-strings (str repl-alist)
186   "Replace all instances of a chars with a string. repl-alist is an assoc
187 list of characters and replacement strings."
188   (declare (simple-string str)
189            (optimize (speed 3) (safety 0) (space 0)))
190   (do* ((orig-len (length str))
191         (new-string (make-string (replaced-string-length str repl-alist)))
192         (spos 0 (1+ spos))
193         (dpos 0))
194       ((>= spos orig-len)
195        new-string)
196     (declare (fixnum spos dpos) (simple-string new-string))
197     (let* ((c (char str spos))
198            (match (assoc c repl-alist :test #'char=)))
199       (declare (character c))
200       (if match
201           (let* ((subst (cdr match))
202                  (len (length subst)))
203             (declare (fixnum len)
204                      (simple-string subst))
205             (dotimes (j len)
206               (declare (fixnum j))
207               (setf (char new-string dpos) (char subst j))
208               (incf dpos)))
209         (progn
210           (setf (char new-string dpos) c)
211           (incf dpos))))))
212
213 (defun escape-xml-string (string)
214   "Escape invalid XML characters"
215   (substitute-chars-strings string '((#\& . "&amp;") (#\< . "&lt;"))))
216
217 (defun make-usb8-array (len)
218   (make-array len :element-type '(unsigned-byte 8)))
219
220 (defun usb8-array-to-string (vec)
221   (declare (type (simple-array (unsigned-byte 8) (*)) vec))
222   (let* ((len (length vec))
223          (str (make-string len)))
224     (declare (fixnum len)
225              (simple-string str)
226              (optimize (speed 3)))
227     (do ((i 0 (1+ i)))
228         ((= i len) str)
229       (declare (fixnum i))
230       (setf (schar str i) (code-char (aref vec i))))))
231
232 (defun string-to-usb8-array (str)
233   (declare (simple-string str))
234   (let* ((len (length str))
235          (vec (make-usb8-array len)))
236     (declare (fixnum len)
237              (type (simple-array (unsigned-byte 8) (*)) vec)
238              (optimize (speed 3)))
239     (do ((i 0 (1+ i)))
240         ((= i len) vec)
241       (declare (fixnum i))
242       (setf (aref vec i) (char-code (schar str i))))))
243
244 (defun concat-separated-strings (separator &rest lists)
245   (format nil (concatenate 'string "~{~A~^" (string separator) "~}")
246           (append-sublists lists)))
247
248 (defun only-null-list-elements-p (lst)
249   (or (null lst) (every #'null lst)))
250
251 (defun print-separated-strings (strm separator &rest lists)
252   (declare (optimize (speed 3) (safety 0) (space 0) (debug 0)
253                      (compilation-speed 0)))
254   (do* ((rest-lists lists (cdr rest-lists))
255         (list (car rest-lists) (car rest-lists))
256         (last-list (only-null-list-elements-p (cdr rest-lists))
257                    (only-null-list-elements-p (cdr rest-lists))))
258        ((null rest-lists) strm)
259     (do* ((lst list (cdr lst))
260           (elem (car lst) (car lst))
261           (last-elem (null (cdr lst)) (null (cdr lst))))
262          ((null lst))
263       (write-string elem strm)
264       (unless (and last-elem last-list)
265         (write-string separator strm)))))
266
267 (defun prefixed-fixnum-string (num pchar len)
268   "Outputs a string of LEN digit with an optional initial character PCHAR.
269 Leading zeros are present."
270   (declare (optimize (speed 3) (safety 0) (space 0))
271            (type fixnum num len))
272   (when pchar
273     (incf len))
274   (do* ((zero-code (char-code #\0))
275         (result (make-string len :initial-element #\0))
276         (minus? (minusp num))
277         (val (if minus? (- num) num)
278              (nth-value 0 (floor val 10)))
279         (pos (1- len) (1- pos))
280         (mod (mod val 10) (mod val 10)))
281       ((or (zerop val) (minusp pos))
282        (when pchar
283          (setf (schar result 0) pchar))
284        (when minus? (setf (schar result (if pchar 1 0)) #\-))
285        result)
286     (declare (fixnum val mod zero-code pos) (simple-string result))
287     (setf (schar result pos) (code-char (+ zero-code mod)))))
288
289 (defun integer-string (num len)
290   "Outputs a string of LEN digit with an optional initial character PCHAR.
291 Leading zeros are present."
292   (declare (optimize (speed 3) (safety 0) (space 0))
293            (type fixnum len)
294            (type integer num))
295   (do* ((zero-code (char-code #\0))
296         (result (make-string len :initial-element #\0))
297         (minus? (minusp num))
298         (val (if minus? (- 0 num) num)
299              (nth-value 0 (floor val 10)))
300         (pos (1- len) (1- pos))
301         (mod (mod val 10) (mod val 10)))
302       ((or (zerop val) (minusp pos))
303        (when minus? (setf (schar result 0) #\-))
304        result)
305     (declare (fixnum mod zero-code pos) (simple-string result) (integer val))
306     (setf (schar result pos) (code-char (+ zero-code mod)))))
307
308 (defun fast-string-search (substr str substr-length startpos endpos)
309   "Optimized search for a substring in a simple-string"
310   (declare (simple-string substr str)
311            (fixnum substr-length startpos endpos)
312            (optimize (speed 3) (space 0) (safety 0)))
313   (do* ((pos startpos (1+ pos))
314         (lastpos (- endpos substr-length)))
315        ((> pos lastpos) nil)
316     (declare (fixnum pos lastpos))
317     (do ((i 0 (1+ i)))
318         ((= i substr-length)
319          (return-from fast-string-search pos))
320       (declare (fixnum i))
321       (unless (char= (schar str (+ i pos)) (schar substr i))
322         (return nil)))))
323
324 (defun string-delimited-string-to-list (str substr)
325   "splits a string delimited by substr into a list of strings"
326   (declare (simple-string str substr)
327            (optimize (speed 3) (safety 0) (space 0) (compilation-speed 0)
328                      (debug 0)))
329   (do* ((substr-len (length substr))
330         (strlen (length str))
331         (output '())
332         (pos 0)
333         (end (fast-string-search substr str substr-len pos strlen)
334              (fast-string-search substr str substr-len pos strlen)))
335        ((null end)
336         (when (< pos strlen)
337           (push (subseq str pos) output))
338         (nreverse output))
339     (declare (fixnum strlen substr-len pos)
340              (type (or fixnum null) end))
341     (push (subseq str pos end) output)
342     (setq pos (+ end substr-len))))
343   
344 (defun string-to-list-skip-delimiter (str &optional (delim #\space))
345   "Return a list of strings, delimited by spaces, skipping spaces."
346   (declare (simple-string str)
347            (optimize (speed 0) (space 0) (safety 0)))
348   (do* ((results '())
349         (end (length str))
350         (i (position-not-char delim str 0 end)
351            (position-not-char delim str j end))
352         (j (when i (position-char delim str i end))
353            (when i (position-char delim str i end))))
354        ((or (null i) (null j))
355         (when (and i (< i end))
356           (push (subseq str i end) results))
357         (nreverse results))
358     (declare (fixnum end)
359              (type (or fixnum null) i j))
360     (push (subseq str i j) results)))
361
362 (defun string-starts-with (start str)
363   (and (>= (length str) (length start))
364        (string-equal start str :end2 (length start))))
365
366 (defun count-string-char (s c)
367   "Return a count of the number of times a character appears in a string"
368   (declare (simple-string s)
369            (character c)
370            (optimize (speed 3) (safety 0)))
371   (do ((len (length s))
372        (i 0 (1+ i))
373        (count 0))
374       ((= i len) count)
375     (declare (fixnum i len count))
376     (when (char= (schar s i) c)
377       (incf count))))
378
379 (defun count-string-char-if (pred s)
380   "Return a count of the number of times a predicate is true
381 for characters in a string"
382   (declare (simple-string s)
383            (type (or function symbol) pred)
384            (optimize (speed 3) (safety 0) (space 0)))
385   (do ((len (length s))
386        (i 0 (1+ i))
387        (count 0))
388       ((= i len) count)
389     (declare (fixnum i len count))
390     (when (funcall pred (schar s i))
391       (incf count))))
392
393
394 ;;; URL Encoding
395
396 (defun non-alphanumericp (ch)
397   (not (alphanumericp ch)))
398
399 (defvar +hex-chars+ "0123456789ABCDEF")
400 (declaim (type simple-string +hex-chars+))
401
402 (defun hexchar (n)
403   (declare (type (integer 0 15) n))
404   (schar +hex-chars+ n))
405
406 (defconstant +char-code-lower-a+ (char-code #\a))
407 (defconstant +char-code-upper-a+ (char-code #\A))
408 (defconstant +char-code-0+ (char-code #\0))
409 (declaim (type fixnum +char-code-0+ +char-code-upper-a+
410                +char-code-0))
411
412 (defun charhex (ch)
413   "convert hex character to decimal"
414   (let ((code (char-code (char-upcase ch))))
415     (declare (fixnum ch)) 
416     (if (>= code +char-code-upper-a+)
417         (+ 10 (- code +char-code-upper-a+))
418         (- code +char-code-0+))))
419
420 (defun escape-uri-field (query)
421   "Escape non-alphanumeric characters for URI fields"
422   (declare (simple-string query)
423            (optimize (speed 3) (safety 0) (space 0)))
424   (do* ((count (count-string-char-if #'non-alphanumericp query))
425         (len (length query))
426         (new-len (+ len (* 2 count)))
427         (str (make-string new-len))
428         (spos 0 (1+ spos))
429         (dpos 0 (1+ dpos)))
430       ((= spos len) str)
431     (declare (fixnum count len new-len spos dpos)
432              (simple-string str))
433     (let ((ch (schar query spos)))
434       (if (non-alphanumericp ch)
435           (let ((c (char-code ch)))
436             (setf (schar str dpos) #\%)
437             (incf dpos)
438             (setf (schar str dpos) (hexchar (logand (ash c -4) 15)))
439             (incf dpos)
440             (setf (schar str dpos) (hexchar (logand c 15))))
441         (setf (schar str dpos) ch)))))
442
443 (defun unescape-uri-field (query)
444   "Unescape non-alphanumeric characters for URI fields"
445   (declare (simple-string query)
446            (optimize (speed 3) (safety 0) (space 0)))
447   (do* ((count (count-string-char query #\%))
448         (len (length query))
449         (new-len (- len (* 2 count)))
450         (str (make-string new-len))
451         (spos 0 (1+ spos))
452         (dpos 0 (1+ dpos)))
453       ((= spos len) str)
454     (declare (fixnum count len new-len spos dpos)
455              (simple-string str))
456     (let ((ch (schar query spos)))
457       (if (char= #\% ch)
458           (let ((c1 (charhex (schar query (1+ spos))))
459                 (c2 (charhex (schar query (+ spos 2)))))
460             (declare (fixnum c1 c2))
461             (setf (schar str dpos)
462                   (code-char (logior c2 (ash c1 4))))
463             (incf spos 2))
464         (setf (schar str dpos) ch)))))
465
466
467
468 (eval-when (:compile-toplevel :load-toplevel :execute)
469   (defvar +unambigous-charset+
470     "abcdefghjkmnpqrstuvwxyz123456789ABCDEFGHJKLMNPQSRTUVWXYZ")
471   (defconstant +unambigous-length+ (length +unambigous-charset+)))
472
473 (defun random-char (&optional (set :lower-alpha))
474   (ecase set
475     (:lower-alpha
476      (code-char (+ +char-code-lower-a+ (random 26))))
477     (:lower-alphanumeric
478      (let ((n (random 36)))
479        (if (>= n 26)
480            (code-char (+ +char-code-0+ (- n 26)))
481          (code-char (+ +char-code-lower-a+ n)))))
482     (:upper-alpha
483      (code-char (+ +char-code-upper-a+ (random 26))))
484     (:unambigous
485      (schar +unambigous-charset+ (random +unambigous-length+)))
486     (:upper-lower-alpha
487      (let ((n (random 52)))
488        (if (>= n 26)
489            (code-char (+ +char-code-upper-a+ (- n 26)))
490          (code-char (+ +char-code-lower-a+ n)))))))
491      
492
493 (defun random-string (&key (length 10) (set :lower-alpha))
494   "Returns a random lower-case string."
495   (declare (optimize (speed 3)))
496   (let ((s (make-string length)))
497     (declare (simple-string s))
498     (dotimes (i length s)
499       (setf (schar s i) (random-char set)))))
500
501
502 (defun first-char (s)
503   (declare (simple-string s))
504   (when (and (stringp s) (plusp (length s)))
505     (schar s 0)))
506
507 (defun last-char (s)
508   (declare (simple-string s))
509   (when (stringp s)
510     (let ((len (length s)))
511       (when (plusp len))
512       (schar s (1- len)))))
513
514 (defun ensure-string (v)
515   (typecase v
516     (string v)
517     (character (string v))
518     (symbol (symbol-name v))
519     (otherwise (write-to-string v))))
520
521 (defun string-right-trim-one-char (char str)
522   (declare (simple-string str))
523   (let* ((len (length str))
524          (last (1- len)))
525     (declare (fixnum len last))
526     (if (char= char (schar str last))
527         (subseq str 0 last)
528       str)))
529
530
531 (defun string-strip-ending (str endings)
532   (if (stringp endings)
533       (setq endings (list endings)))
534   (let ((len (length str)))
535     (dolist (ending endings str)
536       (when (and (>= len (length ending))
537                  (string-equal ending
538                                (subseq str (- len
539                                               (length ending)))))
540         (return-from string-strip-ending
541           (subseq str 0 (- len (length ending))))))))
542        
543
544 (defun string-maybe-shorten (str maxlen)
545   (let ((len (length str)))
546     (if (<= len maxlen)
547         str
548       (concatenate 'string (subseq str 0 (- maxlen 3)) "..."))))
549
550
551 (defun shrink-vector (str size)
552   #+allegro
553   (excl::.primcall 'sys::shrink-svector str size)
554   #+cmu
555   (lisp::shrink-vector str size)
556   #+lispworks
557   (system::shrink-vector$vector str size)
558   #+sbcl
559   (sb-kernel:shrink-vector str size)
560   #+scl
561   (common-lisp::shrink-vector str size)
562   #-(or allegro cmu lispworks sbcl scl)
563   (setq str (subseq str 0 size))
564   str)
565
566 (defun lex-string (string &key (whitespace '(#\space #\newline)))
567   "Separates a string at whitespace and returns a list of strings"
568   (flet ((whitespace? (char) (member char whitespace :test #'char=)))
569     (let ((tokens nil))
570       (do* ((token-start
571              (position-if-not #'whitespace? string) 
572              (when token-end
573                (position-if-not #'whitespace? string :start (1+ token-end))))
574             (token-end
575              (when token-start
576                (position-if #'whitespace? string :start token-start))
577              (when token-start
578                (position-if #'whitespace? string :start token-start))))
579            ((null token-start) (nreverse tokens))
580         (push (subseq string token-start token-end) tokens)))))
581
582 (defun split-alphanumeric-string (string)
583   "Separates a string at any non-alphanumeric chararacter"
584   (flet ((whitespace? (char) (non-alphanumericp char)))
585     (let ((tokens nil))
586       (do* ((token-start
587              (position-if-not #'whitespace? string) 
588              (when token-end
589                (position-if-not #'whitespace? string :start (1+ token-end))))
590             (token-end
591              (when token-start
592                (position-if #'whitespace? string :start token-start))
593              (when token-start
594                (position-if #'whitespace? string :start token-start))))
595            ((null token-start) (nreverse tokens))
596         (push (subseq string token-start token-end) tokens)))))
597
598