r5246: *** 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.46 2003/07/08 00:12:51 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-0+ (char-code #\0))
407 (defconstant +char-code-upper-a+ (char-code #\A))
408 (declaim (type fixnum +char-code-0+ +char-code-upper-a+))
409
410 (defun charhex (ch)
411   "convert hex character to decimal"
412   (let ((code (char-code (char-upcase ch))))
413     (declare (fixnum ch)) 
414     (if (>= code +char-code-upper-a+)
415         (+ 10 (- code +char-code-upper-a+))
416         (- code +char-code-0+))))
417
418 (defun escape-uri-field (query)
419   "Escape non-alphanumeric characters for URI fields"
420   (declare (simple-string query)
421            (optimize (speed 3) (safety 0) (space 0)))
422   (do* ((count (count-string-char-if #'non-alphanumericp query))
423         (len (length query))
424         (new-len (+ len (* 2 count)))
425         (str (make-string new-len))
426         (spos 0 (1+ spos))
427         (dpos 0 (1+ dpos)))
428       ((= spos len) str)
429     (declare (fixnum count len new-len spos dpos)
430              (simple-string str))
431     (let ((ch (schar query spos)))
432       (if (non-alphanumericp ch)
433           (let ((c (char-code ch)))
434             (setf (schar str dpos) #\%)
435             (incf dpos)
436             (setf (schar str dpos) (hexchar (logand (ash c -4) 15)))
437             (incf dpos)
438             (setf (schar str dpos) (hexchar (logand c 15))))
439         (setf (schar str dpos) ch)))))
440
441 (defun unescape-uri-field (query)
442   "Unescape non-alphanumeric characters for URI fields"
443   (declare (simple-string query)
444            (optimize (speed 3) (safety 0) (space 0)))
445   (do* ((count (count-string-char query #\%))
446         (len (length query))
447         (new-len (- len (* 2 count)))
448         (str (make-string new-len))
449         (spos 0 (1+ spos))
450         (dpos 0 (1+ dpos)))
451       ((= spos len) str)
452     (declare (fixnum count len new-len spos dpos)
453              (simple-string str))
454     (let ((ch (schar query spos)))
455       (if (char= #\% ch)
456           (let ((c1 (charhex (schar query (1+ spos))))
457                 (c2 (charhex (schar query (+ spos 2)))))
458             (declare (fixnum c1 c2))
459             (setf (schar str dpos)
460                   (code-char (logior c2 (ash c1 4))))
461             (incf spos 2))
462         (setf (schar str dpos) ch)))))
463
464
465 (defconstant +char-code-a+ (char-code #\a))
466
467 (defun random-string (&optional (len 10))
468   "Returns a random lower-case string."
469   (declare (optimize (speed 3)))
470   (let ((s (make-string len)))
471     (declare (simple-string s))
472     (dotimes (i len s)
473       (setf (schar s i)
474             (code-char (+ +char-code-a+ (random 26)))))))
475
476
477 (defun first-char (s)
478   (declare (simple-string s))
479   (when (and (stringp s) (plusp (length s)))
480     (schar s 0)))
481
482 (defun last-char (s)
483   (declare (simple-string s))
484   (when (stringp s)
485     (let ((len (length s)))
486       (when (plusp len))
487       (schar s (1- len)))))
488
489 (defun ensure-string (v)
490   (typecase v
491     (string v)
492     (character (string v))
493     (symbol (symbol-name v))
494     (otherwise (write-to-string v))))
495
496 (defun string-left-trim-one-char (char str)
497   (declare (simple-string str))
498   (let* ((len (length str))
499          (last (1- len)))
500     (declare (fixnum len last))
501     (if (char= char (schar str last))
502         (subseq str 0 last)
503       str)))
504
505