aboutsummaryrefslogtreecommitdiff
path: root/stdio-common/printf_fphex.c
blob: d657834ae49b011b4f2092251a424dcbe64fd789 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/* Print floating point number in hexadecimal notation according to ISO C99.
   Copyright (C) 1997-2023 Free Software Foundation, Inc.
   This file is part of the GNU C Library.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   <https://www.gnu.org/licenses/>.  */

#include <array_length.h>
#include <assert.h>
#include <ctype.h>
#include <ieee754.h>
#include <math.h>
#include <printf.h>
#include <libioP.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <wchar.h>
#include <_itoa.h>
#include <_itowa.h>
#include <locale/localeinfo.h>
#include <stdbool.h>
#include <rounding-mode.h>
#include <sys/param.h>
#include <printf_buffer.h>
#include <errno.h>

#if __HAVE_DISTINCT_FLOAT128
# include "ieee754_float128.h"
# include <ldbl-128/printf_fphex_macros.h>
# define PRINT_FPHEX_FLOAT128 \
   PRINT_FPHEX (_Float128, fpnum.flt128, ieee854_float128, \
		IEEE854_FLOAT128_BIAS)
#endif

static void
__printf_fphex_buffer (struct __printf_buffer *buf,
		       const char *decimal,
		       const struct printf_info *info,
		       const void *const *args)
{
  /* The floating-point value to output.  */
  union
    {
      union ieee754_double dbl;
      long double ldbl;
#if __HAVE_DISTINCT_FLOAT128
      _Float128 flt128;
#endif
    }
  fpnum;

  /* This function always uses LC_NUMERIC.  */
  assert (info->extra == 0);

  /* "NaN" or "Inf" for the special cases.  */
  const char *special = NULL;

  /* Buffer for the generated number string for the mantissa.  The
     maximal size for the mantissa is 128 bits.  */
  char numbuf[32];
  char *numstr;
  char *numend;
  int negative;

  /* The maximal exponent of two in decimal notation has 5 digits.  */
  char expbuf[5];
  char *expstr;
  int expnegative;
  int exponent;

  /* Non-zero is mantissa is zero.  */
  int zero_mantissa;

  /* The leading digit before the decimal point.  */
  char leading;

  /* Precision.  */
  int precision = info->prec;

  /* Width.  */
  int width = info->width;

#define PRINTF_FPHEX_FETCH(FLOAT, VAR)					\
  {									\
    (VAR) = *(const FLOAT *) args[0];					\
									\
    /* Check for special values: not a number or infinity.  */		\
    if (isnan (VAR))							\
      {									\
	if (isupper (info->spec))					\
	  special = "NAN";						\
	else								\
	  special = "nan";						\
      }									\
    else								\
      {									\
	if (isinf (VAR))						\
	  {								\
	    if (isupper (info->spec))					\
	      special = "INF";						\
	    else							\
	      special = "inf";						\
	  }								\
      }									\
    negative = signbit (VAR);						\
  }

  /* Fetch the argument value.	*/
#if __HAVE_DISTINCT_FLOAT128
  if (info->is_binary128)
    PRINTF_FPHEX_FETCH (_Float128, fpnum.flt128)
  else
#endif
#ifndef __NO_LONG_DOUBLE_MATH
  if (info->is_long_double && sizeof (long double) > sizeof (double))
    PRINTF_FPHEX_FETCH (long double, fpnum.ldbl)
  else
#endif
    PRINTF_FPHEX_FETCH (double, fpnum.dbl.d)

#undef PRINTF_FPHEX_FETCH

  if (special)
    {
      int width = info->width;

      if (negative || info->showsign || info->space)
	--width;
      width -= 3;

      if (!info->left)
	__printf_buffer_pad (buf, ' ', width);

      if (negative)
	__printf_buffer_putc (buf, '-');
      else if (info->showsign)
	__printf_buffer_putc (buf, '+');
      else if (info->space)
	__printf_buffer_putc (buf, ' ');

      __printf_buffer_puts (buf, special);

      if (info->left)
	__printf_buffer_pad (buf, ' ', width);

      return;
    }

#if __HAVE_DISTINCT_FLOAT128
  if (info->is_binary128)
    PRINT_FPHEX_FLOAT128;
  else
#endif
  if (info->is_long_double == 0 || sizeof (double) == sizeof (long double))
    {
      /* We have 52 bits of mantissa plus one implicit digit.  Since
	 52 bits are representable without rest using hexadecimal
	 digits we use only the implicit digits for the number before
	 the decimal point.  */
      unsigned long long int num;

      num = (((unsigned long long int) fpnum.dbl.ieee.mantissa0) << 32
	     | fpnum.dbl.ieee.mantissa1);

      zero_mantissa = num == 0;

      if (sizeof (unsigned long int) > 6)
	  numstr = _itoa_word (num, numbuf + sizeof numbuf, 16,
			       info->spec == 'A');
      else
	  numstr = _itoa (num, numbuf + sizeof numbuf, 16,
			  info->spec == 'A');

      /* Fill with zeroes.  */
      while (numstr > numbuf + (sizeof numbuf - 13))
	*--numstr = '0';

      leading = fpnum.dbl.ieee.exponent == 0 ? '0' : '1';

      exponent = fpnum.dbl.ieee.exponent;

      if (exponent == 0)
	{
	  if (zero_mantissa)
	    expnegative = 0;
	  else
	    {
	      /* This is a denormalized number.  */
	      expnegative = 1;
	      exponent = IEEE754_DOUBLE_BIAS - 1;
	    }
	}
      else if (exponent >= IEEE754_DOUBLE_BIAS)
	{
	  expnegative = 0;
	  exponent -= IEEE754_DOUBLE_BIAS;
	}
      else
	{
	  expnegative = 1;
	  exponent = -(exponent - IEEE754_DOUBLE_BIAS);
	}
    }
#ifdef PRINT_FPHEX_LONG_DOUBLE
  else
    PRINT_FPHEX_LONG_DOUBLE;
#endif

  /* Look for trailing zeroes.  */
  if (! zero_mantissa)
    {
      numend = array_end (numbuf);
      while (numend[-1] == '0')
	  --numend;

      bool do_round_away = false;

      if (precision != -1 && precision < numend - numstr)
	{
	  char last_digit = precision > 0 ? numstr[precision - 1] : leading;
	  char next_digit = numstr[precision];
	  int last_digit_value = (last_digit >= 'A' && last_digit <= 'F'
				  ? last_digit - 'A' + 10
				  : (last_digit >= 'a' && last_digit <= 'f'
				     ? last_digit - 'a' + 10
				     : last_digit - '0'));
	  int next_digit_value = (next_digit >= 'A' && next_digit <= 'F'
				  ? next_digit - 'A' + 10
				  : (next_digit >= 'a' && next_digit <= 'f'
				     ? next_digit - 'a' + 10
				     : next_digit - '0'));
	  bool more_bits = ((next_digit_value & 7) != 0
			    || precision + 1 < numend - numstr);
	  int rounding_mode = get_rounding_mode ();
	  do_round_away = round_away (negative, last_digit_value & 1,
				      next_digit_value >= 8, more_bits,
				      rounding_mode);
	}

      if (precision == -1)
	precision = numend - numstr;
      else if (do_round_away)
	{
	  /* Round up.  */
	  int cnt = precision;
	  while (--cnt >= 0)
	    {
	      char ch = numstr[cnt];
	      /* We assume that the digits and the letters are ordered
		 like in ASCII.  This is true for the rest of GNU, too.  */
	      if (ch == '9')
		{
		  numstr[cnt] = info->spec;	/* This is tricky,
						   think about it!  */
		  break;
		}
	      else if (tolower (ch) < 'f')
		{
		  ++numstr[cnt];
		  break;
		}
	      else
		numstr[cnt] = '0';
	    }
	  if (cnt < 0)
	    {
	      /* The mantissa so far was fff...f  Now increment the
		 leading digit.  Here it is again possible that we
		 get an overflow.  */
	      if (leading == '9')
		leading = info->spec;
	      else if (tolower (leading) < 'f')
		++leading;
	      else
		{
		  leading = '1';
		  if (expnegative)
		    {
		      exponent -= 4;
		      if (exponent <= 0)
			{
			  exponent = -exponent;
			  expnegative = 0;
			}
		    }
		  else
		    exponent += 4;
		}
	    }
	}
    }
  else
    {
      if (precision == -1)
	precision = 0;
      numend = numstr;
    }

  /* Now we can compute the exponent string.  */
  expstr = _itoa_word (exponent, expbuf + sizeof expbuf, 10, 0);

  /* Now we have all information to compute the size.  */
  width -= ((negative || info->showsign || info->space)
	    /* Sign.  */
	    + 2    + 1 + 0 + precision + 1 + 1
	    /* 0x    h   .   hhh         P   ExpoSign.  */
	    + ((expbuf + sizeof expbuf) - expstr));
	    /* Exponent.  */

  /* Count the decimal point.
     A special case when the mantissa or the precision is zero and the `#'
     is not given.  In this case we must not print the decimal point.  */
  if (precision > 0 || info->alt)
    --width;

  if (!info->left && info->pad != '0')
    __printf_buffer_pad (buf, ' ', width);

  if (negative)
    __printf_buffer_putc (buf, '-');
  else if (info->showsign)
    __printf_buffer_putc (buf, '+');
  else if (info->space)
    __printf_buffer_putc (buf, ' ');

  __printf_buffer_putc (buf, '0');
  if ('X' - 'A' == 'x' - 'a')
    __printf_buffer_putc (buf, info->spec + ('x' - 'a'));
  else
    __printf_buffer_putc (buf, info->spec == 'A' ? 'X' : 'x');

  if (!info->left && info->pad == '0')
    __printf_buffer_pad (buf, '0', width);

  __printf_buffer_putc (buf, leading);

  if (precision > 0 || info->alt)
    __printf_buffer_puts (buf, decimal);

  if (precision > 0)
    {
      ssize_t tofill = precision - (numend - numstr);
      __printf_buffer_write (buf, numstr, MIN (numend - numstr, precision));
      __printf_buffer_pad (buf, '0', tofill);
    }

  if ('P' - 'A' == 'p' - 'a')
    __printf_buffer_putc (buf, info->spec + ('p' - 'a'));
  else
    __printf_buffer_putc (buf, info->spec == 'A' ? 'P' : 'p');

  __printf_buffer_putc (buf, expnegative ? '-' : '+');

  __printf_buffer_write (buf, expstr, (expbuf + sizeof expbuf) - expstr);

  if (info->left && info->pad != '0')
    __printf_buffer_pad (buf, info->pad, width);
}

void
__printf_fphex_l_buffer (struct __printf_buffer *buf, locale_t loc,
			 const struct printf_info *info,
			 const void *const *args)
{
  __printf_fphex_buffer (buf, _nl_lookup (loc, LC_NUMERIC, DECIMAL_POINT),
			 info, args);
}


/* The wide buffer version is implemented by translating the output of
   the multibyte verison.  */

struct __printf_buffer_fphex_to_wide
{
  struct __printf_buffer base;
  wchar_t decimalwc;
  struct __wprintf_buffer *next;
  char untranslated[PRINTF_BUFFER_SIZE_DIGITS];
};

/* Translate to wide characters, rewriting "." to the actual decimal
   point.  */
void
__printf_buffer_flush_fphex_to_wide (struct __printf_buffer_fphex_to_wide *buf)
{
  /* No need to adjust buf->base.written, only buf->next->written matters.  */
  for (char *p = buf->untranslated; p < buf->base.write_ptr; ++p)
    {
      /* wchar_t overlaps with char in the ASCII range.  */
      wchar_t ch = *p;
      if (ch == L'.')
	ch = buf->decimalwc;
      __wprintf_buffer_putc (buf->next, ch);
    }

  if (!__wprintf_buffer_has_failed (buf->next))
    buf->base.write_ptr = buf->untranslated;
  else
    __printf_buffer_mark_failed (&buf->base);
}

void
__wprintf_fphex_l_buffer (struct __wprintf_buffer *next, locale_t loc,
			  const struct printf_info *info,
			  const void *const *args)
{
  struct __printf_buffer_fphex_to_wide buf;
  __printf_buffer_init (&buf.base, buf.untranslated, sizeof (buf.untranslated),
			__printf_buffer_mode_fphex_to_wide);
  buf.decimalwc = _nl_lookup_word (loc, LC_NUMERIC,
				   _NL_NUMERIC_DECIMAL_POINT_WC);
  buf.next = next;
  __printf_fphex_buffer (&buf.base, ".", info, args);
  if (__printf_buffer_has_failed (&buf.base))
    {
      __wprintf_buffer_mark_failed (buf.next);
      return;
    }
  __printf_buffer_flush_fphex_to_wide (&buf);
}