source: mainline/uspace/lib/posix/source/stdlib/strtold.c@ acdb5bac

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since acdb5bac was 3e6a98c5, checked in by Jiri Svoboda <jiri@…>, 13 years ago

Standards-compliant boolean type.

  • Property mode set to 100644
File size: 11.5 KB
Line 
1/*
2 * Copyright (c) 2011 Jiri Zarevucky
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/** @addtogroup libposix
30 * @{
31 */
32/** @file Backend for floating point conversions.
33 */
34
35#define LIBPOSIX_INTERNAL
36
37#include "../internal/common.h"
38#include "libc/stdbool.h"
39#include "posix/stdlib.h"
40
41#include "posix/assert.h"
42#include "posix/ctype.h"
43#include "posix/stdint.h"
44#include "posix/strings.h"
45#include "posix/errno.h"
46#include "posix/limits.h"
47
48#include "posix/float.h"
49
50#ifndef HUGE_VALL
51 #define HUGE_VALL (+1.0l / +0.0l)
52#endif
53
54#ifndef abs
55 #define abs(x) (((x) < 0) ? -(x) : (x))
56#endif
57
58/* If the constants are not defined, use double precision as default. */
59#ifndef LDBL_MANT_DIG
60 #define LDBL_MANT_DIG 53
61#endif
62#ifndef LDBL_MAX_EXP
63 #define LDBL_MAX_EXP 1024
64#endif
65#ifndef LDBL_MIN_EXP
66 #define LDBL_MIN_EXP (-1021)
67#endif
68#ifndef LDBL_DIG
69 #define LDBL_DIG 15
70#endif
71#ifndef LDBL_MIN
72 #define LDBL_MIN 2.2250738585072014E-308
73#endif
74
75/* power functions ************************************************************/
76
77#if LDBL_MAX_EXP >= 16384
78const int MAX_POW5 = 12;
79#else
80const int MAX_POW5 = 8;
81#endif
82
83/* The value at index i is approximately 5**(2**i). */
84long double pow5[] = {
85 0x5p0l,
86 0x19p0l,
87 0x271p0l,
88 0x5F5E1p0l,
89 0x2386F26FC1p0l,
90 0x4EE2D6D415B85ACEF81p0l,
91 0x184F03E93FF9F4DAA797ED6E38ED6p36l,
92 0x127748F9301D319BF8CDE66D86D62p185l,
93 0x154FDD7F73BF3BD1BBB77203731FDp482l,
94#if LDBL_MAX_EXP >= 16384
95 0x1C633415D4C1D238D98CAB8A978A0p1076l,
96 0x192ECEB0D02EA182ECA1A7A51E316p2265l,
97 0x13D1676BB8A7ABBC94E9A519C6535p4643l,
98 0x188C0A40514412F3592982A7F0094p9398l,
99#endif
100};
101
102#if LDBL_MAX_EXP >= 16384
103const int MAX_POW2 = 15;
104#else
105const int MAX_POW2 = 9;
106#endif
107
108/* Powers of two. */
109long double pow2[] = {
110 0x1P1l,
111 0x1P2l,
112 0x1P4l,
113 0x1P8l,
114 0x1P16l,
115 0x1P32l,
116 0x1P64l,
117 0x1P128l,
118 0x1P256l,
119 0x1P512l,
120#if LDBL_MAX_EXP >= 16384
121 0x1P1024l,
122 0x1P2048l,
123 0x1P4096l,
124 0x1P8192l,
125#endif
126};
127
128/**
129 * Multiplies a number by a power of five.
130 * The result may be inexact and may not be the best possible approximation.
131 *
132 * @param mant Number to be multiplied.
133 * @param exp Base 5 exponent.
134 * @return mant multiplied by 5**exp
135 */
136static long double mul_pow5(long double mant, int exp)
137{
138 if (mant == 0.0l || mant == HUGE_VALL) {
139 return mant;
140 }
141
142 if (abs(exp) >> (MAX_POW5 + 1) != 0) {
143 /* Too large exponent. */
144 errno = ERANGE;
145 return exp < 0 ? LDBL_MIN : HUGE_VALL;
146 }
147
148 if (exp < 0) {
149 exp = abs(exp);
150 for (int bit = 0; bit <= MAX_POW5; ++bit) {
151 /* Multiply by powers of five bit-by-bit. */
152 if (((exp >> bit) & 1) != 0) {
153 mant /= pow5[bit];
154 if (mant == 0.0l) {
155 /* Underflow. */
156 mant = LDBL_MIN;
157 errno = ERANGE;
158 break;
159 }
160 }
161 }
162 } else {
163 for (int bit = 0; bit <= MAX_POW5; ++bit) {
164 /* Multiply by powers of five bit-by-bit. */
165 if (((exp >> bit) & 1) != 0) {
166 mant *= pow5[bit];
167 if (mant == HUGE_VALL) {
168 /* Overflow. */
169 errno = ERANGE;
170 break;
171 }
172 }
173 }
174 }
175
176 return mant;
177}
178
179/**
180 * Multiplies a number by a power of two. This is always exact.
181 *
182 * @param mant Number to be multiplied.
183 * @param exp Base 2 exponent.
184 * @return mant multiplied by 2**exp.
185 */
186static long double mul_pow2(long double mant, int exp)
187{
188 if (mant == 0.0l || mant == HUGE_VALL) {
189 return mant;
190 }
191
192 if (exp > LDBL_MAX_EXP || exp < LDBL_MIN_EXP) {
193 errno = ERANGE;
194 return exp < 0 ? LDBL_MIN : HUGE_VALL;
195 }
196
197 if (exp < 0) {
198 exp = abs(exp);
199 for (int i = 0; i <= MAX_POW2; ++i) {
200 if (((exp >> i) & 1) != 0) {
201 mant /= pow2[i];
202 if (mant == 0.0l) {
203 mant = LDBL_MIN;
204 errno = ERANGE;
205 break;
206 }
207 }
208 }
209 } else {
210 for (int i = 0; i <= MAX_POW2; ++i) {
211 if (((exp >> i) & 1) != 0) {
212 mant *= pow2[i];
213 if (mant == HUGE_VALL) {
214 errno = ERANGE;
215 break;
216 }
217 }
218 }
219 }
220
221 return mant;
222}
223
224/* end power functions ********************************************************/
225
226
227
228/**
229 * Convert decimal string representation of the floating point number.
230 * Function expects the string pointer to be already pointed at the first
231 * digit (i.e. leading optional sign was already consumed by the caller).
232 *
233 * @param sptr Pointer to the storage of the string pointer. Upon successful
234 * conversion, the string pointer is updated to point to the first
235 * unrecognized character.
236 * @return An approximate representation of the input floating-point number.
237 */
238static long double parse_decimal(const char **sptr)
239{
240 assert(sptr != NULL);
241 assert (*sptr != NULL);
242
243 const int DEC_BASE = 10;
244 const char DECIMAL_POINT = '.';
245 const char EXPONENT_MARK = 'e';
246
247 const char *str = *sptr;
248 long double significand = 0;
249 long exponent = 0;
250
251 /* number of digits parsed so far */
252 int parsed_digits = 0;
253 bool after_decimal = false;
254
255 while (isdigit(*str) || (!after_decimal && *str == DECIMAL_POINT)) {
256 if (*str == DECIMAL_POINT) {
257 after_decimal = true;
258 str++;
259 continue;
260 }
261
262 if (parsed_digits == 0 && *str == '0') {
263 /* Nothing, just skip leading zeros. */
264 } else if (parsed_digits < LDBL_DIG) {
265 significand = significand * DEC_BASE + (*str - '0');
266 parsed_digits++;
267 } else {
268 exponent++;
269 }
270
271 if (after_decimal) {
272 /* Decrement exponent if we are parsing the fractional part. */
273 exponent--;
274 }
275
276 str++;
277 }
278
279 /* exponent */
280 if (tolower(*str) == EXPONENT_MARK) {
281 str++;
282
283 /* Returns MIN/MAX value on error, which is ok. */
284 long exp = strtol(str, (char **) &str, DEC_BASE);
285
286 if (exponent > 0 && exp > LONG_MAX - exponent) {
287 exponent = LONG_MAX;
288 } else if (exponent < 0 && exp < LONG_MIN - exponent) {
289 exponent = LONG_MIN;
290 } else {
291 exponent += exp;
292 }
293 }
294
295 *sptr = str;
296
297 /* Return multiplied by a power of ten. */
298 return mul_pow2(mul_pow5(significand, exponent), exponent);
299}
300
301/**
302 * Derive a hexadecimal digit from its character representation.
303 *
304 * @param ch Character representation of the hexadecimal digit.
305 * @return Digit value represented by an integer.
306 */
307static inline int hex_value(char ch)
308{
309 if (ch <= '9') {
310 return ch - '0';
311 } else {
312 return 10 + tolower(ch) - 'a';
313 }
314}
315
316/**
317 * Convert hexadecimal string representation of the floating point number.
318 * Function expects the string pointer to be already pointed at the first
319 * digit (i.e. leading optional sign and 0x prefix were already consumed
320 * by the caller).
321 *
322 * @param sptr Pointer to the storage of the string pointer. Upon successful
323 * conversion, the string pointer is updated to point to the first
324 * unrecognized character.
325 * @return Representation of the input floating-point number.
326 */
327static long double parse_hexadecimal(const char **sptr)
328{
329 assert(sptr != NULL && *sptr != NULL);
330
331 const int DEC_BASE = 10;
332 const int HEX_BASE = 16;
333 const char DECIMAL_POINT = '.';
334 const char EXPONENT_MARK = 'p';
335
336 const char *str = *sptr;
337 long double significand = 0;
338 long exponent = 0;
339
340 /* number of bits parsed so far */
341 int parsed_bits = 0;
342 bool after_decimal = false;
343
344 while (posix_isxdigit(*str) || (!after_decimal && *str == DECIMAL_POINT)) {
345 if (*str == DECIMAL_POINT) {
346 after_decimal = true;
347 str++;
348 continue;
349 }
350
351 if (parsed_bits == 0 && *str == '0') {
352 /* Nothing, just skip leading zeros. */
353 } else if (parsed_bits <= LDBL_MANT_DIG) {
354 significand = significand * HEX_BASE + hex_value(*str);
355 parsed_bits += 4;
356 } else {
357 exponent += 4;
358 }
359
360 if (after_decimal) {
361 exponent -= 4;
362 }
363
364 str++;
365 }
366
367 /* exponent */
368 if (tolower(*str) == EXPONENT_MARK) {
369 str++;
370
371 /* Returns MIN/MAX value on error, which is ok. */
372 long exp = strtol(str, (char **) &str, DEC_BASE);
373
374 if (exponent > 0 && exp > LONG_MAX - exponent) {
375 exponent = LONG_MAX;
376 } else if (exponent < 0 && exp < LONG_MIN - exponent) {
377 exponent = LONG_MIN;
378 } else {
379 exponent += exp;
380 }
381 }
382
383 *sptr = str;
384
385 /* Return multiplied by a power of two. */
386 return mul_pow2(significand, exponent);
387}
388
389/**
390 * Converts a string representation of a floating-point number to
391 * its native representation. Largely POSIX compliant, except for
392 * locale differences (always uses '.' at the moment) and rounding.
393 * Decimal strings are NOT guaranteed to be correctly rounded. This function
394 * should return a good enough approximation for most purposes but if you
395 * depend on a precise conversion, use hexadecimal representation.
396 * Hexadecimal strings are currently always rounded towards zero, regardless
397 * of the current rounding mode.
398 *
399 * @param nptr Input string.
400 * @param endptr If non-NULL, *endptr is set to the position of the first
401 * unrecognized character.
402 * @return An approximate representation of the input floating-point number.
403 */
404long double posix_strtold(const char *restrict nptr, char **restrict endptr)
405{
406 assert(nptr != NULL);
407
408 const int RADIX = '.';
409
410 /* minus sign */
411 bool negative = false;
412 /* current position in the string */
413 int i = 0;
414
415 /* skip whitespace */
416 while (isspace(nptr[i])) {
417 i++;
418 }
419
420 /* parse sign */
421 switch (nptr[i]) {
422 case '-':
423 negative = true;
424 /* fallthrough */
425 case '+':
426 i++;
427 }
428
429 /* check for NaN */
430 if (posix_strncasecmp(&nptr[i], "nan", 3) == 0) {
431 // FIXME: return NaN
432 // TODO: handle the parenthesised case
433
434 if (endptr != NULL) {
435 *endptr = (char *) nptr;
436 }
437 errno = EINVAL;
438 return 0;
439 }
440
441 /* check for Infinity */
442 if (posix_strncasecmp(&nptr[i], "inf", 3) == 0) {
443 i += 3;
444 if (posix_strncasecmp(&nptr[i], "inity", 5) == 0) {
445 i += 5;
446 }
447
448 if (endptr != NULL) {
449 *endptr = (char *) &nptr[i];
450 }
451 return negative ? -HUGE_VALL : +HUGE_VALL;
452 }
453
454 /* check for a hex number */
455 if (nptr[i] == '0' && tolower(nptr[i + 1]) == 'x' &&
456 (posix_isxdigit(nptr[i + 2]) ||
457 (nptr[i + 2] == RADIX && posix_isxdigit(nptr[i + 3])))) {
458 i += 2;
459
460 const char *ptr = &nptr[i];
461 /* this call sets errno if appropriate. */
462 long double result = parse_hexadecimal(&ptr);
463 if (endptr != NULL) {
464 *endptr = (char *) ptr;
465 }
466 return negative ? -result : result;
467 }
468
469 /* check for a decimal number */
470 if (isdigit(nptr[i]) || (nptr[i] == RADIX && isdigit(nptr[i + 1]))) {
471 const char *ptr = &nptr[i];
472 /* this call sets errno if appropriate. */
473 long double result = parse_decimal(&ptr);
474 if (endptr != NULL) {
475 *endptr = (char *) ptr;
476 }
477 return negative ? -result : result;
478 }
479
480 /* nothing to parse */
481 if (endptr != NULL) {
482 *endptr = (char *) nptr;
483 }
484 errno = EINVAL;
485 return 0;
486}
487
488/** @}
489 */
Note: See TracBrowser for help on using the repository browser.