]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/string.c
Clamp pitch values rather than just dumping an error message.
[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 (and length-1 strings like '+') are allowed, and
151 // are returned as zero.
152 static int readsigned(unsigned char* s, int len, int i, double* v)
153 {
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     i = readdec(s, len, i, &val);
159     *v = sgn*val;
160     return i;
161 }
162
163
164 // Integer decimal power utility, with a tweak that enforces
165 // integer-exactness for arguments where that is possible.
166 static double decpow(int exp)
167 {
168     double v = 1;
169     int absexp;
170     if(exp < 0 || exp >= DIGITS)
171         return pow(10, exp);
172     else
173         absexp = exp < 0 ? -exp : exp;
174     while(absexp--) v *= 10.0;
175     return v;
176 }
177
178 static int tonum(unsigned char* s, int len, double* result)
179 {
180     int i=0, fraclen=0;
181     double sgn=1, val, frac=0, exp=0;
182
183     // Read the integer part
184     i = readsigned(s, len, i, &val);
185     if(val < 0) { sgn = -1; val = -val; }
186
187     // Read the fractional part, if any
188     if(i < len && s[i] == '.') {
189         i++;
190         fraclen = readdec(s, len, i, &frac) - i;
191         i += fraclen;
192     }
193
194     // Read the exponent, if any
195     if(i < len && (s[i] == 'e' || s[i] == 'E'))
196         i = readsigned(s, len, i+1, &exp);
197     
198     // compute the result
199     *result = sgn * (val + frac * decpow(-fraclen)) * decpow(exp);
200
201     // if we didn't use the whole string, return failure
202     if(i < len) return 0;
203     return 1;
204 }
205
206 // Very simple positive (!) integer print routine.  Puts the result in
207 // s and returns the number of characters written.  Does not null
208 // terminate the result.
209 static int decprint(int val, unsigned char* s)
210 {
211     int p=1, i=0;
212     if(val == 0) { *s = '0'; return 1; }
213     while(p <= val) p *= 10;
214     p /= 10;
215     while(p > 0) {
216         int count = 0;
217         while(val >= p) { val -= p; count++; }
218         s[i++] = '0' + count;
219         p /= 10;
220     }
221     return i;
222 }
223
224 // Takes a positive (!) floating point numbers, and returns exactly
225 // DIGITS decimal numbers in the buffer pointed to by s, and an
226 // integer exponent as the return value.  For example, printing 1.0
227 // will result in "1000000000000000" in the buffer and -15 as the
228 // exponent.  The caller can then place the floating point as needed.
229 static int rawprint(double val, unsigned char* s)
230 {
231     int exponent = (int)floor(log10(val));
232     double mantissa = val / pow(10, exponent);
233     int i, c;
234     for(i=0; i<DIGITS-1; i++) {
235         int digit = (int)floor(mantissa);
236         s[i] = '0' + digit;
237         mantissa -= digit;
238         mantissa *= 10.0;
239     }
240     // Round (i.e. don't floor) the last digit
241     c = (int)floor(mantissa);
242     if(mantissa - c >= 0.5) c++;
243     if(c < 0) c = 0;
244     if(c > 9) c = 9;
245     s[i] = '0' + c;
246     return exponent - DIGITS + 1;
247 }
248
249 static int fromnum(double val, unsigned char* s)
250 {
251     unsigned char raw[DIGITS];
252     unsigned char* ptr = s;
253     int exp, digs, i=0;
254
255     // Handle negatives
256     if(val < 0) { *ptr++ = '-'; val = -val; }
257
258     // Exactly an integer is a special case
259     if(val == (int)val) {
260         ptr += decprint(val, ptr);
261         *ptr = 0;
262         return ptr - s;
263     }
264
265     // Get the raw digits
266     exp = rawprint(val, raw);
267
268     // Examine trailing zeros to get a significant digit count
269     for(i=DIGITS-1; i>0; i--)
270         if(raw[i] != '0') break;
271     digs = i+1;
272
273     if(exp > 0 || exp < -(DIGITS+2)) {
274         // Standard scientific notation
275         exp += DIGITS-1;
276         *ptr++ = raw[0];
277         if(digs > 1) {
278             *ptr++ = '.';
279             for(i=1; i<digs; i++) *ptr++ = raw[i];
280         }
281         *ptr++ = 'e';
282         if(exp < 0) { exp = -exp; *ptr++ = '-'; }
283         else { *ptr++ = '+'; }
284         if(exp < 10) *ptr++ = '0';
285         ptr += decprint(exp, ptr);
286     } else if(exp < 1-DIGITS) {
287         // Fraction with insignificant leading zeros
288         *ptr++ = '0'; *ptr++ = '.';
289         for(i=0; i<-(exp+DIGITS); i++) *ptr++ = '0';
290         for(i=0; i<digs; i++) *ptr++ = raw[i];
291     } else {
292         // Integer part
293         for(i=0; i<DIGITS+exp; i++) *ptr++ = raw[i];
294         if(i < digs) {
295             // Fraction, if any
296             *ptr++ = '.';
297             while(i<digs) *ptr++ = raw[i++];
298         }
299     }
300     *ptr = 0;
301     return ptr - s;
302 }