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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since e0f47f5 was df2e5514, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 7 years ago

Rename uspace/lib/posix/source to src, for consistency with other libraries.

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