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-2004, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
13 * $PostgreSQL: pgsql/src/backend/utils/adt/numutils.c,v 1.65 2004/08/29 05:06:49 momjian Exp $
15 *-------------------------------------------------------------------------
24 #include "utils/builtins.h"
27 #define INT_MAX (0x7FFFFFFFL)
30 #define INT_MIN (-INT_MAX-1)
33 #define SHRT_MAX (0x7FFF)
36 #define SHRT_MIN (-SHRT_MAX-1)
39 #define SCHAR_MAX (0x7F)
42 #define SCHAR_MIN (-SCHAR_MAX-1)
47 * pg_atoi: convert string to integer
49 * 'size' is the sizeof() the desired integral result (1, 2, or 4 bytes).
51 * allows any number of leading or trailing whitespace characters.
53 * 'c' is the character that terminates the input string (after any
54 * number of whitespace characters).
56 * Unlike plain atoi(), this will throw ereport() upon bad input format or
60 pg_atoi(char *s, int size, int c)
66 * Some versions of strtol treat the empty string as an error, but
67 * some seem not to. Make an explicit test to be sure we catch it.
70 elog(ERROR, "NULL pointer");
73 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
74 errmsg("invalid input syntax for integer: \"%s\"",
78 l = strtol(s, &badp, 10);
80 /* We made no progress parsing the string, so bail out */
83 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
84 errmsg("invalid input syntax for integer: \"%s\"",
88 * Skip any trailing whitespace; if anything but whitespace remains
89 * before the terminating character, bail out
91 while (*badp != c && isspace((unsigned char) *badp))
96 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
97 errmsg("invalid input syntax for integer: \"%s\"",
104 #if defined(HAVE_LONG_INT_64)
105 /* won't get ERANGE on these with 64-bit longs... */
106 || l < INT_MIN || l > INT_MAX
110 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
111 errmsg("value \"%s\" is out of range for type integer", s)));
114 if (errno == ERANGE || l < SHRT_MIN || l > SHRT_MAX)
116 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
117 errmsg("value \"%s\" is out of range for type shortint", s)));
120 if (errno == ERANGE || l < SCHAR_MIN || l > SCHAR_MAX)
122 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
123 errmsg("value \"%s\" is out of range for 8-bit integer", s)));
126 elog(ERROR, "unsupported result size: %d", size);
132 * pg_itoa - converts a short int to its string represention
135 * previously based on ~ingres/source/gutil/atoi.c
136 * now uses vendor's sprintf conversion
139 pg_itoa(int16 i, char *a)
141 sprintf(a, "%hd", (short) i);
145 * pg_ltoa - converts a long int to its string represention
148 * previously based on ~ingres/source/gutil/atoi.c
149 * now uses vendor's sprintf conversion
152 pg_ltoa(int32 l, char *a)