Redefined parse_phone_number to take text, not cstring

This commit is contained in:
BLM 2015-07-22 11:57:44 -05:00
parent 7343039678
commit 89d2c9a241
2 changed files with 35 additions and 11 deletions

View File

@ -64,7 +64,16 @@ static void logInfo(const char* msg) {
* Utility functions
*/
static char* textToCString(const text* text) {
size_t len = VARSIZE(text) - VARHDRSZ;
char* str = (char*)palloc(len + 1);
memcpy(str, VARDATA(text), len);
str[len] = '\0';
return str;
}
//Internal function used by phone_number_in and parse_phone_number
//TODO: take a std::string to minimize copying?
ShortPhoneNumber* parsePhoneNumber(const char* number_str, const char* country) throw() {
try {
PhoneNumber number;
@ -132,15 +141,27 @@ extern "C" {
Datum
parse_phone_number(PG_FUNCTION_ARGS)
{
const char *number_str = PG_GETARG_CSTRING(0);
const char *country = PG_GETARG_CSTRING(1);
try {
const text* number_text = PG_GETARG_TEXT_P(0);
const text* country_text = PG_GETARG_TEXT_P(1);
char* number_str = textToCString(number_text);
char* country = textToCString(country_text);
ShortPhoneNumber* number = parsePhoneNumber(number_str, country);
//TODO: prevent leaks.
pfree(number_str);
pfree(country);
if(number) {
PG_RETURN_POINTER(number);
} else {
PG_RETURN_NULL();
}
} catch(std::bad_alloc e) {
reportOutOfMemory();
} catch(std::exception& e) {
reportGenericError(e);
}
}
PGDLLEXPORT PG_FUNCTION_INFO_V1(phone_number_out);

View File

@ -7,10 +7,6 @@ CREATE FUNCTION phone_number_in(cstring) RETURNS phone_number
LANGUAGE c IMMUTABLE STRICT
AS 'pg_libphonenumber', 'phone_number_in';
CREATE FUNCTION parse_phone_number(cstring, cstring) RETURNS phone_number
LANGUAGE c IMMUTABLE STRICT
AS 'pg_libphonenumber', 'parse_phone_number';
CREATE FUNCTION phone_number_out(phone_number) RETURNS cstring
LANGUAGE c IMMUTABLE STRICT
AS 'pg_libphonenumber', 'phone_number_out';
@ -34,4 +30,11 @@ CREATE TYPE phone_number (
STORAGE = plain
);
CREATE CAST (phone_number AS text)
WITH INOUT;
CREATE FUNCTION parse_phone_number(text, text) RETURNS phone_number
LANGUAGE c IMMUTABLE STRICT
AS 'pg_libphonenumber', 'parse_phone_number';
-- vim:syntax=sql