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

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

abs, labs, llabs.

  • Property mode set to 100644
File size: 11.4 KB
RevLine 
[63fc519]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 */
[087c8798]32/** @file Backend for floating point conversions.
[63fc519]33 */
34
35#include "../internal/common.h"
[3e6a98c5]36#include "libc/stdbool.h"
[a3da2b2]37#include "posix/stdlib.h"
[63fc519]38
[e8d3c6f5]39#include <assert.h>
[a3da2b2]40#include "posix/ctype.h"
41#include "posix/stdint.h"
42#include "posix/strings.h"
[0d0b319]43
44#include <errno.h>
45
[a3da2b2]46#include "posix/limits.h"
[d43c117]47
[a3da2b2]48#include "posix/float.h"
[63fc519]49
[1d6dd2a]50#include "libc/str.h"
51
[63fc519]52#ifndef HUGE_VALL
[1433ecda]53#define HUGE_VALL (+1.0l / +0.0l)
[63fc519]54#endif
55
[d43c117]56/* If the constants are not defined, use double precision as default. */
57#ifndef LDBL_MANT_DIG
[1433ecda]58#define LDBL_MANT_DIG 53
[d43c117]59#endif
60#ifndef LDBL_MAX_EXP
[1433ecda]61#define LDBL_MAX_EXP 1024
[d43c117]62#endif
63#ifndef LDBL_MIN_EXP
[1433ecda]64#define LDBL_MIN_EXP (-1021)
[d43c117]65#endif
66#ifndef LDBL_DIG
[1433ecda]67#define LDBL_DIG 15
[d43c117]68#endif
69#ifndef LDBL_MIN
[1433ecda]70#define LDBL_MIN 2.2250738585072014E-308
[d43c117]71#endif
[63fc519]72
[d43c117]73/* power functions ************************************************************/
[63fc519]74
[d43c117]75#if LDBL_MAX_EXP >= 16384
76const int MAX_POW5 = 12;
77#else
78const int MAX_POW5 = 8;
79#endif
[63fc519]80
81/* The value at index i is approximately 5**(2**i). */
[d43c117]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
[63fc519]98};
99
[d43c117]100#if LDBL_MAX_EXP >= 16384
101const int MAX_POW2 = 15;
102#else
103const int MAX_POW2 = 9;
104#endif
105
[63fc519]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,
[d43c117]118#if LDBL_MAX_EXP >= 16384
[63fc519]119 0x1P1024l,
120 0x1P2048l,
121 0x1P4096l,
[d43c117]122 0x1P8192l,
123#endif
[63fc519]124};
125
126/**
127 * Multiplies a number by a power of five.
[d43c117]128 * The result may be inexact and may not be the best possible approximation.
[63fc519]129 *
[d43c117]130 * @param mant Number to be multiplied.
131 * @param exp Base 5 exponent.
132 * @return mant multiplied by 5**exp
[63fc519]133 */
[d43c117]134static long double mul_pow5(long double mant, int exp)
[63fc519]135{
[d43c117]136 if (mant == 0.0l || mant == HUGE_VALL) {
137 return mant;
[63fc519]138 }
[a35b458]139
[d43c117]140 if (abs(exp) >> (MAX_POW5 + 1) != 0) {
141 /* Too large exponent. */
[63fc519]142 errno = ERANGE;
[d43c117]143 return exp < 0 ? LDBL_MIN : HUGE_VALL;
[63fc519]144 }
[a35b458]145
[d43c117]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;
[63fc519]155 errno = ERANGE;
156 break;
157 }
158 }
159 }
160 } else {
[d43c117]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. */
[63fc519]167 errno = ERANGE;
168 break;
169 }
170 }
171 }
172 }
[a35b458]173
[d43c117]174 return mant;
[63fc519]175}
176
177/**
[d43c117]178 * Multiplies a number by a power of two. This is always exact.
[63fc519]179 *
[d43c117]180 * @param mant Number to be multiplied.
181 * @param exp Base 2 exponent.
182 * @return mant multiplied by 2**exp.
[63fc519]183 */
[d43c117]184static long double mul_pow2(long double mant, int exp)
[63fc519]185{
[d43c117]186 if (mant == 0.0l || mant == HUGE_VALL) {
187 return mant;
[63fc519]188 }
[a35b458]189
[d43c117]190 if (exp > LDBL_MAX_EXP || exp < LDBL_MIN_EXP) {
[63fc519]191 errno = ERANGE;
[d43c117]192 return exp < 0 ? LDBL_MIN : HUGE_VALL;
[63fc519]193 }
[a35b458]194
[d43c117]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;
[63fc519]202 errno = ERANGE;
203 break;
204 }
205 }
206 }
207 } else {
[d43c117]208 for (int i = 0; i <= MAX_POW2; ++i) {
209 if (((exp >> i) & 1) != 0) {
210 mant *= pow2[i];
211 if (mant == HUGE_VALL) {
[63fc519]212 errno = ERANGE;
213 break;
214 }
215 }
216 }
217 }
[a35b458]218
[d43c117]219 return mant;
[63fc519]220}
221
[d43c117]222/* end power functions ********************************************************/
223
224
225
[087c8798]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).
[1b20da0]230 *
[087c8798]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 */
[63fc519]236static long double parse_decimal(const char **sptr)
237{
[d43c117]238 assert(sptr != NULL);
239 assert (*sptr != NULL);
[a35b458]240
[63fc519]241 const int DEC_BASE = 10;
242 const char DECIMAL_POINT = '.';
243 const char EXPONENT_MARK = 'e';
[a35b458]244
[d43c117]245 const char *str = *sptr;
246 long double significand = 0;
247 long exponent = 0;
[a35b458]248
[63fc519]249 /* number of digits parsed so far */
250 int parsed_digits = 0;
[d43c117]251 bool after_decimal = false;
[a35b458]252
[d43c117]253 while (isdigit(*str) || (!after_decimal && *str == DECIMAL_POINT)) {
254 if (*str == DECIMAL_POINT) {
255 after_decimal = true;
256 str++;
257 continue;
258 }
[a35b458]259
[d43c117]260 if (parsed_digits == 0 && *str == '0') {
[5ee9692]261 /* Nothing, just skip leading zeros. */
[d43c117]262 } else if (parsed_digits < LDBL_DIG) {
263 significand = significand * DEC_BASE + (*str - '0');
[63fc519]264 parsed_digits++;
265 } else {
266 exponent++;
267 }
[a35b458]268
[d43c117]269 if (after_decimal) {
270 /* Decrement exponent if we are parsing the fractional part. */
271 exponent--;
[63fc519]272 }
[a35b458]273
[d43c117]274 str++;
[63fc519]275 }
[a35b458]276
[63fc519]277 /* exponent */
[d43c117]278 if (tolower(*str) == EXPONENT_MARK) {
279 str++;
[a35b458]280
[d43c117]281 /* Returns MIN/MAX value on error, which is ok. */
282 long exp = strtol(str, (char **) &str, DEC_BASE);
[a35b458]283
[d43c117]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;
[63fc519]290 }
291 }
[a35b458]292
[d43c117]293 *sptr = str;
[a35b458]294
[d43c117]295 /* Return multiplied by a power of ten. */
296 return mul_pow2(mul_pow5(significand, exponent), exponent);
[63fc519]297}
298
[087c8798]299/**
300 * Derive a hexadecimal digit from its character representation.
[1b20da0]301 *
[087c8798]302 * @param ch Character representation of the hexadecimal digit.
303 * @return Digit value represented by an integer.
304 */
[5ee9692]305static inline int hex_value(char ch)
306{
[63fc519]307 if (ch <= '9') {
308 return ch - '0';
309 } else {
310 return 10 + tolower(ch) - 'a';
311 }
312}
313
[087c8798]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 */
[63fc519]325static long double parse_hexadecimal(const char **sptr)
326{
[d43c117]327 assert(sptr != NULL && *sptr != NULL);
[a35b458]328
[63fc519]329 const int DEC_BASE = 10;
330 const int HEX_BASE = 16;
331 const char DECIMAL_POINT = '.';
332 const char EXPONENT_MARK = 'p';
[a35b458]333
[63fc519]334 const char *str = *sptr;
[d43c117]335 long double significand = 0;
336 long exponent = 0;
[a35b458]337
[d43c117]338 /* number of bits parsed so far */
339 int parsed_bits = 0;
340 bool after_decimal = false;
[a35b458]341
[dbbbe75b]342 while (isxdigit(*str) || (!after_decimal && *str == DECIMAL_POINT)) {
[d43c117]343 if (*str == DECIMAL_POINT) {
344 after_decimal = true;
345 str++;
346 continue;
347 }
[a35b458]348
[d43c117]349 if (parsed_bits == 0 && *str == '0') {
[5ee9692]350 /* Nothing, just skip leading zeros. */
[d43c117]351 } else if (parsed_bits <= LDBL_MANT_DIG) {
352 significand = significand * HEX_BASE + hex_value(*str);
353 parsed_bits += 4;
[63fc519]354 } else {
355 exponent += 4;
356 }
[a35b458]357
[d43c117]358 if (after_decimal) {
359 exponent -= 4;
[63fc519]360 }
[a35b458]361
[d43c117]362 str++;
[63fc519]363 }
[a35b458]364
[63fc519]365 /* exponent */
[d43c117]366 if (tolower(*str) == EXPONENT_MARK) {
367 str++;
[a35b458]368
[d43c117]369 /* Returns MIN/MAX value on error, which is ok. */
370 long exp = strtol(str, (char **) &str, DEC_BASE);
[a35b458]371
[d43c117]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;
[63fc519]378 }
379 }
[a35b458]380
[d43c117]381 *sptr = str;
[a35b458]382
[d43c117]383 /* Return multiplied by a power of two. */
384 return mul_pow2(significand, exponent);
[63fc519]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
[4cf8ca6]399 * unrecognized character.
[63fc519]400 * @return An approximate representation of the input floating-point number.
401 */
[7f9df7b9]402long double strtold(const char *restrict nptr, char **restrict endptr)
[63fc519]403{
404 assert(nptr != NULL);
[a35b458]405
[63fc519]406 const int RADIX = '.';
[a35b458]407
[63fc519]408 /* minus sign */
409 bool negative = false;
410 /* current position in the string */
411 int i = 0;
[a35b458]412
[63fc519]413 /* skip whitespace */
414 while (isspace(nptr[i])) {
415 i++;
416 }
[a35b458]417
[63fc519]418 /* parse sign */
419 switch (nptr[i]) {
420 case '-':
421 negative = true;
[dc12262]422 /* Fallthrough */
[63fc519]423 case '+':
424 i++;
425 }
[a35b458]426
[63fc519]427 /* check for NaN */
[7f9df7b9]428 if (strncasecmp(&nptr[i], "nan", 3) == 0) {
[63fc519]429 // FIXME: return NaN
430 // TODO: handle the parenthesised case
[a35b458]431
[63fc519]432 if (endptr != NULL) {
[102a729]433 *endptr = (char *) nptr;
[63fc519]434 }
[102a729]435 errno = EINVAL;
436 return 0;
[63fc519]437 }
[a35b458]438
[63fc519]439 /* check for Infinity */
[7f9df7b9]440 if (strncasecmp(&nptr[i], "inf", 3) == 0) {
[63fc519]441 i += 3;
[7f9df7b9]442 if (strncasecmp(&nptr[i], "inity", 5) == 0) {
[63fc519]443 i += 5;
444 }
[a35b458]445
[63fc519]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' &&
[dbbbe75b]454 (isxdigit(nptr[i + 2]) ||
455 (nptr[i + 2] == RADIX && isxdigit(nptr[i + 3])))) {
[63fc519]456 i += 2;
[a35b458]457
[63fc519]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 }
[a35b458]466
[63fc519]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 }
[a35b458]477
[63fc519]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.