Add first lisp bits
[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_cat(char *a, char *b)
48 {
49         int     alen = strlen(a);
50         int     blen = strlen(b);
51         char    *r = ao_lisp_alloc(alen + blen + 1);
52         if (!r)
53                 return NULL;
54         strcpy(r, a);
55         strcpy(r+alen, b);
56         return r;
57 }
58
59 const struct ao_lisp_mem_type ao_lisp_string_type = {
60         .mark = string_mark,
61         .size = string_size,
62         .move = string_move,
63 };
64
65 void
66 ao_lisp_string_print(char *s)
67 {
68         char    c;
69         putchar('"');
70         while ((c = *s++)) {
71                 switch (c) {
72                 case '\n':
73                         printf ("\\n");
74                         break;
75                 case '\r':
76                         printf ("\\r");
77                         break;
78                 case '\t':
79                         printf ("\\t");
80                         break;
81                 default:
82                         putchar(c);
83                         break;
84                 }
85         }
86         putchar('"');
87 }