1
/*-------------------------------------------------------------------------
4
* utility functions for I/O of built-in numeric types.
6
* integer: pg_atoi, pg_itoa, pg_ltoa
8
* Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
9
* Portions Copyright (c) 1994, Regents of the University of California
15
*-------------------------------------------------------------------------
23
#include "utils/builtins.h"
26
* pg_atoi: convert string to integer
28
* allows any number of leading or trailing whitespace characters.
30
* 'size' is the sizeof() the desired integral result (1, 2, or 4 bytes).
32
* c, if not 0, is a terminator character that may appear after the
33
* integer (plus whitespace). If 0, the string must end after the integer.
35
* Unlike plain atoi(), this will throw ereport() upon bad input format or
39
pg_atoi(char *s, int size, int c)
45
* Some versions of strtol treat the empty string as an error, but some
46
* seem not to. Make an explicit test to be sure we catch it.
49
elog(ERROR, "NULL pointer");
52
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
53
errmsg("invalid input syntax for integer: \"%s\"",
57
l = strtol(s, &badp, 10);
59
/* We made no progress parsing the string, so bail out */
62
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
63
errmsg("invalid input syntax for integer: \"%s\"",
70
#if defined(HAVE_LONG_INT_64)
71
/* won't get ERANGE on these with 64-bit longs... */
72
|| l < INT_MIN || l > INT_MAX
76
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
77
errmsg("value \"%s\" is out of range for type integer", s)));
80
if (errno == ERANGE || l < SHRT_MIN || l > SHRT_MAX)
82
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
83
errmsg("value \"%s\" is out of range for type smallint", s)));
86
if (errno == ERANGE || l < SCHAR_MIN || l > SCHAR_MAX)
88
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
89
errmsg("value \"%s\" is out of range for 8-bit integer", s)));
92
elog(ERROR, "unsupported result size: %d", size);
96
* Skip any trailing whitespace; if anything but whitespace remains before
97
* the terminating character, bail out
99
while (*badp && *badp != c && isspace((unsigned char) *badp))
102
if (*badp && *badp != c)
104
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
105
errmsg("invalid input syntax for integer: \"%s\"",
112
* pg_itoa - converts a short int to its string represention
115
* previously based on ~ingres/source/gutil/atoi.c
116
* now uses vendor's sprintf conversion
119
pg_itoa(int16 i, char *a)
121
sprintf(a, "%hd", (short) i);
125
* pg_ltoa - converts a long int to its string represention
128
* previously based on ~ingres/source/gutil/atoi.c
129
* now uses vendor's sprintf conversion
132
pg_ltoa(int32 l, char *a)