altos/lisp: Add 'big' ints -- 24 bits wide
[fw/altos] / src / lisp / ao_lisp_int.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, either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  */
14
15 #include "ao_lisp.h"
16
17 void
18 ao_lisp_int_write(ao_poly p)
19 {
20         int i = ao_lisp_poly_int(p);
21         printf("%d", i);
22 }
23
24 int32_t
25 ao_lisp_poly_integer(ao_poly p)
26 {
27         switch (ao_lisp_poly_base_type(p)) {
28         case AO_LISP_INT:
29                 return ao_lisp_poly_int(p);
30         case AO_LISP_OTHER:
31                 if (ao_lisp_other_type(ao_lisp_poly_other(p)) == AO_LISP_BIGINT)
32                         return ao_lisp_bigint_int(ao_lisp_poly_bigint(p)->value);
33         }
34         return AO_LISP_NOT_INTEGER;
35 }
36
37 ao_poly
38 ao_lisp_integer_poly(int32_t p)
39 {
40         struct ao_lisp_bigint   *bi;
41
42         if (AO_LISP_MIN_INT <= p && p <= AO_LISP_MAX_INT)
43                 return ao_lisp_int_poly(p);
44         bi = ao_lisp_alloc(sizeof (struct ao_lisp_bigint));
45         bi->value = ao_lisp_int_bigint(p);
46         return ao_lisp_bigint_poly(bi);
47 }
48
49 static void bigint_mark(void *addr)
50 {
51         (void) addr;
52 }
53
54 static int bigint_size(void *addr)
55 {
56         if (!addr)
57                 return 0;
58         return sizeof (struct ao_lisp_bigint);
59 }
60
61 static void bigint_move(void *addr)
62 {
63         (void) addr;
64 }
65
66 const struct ao_lisp_type ao_lisp_bigint_type = {
67         .mark = bigint_mark,
68         .size = bigint_size,
69         .move = bigint_move,
70         .name = "bigint",
71 };
72
73 void
74 ao_lisp_bigint_write(ao_poly p)
75 {
76         struct ao_lisp_bigint   *bi = ao_lisp_poly_bigint(p);
77
78         printf("%d", ao_lisp_bigint_int(bi->value));
79 }