Debian Codegraph @

src/c/reader/parse_integer.d

raw
1 /* -*- Mode: C; c-basic-offset: 2; indent-tabs-mode: nil -*- */
2 /* vim: set filetype=c tabstop=2 shiftwidth=2 expandtab: */
3
4 /*
5 *
6 * Copyright (c) 1984 Taiichi Yuasa and Masami Hagiya
7 * Copyright (c) 1990 Giuseppe Attardi
8 * Copyright (c) 2001 Juan Jose Garcia Ripoll
9 *
10 * See file 'LICENSE' for the copyright details.
11 *
12 */
13
14 #include <ecl/ecl.h>
15 #include <ecl/number.h>
16 #include <ecl/internal.h>
17
18 #define basep(d) (d <= 36)
19
20 cl_object
21 ecl_parse_integer(cl_object str, cl_index start, cl_index end,
22 cl_index *ep, unsigned int radix)
23 {
24 int sign, d;
25 cl_object integer_part, output;
26 cl_index i, c;
27
28 if (start >= end || !basep(radix)) {
29 *ep = start;
30 return OBJNULL;
31 }
32 sign = 1;
33 c = ecl_char(str, start);
34 if (c == '+') {
35 start++;
36 } else if (c == '-') {
37 sign = -1;
38 start++;
39 }
40 integer_part = _ecl_big_register0();
41 _ecl_big_set_ui(integer_part, 0);
42 for (i = start; i < end; i++) {
43 c = ecl_char(str, i);
44 d = ecl_digitp(c, radix);
45 if (d < 0) {
46 break;
47 }
48 _ecl_big_mul_ui(integer_part, integer_part, radix);
49 _ecl_big_add_ui(integer_part, integer_part, d);
50 }
51 if (sign < 0) {
52 _ecl_big_complement(integer_part, integer_part);
53 }
54 output = _ecl_big_register_normalize(integer_part);
55 *ep = i;
56 return (i == start)? OBJNULL : output;
57 }
58
59 @(defun parse_integer (strng
60 &key (start ecl_make_fixnum(0))
61 end
62 (radix ecl_make_fixnum(10))
63 junk_allowed
64 &aux x)
65 cl_index s, e, ep;
66 cl_object rtbl = ecl_current_readtable();
67 @ {
68 unlikely_if (!ECL_STRINGP(strng)) {
69 FEwrong_type_nth_arg(@[parse-integer], 1, strng, @[string]);
70 }
71 unlikely_if (!ECL_FIXNUMP(radix) ||
72 ecl_fixnum_lower(radix, ecl_make_fixnum(2)) ||
73 ecl_fixnum_greater(radix, ecl_make_fixnum(36)))
74 {
75 FEerror("~S is an illegal radix.", 1, radix);
76 }
77 {
78 cl_index_pair p =
79 ecl_vector_start_end(@[parse-integer], strng, start, end);
80 s = p.start;
81 e = p.end;
82 }
83 while (s < e &&
84 ecl_readtable_get(rtbl, ecl_char(strng, s), NULL) == cat_whitespace) {
85 s++;
86 }
87 if (s >= e) {
88 if (junk_allowed != ECL_NIL) {
89 @(return ECL_NIL ecl_make_fixnum(s));
90 }
91 else {
92 goto CANNOT_PARSE;
93 }
94 }
95 x = ecl_parse_integer(strng, s, e, &ep, ecl_fixnum(radix));
96 if (x == OBJNULL) {
97 if (junk_allowed != ECL_NIL) {
98 @(return ECL_NIL ecl_make_fixnum(ep));
99 } else {
100 goto CANNOT_PARSE;
101 }
102 }
103 if (junk_allowed != ECL_NIL) {
104 @(return x ecl_make_fixnum(ep));
105 }
106 for (s = ep; s < e; s++) {
107 unlikely_if (ecl_readtable_get(rtbl, ecl_char(strng, s), NULL)
108 != cat_whitespace)
109 {
110 CANNOT_PARSE: FEparse_error("Cannot parse an integer in the string ~S.",
111 ECL_NIL, 1, strng);
112 }
113 }
114 @(return x ecl_make_fixnum(e));
115 } @)