source: mainline/uspace/lib/posix/src/stdlib/strtold.c@ 777832e

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

abs, labs, llabs.

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