1 /*-------------------------------------------------------------------------
2 *
3 * numutils.c
4 * utility functions for I/O of built-in numeric types.
5 *
6 * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/utils/adt/numutils.c
12 *
13 *-------------------------------------------------------------------------
14 */
15 #include "postgres.h"
16
17 #include <math.h>
18 #include <limits.h>
19 #include <ctype.h>
20
21 #include "utils/builtins.h"
22
23 /*
24 * pg_atoi: convert string to integer
25 *
26 * allows any number of leading or trailing whitespace characters.
27 *
28 * 'size' is the sizeof() the desired integral result (1, 2, or 4 bytes).
29 *
30 * c, if not 0, is a terminator character that may appear after the
31 * integer (plus whitespace). If 0, the string must end after the integer.
32 *
33 * Unlike plain atoi(), this will throw ereport() upon bad input format or
34 * overflow.
35 */
36 int32
pg_atoi(const char * s,int size,int c)37 pg_atoi(const char *s, int size, int c)
38 {
39 long l;
40 char *badp;
41
42 /*
43 * Some versions of strtol treat the empty string as an error, but some
44 * seem not to. Make an explicit test to be sure we catch it.
45 */
46 if (s == NULL)
47 elog(ERROR, "NULL pointer");
48 if (*s == 0)
49 ereport(ERROR,
50 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
51 errmsg("invalid input syntax for integer: \"%s\"",
52 s)));
53
54 errno = 0;
55 l = strtol(s, &badp, 10);
56
57 /* We made no progress parsing the string, so bail out */
58 if (s == badp)
59 ereport(ERROR,
60 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
61 errmsg("invalid input syntax for integer: \"%s\"",
62 s)));
63
64 switch (size)
65 {
66 case sizeof(int32):
67 if (errno == ERANGE
68 #if defined(HAVE_LONG_INT_64)
69 /* won't get ERANGE on these with 64-bit longs... */
70 || l < INT_MIN || l > INT_MAX
71 #endif
72 )
73 ereport(ERROR,
74 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
75 errmsg("value \"%s\" is out of range for type integer", s)));
76 break;
77 case sizeof(int16):
78 if (errno == ERANGE || l < SHRT_MIN || l > SHRT_MAX)
79 ereport(ERROR,
80 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
81 errmsg("value \"%s\" is out of range for type smallint", s)));
82 break;
83 case sizeof(int8):
84 if (errno == ERANGE || l < SCHAR_MIN || l > SCHAR_MAX)
85 ereport(ERROR,
86 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
87 errmsg("value \"%s\" is out of range for 8-bit integer", s)));
88 break;
89 default:
90 elog(ERROR, "unsupported result size: %d", size);
91 }
92
93 /*
94 * Skip any trailing whitespace; if anything but whitespace remains before
95 * the terminating character, bail out
96 */
97 while (*badp && *badp != c && isspace((unsigned char) *badp))
98 badp++;
99
100 if (*badp && *badp != c)
101 ereport(ERROR,
102 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
103 errmsg("invalid input syntax for integer: \"%s\"",
104 s)));
105
106 return (int32) l;
107 }
108
109 /*
110 * pg_itoa: converts a signed 16-bit integer to its string representation
111 *
112 * Caller must ensure that 'a' points to enough memory to hold the result
113 * (at least 7 bytes, counting a leading sign and trailing NUL).
114 *
115 * It doesn't seem worth implementing this separately.
116 */
117 void
pg_itoa(int16 i,char * a)118 pg_itoa(int16 i, char *a)
119 {
120 pg_ltoa((int32) i, a);
121 }
122
123 /*
124 * pg_ltoa: converts a signed 32-bit integer to its string representation
125 *
126 * Caller must ensure that 'a' points to enough memory to hold the result
127 * (at least 12 bytes, counting a leading sign and trailing NUL).
128 */
129 void
pg_ltoa(int32 value,char * a)130 pg_ltoa(int32 value, char *a)
131 {
132 char *start = a;
133 bool neg = false;
134
135 /*
136 * Avoid problems with the most negative integer not being representable
137 * as a positive integer.
138 */
139 if (value == PG_INT32_MIN)
140 {
141 memcpy(a, "-2147483648", 12);
142 return;
143 }
144 else if (value < 0)
145 {
146 value = -value;
147 neg = true;
148 }
149
150 /* Compute the result string backwards. */
151 do
152 {
153 int32 remainder;
154 int32 oldval = value;
155
156 value /= 10;
157 remainder = oldval - value * 10;
158 *a++ = '0' + remainder;
159 } while (value != 0);
160
161 if (neg)
162 *a++ = '-';
163
164 /* Add trailing NUL byte, and back up 'a' to the last character. */
165 *a-- = '\0';
166
167 /* Reverse string. */
168 while (start < a)
169 {
170 char swap = *start;
171
172 *start++ = *a;
173 *a-- = swap;
174 }
175 }
176
177 /*
178 * pg_lltoa: convert a signed 64-bit integer to its string representation
179 *
180 * Caller must ensure that 'a' points to enough memory to hold the result
181 * (at least MAXINT8LEN+1 bytes, counting a leading sign and trailing NUL).
182 */
183 void
pg_lltoa(int64 value,char * a)184 pg_lltoa(int64 value, char *a)
185 {
186 char *start = a;
187 bool neg = false;
188
189 /*
190 * Avoid problems with the most negative integer not being representable
191 * as a positive integer.
192 */
193 if (value == PG_INT64_MIN)
194 {
195 memcpy(a, "-9223372036854775808", 21);
196 return;
197 }
198 else if (value < 0)
199 {
200 value = -value;
201 neg = true;
202 }
203
204 /* Compute the result string backwards. */
205 do
206 {
207 int64 remainder;
208 int64 oldval = value;
209
210 value /= 10;
211 remainder = oldval - value * 10;
212 *a++ = '0' + remainder;
213 } while (value != 0);
214
215 if (neg)
216 *a++ = '-';
217
218 /* Add trailing NUL byte, and back up 'a' to the last character. */
219 *a-- = '\0';
220
221 /* Reverse string. */
222 while (start < a)
223 {
224 char swap = *start;
225
226 *start++ = *a;
227 *a-- = swap;
228 }
229 }
230
231
232 /*
233 * pg_ltostr_zeropad
234 * Converts 'value' into a decimal string representation stored at 'str'.
235 * 'minwidth' specifies the minimum width of the result; any extra space
236 * is filled up by prefixing the number with zeros.
237 *
238 * Returns the ending address of the string result (the last character written
239 * plus 1). Note that no NUL terminator is written.
240 *
241 * The intended use-case for this function is to build strings that contain
242 * multiple individual numbers, for example:
243 *
244 * str = pg_ltostr_zeropad(str, hours, 2);
245 * *str++ = ':';
246 * str = pg_ltostr_zeropad(str, mins, 2);
247 * *str++ = ':';
248 * str = pg_ltostr_zeropad(str, secs, 2);
249 * *str = '\0';
250 *
251 * Note: Caller must ensure that 'str' points to enough memory to hold the
252 * result.
253 */
254 char *
pg_ltostr_zeropad(char * str,int32 value,int32 minwidth)255 pg_ltostr_zeropad(char *str, int32 value, int32 minwidth)
256 {
257 char *start = str;
258 char *end = &str[minwidth];
259 int32 num = value;
260
261 Assert(minwidth > 0);
262
263 /*
264 * Handle negative numbers in a special way. We can't just write a '-'
265 * prefix and reverse the sign as that would overflow for INT32_MIN.
266 */
267 if (num < 0)
268 {
269 *start++ = '-';
270 minwidth--;
271
272 /*
273 * Build the number starting at the last digit. Here remainder will
274 * be a negative number, so we must reverse the sign before adding '0'
275 * in order to get the correct ASCII digit.
276 */
277 while (minwidth--)
278 {
279 int32 oldval = num;
280 int32 remainder;
281
282 num /= 10;
283 remainder = oldval - num * 10;
284 start[minwidth] = '0' - remainder;
285 }
286 }
287 else
288 {
289 /* Build the number starting at the last digit */
290 while (minwidth--)
291 {
292 int32 oldval = num;
293 int32 remainder;
294
295 num /= 10;
296 remainder = oldval - num * 10;
297 start[minwidth] = '0' + remainder;
298 }
299 }
300
301 /*
302 * If minwidth was not high enough to fit the number then num won't have
303 * been divided down to zero. We punt the problem to pg_ltostr(), which
304 * will generate a correct answer in the minimum valid width.
305 */
306 if (num != 0)
307 return pg_ltostr(str, value);
308
309 /* Otherwise, return last output character + 1 */
310 return end;
311 }
312
313 /*
314 * pg_ltostr
315 * Converts 'value' into a decimal string representation stored at 'str'.
316 *
317 * Returns the ending address of the string result (the last character written
318 * plus 1). Note that no NUL terminator is written.
319 *
320 * The intended use-case for this function is to build strings that contain
321 * multiple individual numbers, for example:
322 *
323 * str = pg_ltostr(str, a);
324 * *str++ = ' ';
325 * str = pg_ltostr(str, b);
326 * *str = '\0';
327 *
328 * Note: Caller must ensure that 'str' points to enough memory to hold the
329 * result.
330 */
331 char *
pg_ltostr(char * str,int32 value)332 pg_ltostr(char *str, int32 value)
333 {
334 char *start;
335 char *end;
336
337 /*
338 * Handle negative numbers in a special way. We can't just write a '-'
339 * prefix and reverse the sign as that would overflow for INT32_MIN.
340 */
341 if (value < 0)
342 {
343 *str++ = '-';
344
345 /* Mark the position we must reverse the string from. */
346 start = str;
347
348 /* Compute the result string backwards. */
349 do
350 {
351 int32 oldval = value;
352 int32 remainder;
353
354 value /= 10;
355 remainder = oldval - value * 10;
356 /* As above, we expect remainder to be negative. */
357 *str++ = '0' - remainder;
358 } while (value != 0);
359 }
360 else
361 {
362 /* Mark the position we must reverse the string from. */
363 start = str;
364
365 /* Compute the result string backwards. */
366 do
367 {
368 int32 oldval = value;
369 int32 remainder;
370
371 value /= 10;
372 remainder = oldval - value * 10;
373 *str++ = '0' + remainder;
374 } while (value != 0);
375 }
376
377 /* Remember the end+1 and back up 'str' to the last character. */
378 end = str--;
379
380 /* Reverse string. */
381 while (start < str)
382 {
383 char swap = *start;
384
385 *start++ = *str;
386 *str-- = swap;
387 }
388
389 return end;
390 }
391
392 /*
393 * pg_strtouint64
394 * Converts 'str' into an unsigned 64-bit integer.
395 *
396 * This has the identical API to strtoul(3), except that it will handle
397 * 64-bit ints even where "long" is narrower than that.
398 *
399 * For the moment it seems sufficient to assume that the platform has
400 * such a function somewhere; let's not roll our own.
401 */
402 uint64
pg_strtouint64(const char * str,char ** endptr,int base)403 pg_strtouint64(const char *str, char **endptr, int base)
404 {
405 #ifdef _MSC_VER /* MSVC only */
406 return _strtoui64(str, endptr, base);
407 #elif defined(HAVE_STRTOULL) && SIZEOF_LONG < 8
408 return strtoull(str, endptr, base);
409 #else
410 return strtoul(str, endptr, base);
411 #endif
412 }
413