Add make-string
[jscl.git] / src / string.lisp
1 ;;; string.lisp
2
3 ;; JSCL is free software: you can redistribute it and/or
4 ;; modify it under the terms of the GNU General Public License as
5 ;; published by the Free Software Foundation, either version 3 of the
6 ;; License, or (at your option) any later version.
7 ;;
8 ;; JSCL is distributed in the hope that it will be useful, but
9 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
10 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 ;; General Public License for more details.
12 ;;
13 ;; You should have received a copy of the GNU General Public License
14 ;; along with JSCL.  If not, see <http://www.gnu.org/licenses/>.
15
16 ;; (defun stringp (x)
17 ;;   (and (vectorp x) (eq (array-element-type x) 'character)))
18
19 (defun stringp (s)
20   (stringp s))
21
22 (defun make-string (n &key initial-element)
23   (make-array n :element-type 'character :initial-element initial-element))
24
25 ;; (defun char-to-string (x)
26 ;;   (make-string 1 :initial-element x))
27
28 (defun string (x)
29   (cond ((stringp x) x)
30         ((symbolp x) (symbol-name x))
31         (t (char-to-string x))))
32
33 (defun string= (s1 s2)
34   (let* ((s1 (string s1))
35          (s2 (string s2))
36          (n (length s1)))
37     (when (= (length s2) n)
38       (dotimes (i n t)
39         (unless (char= (char s1 i) (char s2 i))
40           (return-from string= nil))))))
41
42 (defun string< (s1 s2)
43   (let ((len-1 (length s1))
44         (len-2 (length s2)))
45     (cond ((= len-2 0) nil)
46           ((= len-1 0) 0)
47           (t (dotimes (i len-1 nil)
48                (when (char< (char s1 i) (char s2 i))
49                  (return-from string< i))
50                (when (and (= i (1- len-1)) (> len-2 len-1))
51                  (return-from string< (1+ i))))))))
52
53 (define-setf-expander char (string index)
54   (let ((g!string (gensym))
55         (g!index (gensym))
56         (g!value (gensym)))
57     (values (list g!string g!index)
58             (list string index)
59             (list g!value)
60             `(aset ,g!string ,g!index ,g!value)
61             `(char ,g!string ,g!index))))
62
63 (defun concatenate-two (string1 string2)
64   (let* ((len1 (length string1))
65          (len2 (length string2))
66          (string (make-array (+ len1 len2) :element-type 'character))
67          (i 0))
68     (dotimes (j len1)
69       (aset string i (char string1 j))
70       (incf i))
71     (dotimes (j len2)
72       (aset string i (char string2 j))
73       (incf i))
74     string))