Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 8a3b80d

Browse files
committed
Make text <=> char conversion functions convert zero character to and
from an empty text string. This makes them consistent with the de facto behavior of type char's I/O conversion functions, and avoids generating text values with embedded nulls, which confuse many text operators.
1 parent a056f14 commit 8a3b80d

File tree

1 file changed

+33
-5
lines changed

1 file changed

+33
-5
lines changed

src/backend/utils/adt/char.c

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
*
1010
*
1111
* IDENTIFICATION
12-
* $Header: /cvsroot/pgsql/src/backend/utils/adt/char.c,v 1.30 2001/01/24 19:43:13 momjian Exp $
12+
* $Header: /cvsroot/pgsql/src/backend/utils/adt/char.c,v 1.31 2001/05/28 21:58:32 tgl Exp $
1313
*
1414
*-------------------------------------------------------------------------
1515
*/
@@ -23,6 +23,8 @@
2323

2424
/*
2525
* charin - converts "x" to 'x'
26+
*
27+
* Note that an empty input string will implicitly be converted to \0.
2628
*/
2729
Datum
2830
charin(PG_FUNCTION_ARGS)
@@ -34,6 +36,10 @@ charin(PG_FUNCTION_ARGS)
3436

3537
/*
3638
* charout - converts 'x' to "x"
39+
*
40+
* Note that if the char value is \0, the resulting string will appear
41+
* to be empty (null-terminated after zero characters). So this is the
42+
* inverse of the charin() function for such data.
3743
*/
3844
Datum
3945
charout(PG_FUNCTION_ARGS)
@@ -147,13 +153,24 @@ chardiv(PG_FUNCTION_ARGS)
147153
PG_RETURN_CHAR((int8) arg1 / (int8) arg2);
148154
}
149155

156+
150157
Datum
151158
text_char(PG_FUNCTION_ARGS)
152159
{
153160
text *arg1 = PG_GETARG_TEXT_P(0);
161+
char result;
162+
163+
/*
164+
* An empty input string is converted to \0 (for consistency with charin).
165+
* If the input is longer than one character, the excess data is silently
166+
* discarded.
167+
*/
168+
if (VARSIZE(arg1) > VARHDRSZ)
169+
result = *(VARDATA(arg1));
170+
else
171+
result = '\0';
154172

155-
/* XXX what if arg1 has length zero? */
156-
PG_RETURN_CHAR(*(VARDATA(arg1)));
173+
PG_RETURN_CHAR(result);
157174
}
158175

159176
Datum
@@ -162,8 +179,19 @@ char_text(PG_FUNCTION_ARGS)
162179
char arg1 = PG_GETARG_CHAR(0);
163180
text *result = palloc(VARHDRSZ + 1);
164181

165-
VARATT_SIZEP(result) = VARHDRSZ + 1;
166-
*(VARDATA(result)) = arg1;
182+
/*
183+
* Convert \0 to an empty string, for consistency with charout (and
184+
* because the text stuff doesn't like embedded nulls all that well).
185+
*/
186+
if (arg1 != '\0')
187+
{
188+
VARATT_SIZEP(result) = VARHDRSZ + 1;
189+
*(VARDATA(result)) = arg1;
190+
}
191+
else
192+
{
193+
VARATT_SIZEP(result) = VARHDRSZ;
194+
}
167195

168196
PG_RETURN_TEXT_P(result);
169197
}

0 commit comments

Comments
 (0)