altos/lisp: Change lisp objects to use ao_poly everywhere. Add const
[fw/altos] / src / lisp / ao_lisp_string.c
1 /*
2  * Copyright © 2016 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program 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 along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #include "ao_lisp.h"
19
20 static void string_mark(void *addr)
21 {
22         (void) addr;
23 }
24
25 static int string_size(void *addr)
26 {
27         if (!addr)
28                 return 0;
29         return strlen(addr) + 1;
30 }
31
32 static void string_move(void *addr)
33 {
34         (void) addr;
35 }
36
37 char *
38 ao_lisp_string_new(int len) {
39         char    *a = ao_lisp_alloc(len + 1);
40         if (!a)
41                 return NULL;
42         a[len] = '\0';
43         return a;
44 }
45
46 char *
47 ao_lisp_string_copy(char *a)
48 {
49         int     alen = strlen(a);
50
51         char    *r = ao_lisp_alloc(alen + 1);
52         if (!r)
53                 return NULL;
54         strcpy(r, a);
55         return r;
56 }
57
58 char *
59 ao_lisp_string_cat(char *a, char *b)
60 {
61         int     alen = strlen(a);
62         int     blen = strlen(b);
63         char    *r = ao_lisp_alloc(alen + blen + 1);
64         if (!r)
65                 return NULL;
66         strcpy(r, a);
67         strcpy(r+alen, b);
68         return r;
69 }
70
71 const struct ao_lisp_type ao_lisp_string_type = {
72         .mark = string_mark,
73         .size = string_size,
74         .move = string_move,
75 };
76
77 void
78 ao_lisp_string_print(ao_poly p)
79 {
80         char    *s = ao_lisp_poly_string(p);
81         char    c;
82
83         putchar('"');
84         while ((c = *s++)) {
85                 switch (c) {
86                 case '\n':
87                         printf ("\\n");
88                         break;
89                 case '\r':
90                         printf ("\\r");
91                         break;
92                 case '\t':
93                         printf ("\\t");
94                         break;
95                 default:
96                         putchar(c);
97                         break;
98                 }
99         }
100         putchar('"');
101 }