]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/string.c
6d9434f726a966d6f3a0204939f8420f0f2754d1
[simgear.git] / simgear / nasal / string.c
1 #include <math.h>
2 #include <string.h>
3
4 #include "nasal.h"
5 #include "data.h"
6
7 // The maximum number of significant (decimal!) figures in an IEEE
8 // double.
9 #define DIGITS 16
10
11 // The minimum size we'll allocate for a string.  Since a string
12 // structure is already 12 bytes, and each naRef that points to it is
13 // 8, there isn't much point in being stingy.
14 #define MINLEN 16
15
16 static int tonum(unsigned char* s, int len, double* result);
17 static int fromnum(double val, unsigned char* s);
18
19 int naStr_len(naRef s)
20 {
21     if(!IS_STR(s)) return 0;
22     return s.ref.ptr.str->len;
23 }
24
25 char* naStr_data(naRef s)
26 {
27     if(!IS_STR(s)) return 0;
28     return s.ref.ptr.str->data;
29 }
30
31 static void setlen(struct naStr* s, int sz)
32 {
33     int currSz, waste;
34     sz += 1; // Allow for an extra nul terminator
35     currSz = s->len+1 < MINLEN ? MINLEN : s->len+1;
36     waste = currSz - sz; // how much extra if we don't reallocate?
37     if(s->data == 0 || waste < 0 || waste > MINLEN) {
38         naFree(s->data);
39         s->data = naAlloc(sz < MINLEN ? MINLEN : sz);
40     }
41     s->len = sz - 1;
42     s->data[s->len] = 0; // nul terminate
43 }
44
45 naRef naStr_fromdata(naRef dst, char* data, int len)
46 {
47     if(!IS_STR(dst)) return naNil();
48     setlen(dst.ref.ptr.str, len);
49     memcpy(dst.ref.ptr.str->data, data, len);
50     return dst;
51 }
52
53 naRef naStr_concat(naRef dest, naRef s1, naRef s2)
54 {
55     struct naStr* dst = dest.ref.ptr.str;
56     struct naStr* a = s1.ref.ptr.str;
57     struct naStr* b = s2.ref.ptr.str;
58     if(!(IS_STR(s1)&&IS_STR(s2)&&IS_STR(dest))) return naNil();
59     setlen(dst, a->len + b->len);
60     memcpy(dst->data, a->data, a->len);
61     memcpy(dst->data + a->len, b->data, b->len);
62     return dest;
63 }
64
65 naRef naStr_substr(naRef dest, naRef str, int start, int len)
66 {
67     struct naStr* dst = dest.ref.ptr.str;
68     struct naStr* s = str.ref.ptr.str;
69     if(!(IS_STR(dest)&&IS_STR(str))) return naNil();
70     if(start + len > s->len) { dst->len = 0; dst->data = 0; return naNil(); }
71     setlen(dst, len);
72     memcpy(dst->data, s->data + start, len);
73     return dest;
74 }
75
76 int naStr_equal(naRef s1, naRef s2)
77 {
78     struct naStr* a = s1.ref.ptr.str;
79     struct naStr* b = s2.ref.ptr.str;
80     if(a->data == b->data) return 1;
81     if(a->len != b->len) return 0;
82     if(memcmp(a->data, b->data, a->len) == 0) return 1;
83     return 0;
84 }
85
86 naRef naStr_fromnum(naRef dest, double num)
87 {
88     struct naStr* dst = dest.ref.ptr.str;
89     unsigned char buf[DIGITS+8];
90     setlen(dst, fromnum(num, buf));
91     memcpy(dst->data, buf, dst->len);
92     return dest;
93 }
94
95 int naStr_parsenum(char* str, int len, double* result)
96 {
97     return tonum(str, len, result);
98 }
99
100 int naStr_tonum(naRef str, double* out)
101 {
102     return tonum(str.ref.ptr.str->data, str.ref.ptr.str->len, out);
103 }
104
105 int naStr_numeric(naRef str)
106 {
107     double dummy;
108     return tonum(str.ref.ptr.str->data, str.ref.ptr.str->len, &dummy);
109 }
110
111 void naStr_gcclean(struct naStr* str)
112 {
113     if(str->len > MINLEN) {
114         naFree(str->data);
115         str->data = 0;
116     }
117     str->len = 0;
118 }
119
120 ////////////////////////////////////////////////////////////////////////
121 // Below is a custom double<->string conversion library.  Why not
122 // simply use sprintf and atof?  Because they aren't acceptably
123 // platform independant, sadly.  I've seen some very strange results.
124 // This works the same way everywhere, although it is tied to an
125 // assumption of standard IEEE 64 bit floating point doubles.
126 //
127 // In practice, these routines work quite well.  Testing conversions
128 // of random doubles to strings and back, this routine is beaten by
129 // glibc on roundoff error 23% of the time, beats glibc in 10% of
130 // cases, and ties (usually with an error of exactly zero) the
131 // remaining 67%.
132 ////////////////////////////////////////////////////////////////////////
133
134 // Reads an unsigned decimal out of the scalar starting at i, stores
135 // it in v, and returns the next index to start at.  Zero-length
136 // decimal numbers are allowed, and are returned as zero.
137 static int readdec(unsigned char* s, int len, int i, double* v)
138 {
139     *v = 0;
140     if(i >= len) return len;
141     while(i < len && s[i] >= '0' && s[i] <= '9') {
142         *v= (*v) * 10 + (s[i] - '0');
143         i++;
144     }
145     return i;
146 }
147
148 // Reads a signed integer out of the string starting at i, stores it
149 // in v, and returns the next index to start at.  Zero-length
150 // decimal numbers are allowed, and are returned as zero.
151 static int readsigned(unsigned char* s, int len, int i, double* v)
152 {
153     int i0 = i, i2;
154     double sgn=1, val;
155     if(i >= len) { *v = 0; return len; }
156     if(s[i] == '+')      { i++; }
157     else if(s[i] == '-') { i++; sgn = -1; }
158     i2 = readdec(s, len, i, &val);
159     if(i0 == i && i2 == i) {
160         *v = 0;
161         return i0; // don't successfully parse bare "+" or "-"
162     }
163     *v = sgn*val;
164     return i2;
165 }
166
167
168 // Integer decimal power utility, with a tweak that enforces
169 // integer-exactness for arguments where that is possible.
170 static double decpow(int exp)
171 {
172     double v = 1;
173     int absexp;
174     if(exp < 0 || exp >= DIGITS)
175         return pow(10, exp);
176     else
177         absexp = exp < 0 ? -exp : exp;
178     while(absexp--) v *= 10.0;
179     return v;
180 }
181
182 static int tonum(unsigned char* s, int len, double* result)
183 {
184     int i=0, fraclen=0;
185     double sgn=1, val, frac=0, exp=0;
186
187     // Special case, "." is not a number, even though "1." and ".0" are.
188     if(len == 1 && s[0] == '.')
189         return 0;
190
191     // Read the integer part
192     i = readsigned(s, len, i, &val);
193     if(val < 0) { sgn = -1; val = -val; }
194
195     // Read the fractional part, if any
196     if(i < len && s[i] == '.') {
197         i++;
198         fraclen = readdec(s, len, i, &frac) - i;
199         i += fraclen;
200     }
201
202     // Read the exponent, if any
203     if(i < len && (s[i] == 'e' || s[i] == 'E'))
204         i = readsigned(s, len, i+1, &exp);
205     
206     // compute the result
207     *result = sgn * (val + frac * decpow(-fraclen)) * decpow(exp);
208
209     // if we didn't use the whole string, return failure
210     if(i < len) return 0;
211     return 1;
212 }
213
214 // Very simple positive (!) integer print routine.  Puts the result in
215 // s and returns the number of characters written.  Does not null
216 // terminate the result.
217 static int decprint(int val, unsigned char* s)
218 {
219     int p=1, i=0;
220     if(val == 0) { *s = '0'; return 1; }
221     while(p <= val) p *= 10;
222     p /= 10;
223     while(p > 0) {
224         int count = 0;
225         while(val >= p) { val -= p; count++; }
226         s[i++] = '0' + count;
227         p /= 10;
228     }
229     return i;
230 }
231
232 // Takes a positive (!) floating point numbers, and returns exactly
233 // DIGITS decimal numbers in the buffer pointed to by s, and an
234 // integer exponent as the return value.  For example, printing 1.0
235 // will result in "1000000000000000" in the buffer and -15 as the
236 // exponent.  The caller can then place the floating point as needed.
237 static int rawprint(double val, unsigned char* s)
238 {
239     int exponent = (int)floor(log10(val));
240     double mantissa = val / pow(10, exponent);
241     int i, c;
242     for(i=0; i<DIGITS-1; i++) {
243         int digit = (int)floor(mantissa);
244         s[i] = '0' + digit;
245         mantissa -= digit;
246         mantissa *= 10.0;
247     }
248     // Round (i.e. don't floor) the last digit
249     c = (int)floor(mantissa);
250     if(mantissa - c >= 0.5) c++;
251     if(c < 0) c = 0;
252     if(c > 9) c = 9;
253     s[i] = '0' + c;
254     return exponent - DIGITS + 1;
255 }
256
257 static int fromnum(double val, unsigned char* s)
258 {
259     unsigned char raw[DIGITS];
260     unsigned char* ptr = s;
261     int exp, digs, i=0;
262
263     // Handle negatives
264     if(val < 0) { *ptr++ = '-'; val = -val; }
265
266     // Exactly an integer is a special case
267     if(val == (int)val) {
268         ptr += decprint(val, ptr);
269         *ptr = 0;
270         return ptr - s;
271     }
272
273     // Get the raw digits
274     exp = rawprint(val, raw);
275
276     // Examine trailing zeros to get a significant digit count
277     for(i=DIGITS-1; i>0; i--)
278         if(raw[i] != '0') break;
279     digs = i+1;
280
281     if(exp > 0 || exp < -(DIGITS+2)) {
282         // Standard scientific notation
283         exp += DIGITS-1;
284         *ptr++ = raw[0];
285         if(digs > 1) {
286             *ptr++ = '.';
287             for(i=1; i<digs; i++) *ptr++ = raw[i];
288         }
289         *ptr++ = 'e';
290         if(exp < 0) { exp = -exp; *ptr++ = '-'; }
291         else { *ptr++ = '+'; }
292         if(exp < 10) *ptr++ = '0';
293         ptr += decprint(exp, ptr);
294     } else if(exp < 1-DIGITS) {
295         // Fraction with insignificant leading zeros
296         *ptr++ = '0'; *ptr++ = '.';
297         for(i=0; i<-(exp+DIGITS); i++) *ptr++ = '0';
298         for(i=0; i<digs; i++) *ptr++ = raw[i];
299     } else {
300         // Integer part
301         for(i=0; i<DIGITS+exp; i++) *ptr++ = raw[i];
302         if(i < digs) {
303             // Fraction, if any
304             *ptr++ = '.';
305             while(i<digs) *ptr++ = raw[i++];
306         }
307     }
308     *ptr = 0;
309     return ptr - s;
310 }