icu_ext.c
/*
 * Return a binary sort key corresponding to the string and
 * the given collation.
 */
Return a binary sort key corresponding to the string and
the given collation.
Return a binary sort key corresponding to the string and the given collation .
Datum
icu_sort_key_coll(PG_FUNCTION_ARGS)
{
	text *txt = PG_GETARG_TEXT_PP(0);
	const char *locname = text_to_cstring(PG_GETARG_TEXT_P(1));
	UCollator	*collator;
	UErrorCode	status = U_ZERO_ERROR;
	int32_t o_len = 1024;		
	int32_t ulen;
	UChar *ustring;
	bytea *output;
	ulen = icu_to_uchar(&ustring, VARDATA_ANY(txt), VARSIZE_ANY_EXHDR(txt));
 	collator = ucol_open(locname, &status);
	if (!collator)
		elog(ERROR, "failed to open collation");
	do
	{
		int32_t effective_len;
		output = (bytea*) palloc(o_len + VARHDRSZ);
		effective_len = ucol_getSortKey(collator,
										ustring,
										ulen,
										(uint8_t*)VARDATA(output),
										o_len);
		if (effective_len == 0)
		{
			ucol_close(collator);
			elog(ERROR, "ucol_getSortKey() failed: internal error");
		}
		if (effective_len > o_len)
		{
			pfree(output);
			output = NULL;
		}
		o_len = effective_len;
	} while (output == NULL);	
	ucol_close(collator);
	SET_VARSIZE(output, o_len + VARHDRSZ - 1);  
	PG_RETURN_BYTEA_P(output);
}
Datum icu_sort_key_coll ( PG_FUNCTION_ARGS ) { text * txt = PG_GETARG_TEXT_PP ( 0 ) ; const char * locname = text_to_cstring ( PG_GETARG_TEXT_P ( 1 ) ) ; UCollator * collator ; UErrorCode status = U_ZERO_ERROR ; int32_t o_len = 1024 ; int32_t ulen ; UChar * ustring ; bytea * output ; ulen = icu_to_uchar ( & ustring , VARDATA_ANY ( txt ) , VARSIZE_ANY_EXHDR ( txt ) ) ; collator = ucol_open ( locname , & status ) ; if ( ! collator ) elog ( ERROR , " " ) ; do { int32_t effective_len ; output = ( bytea * ) palloc ( o_len + VARHDRSZ ) ; effective_len = ucol_getSortKey ( collator , ustring , ulen , ( uint8_t * ) VARDATA ( output ) , o_len ) ; if ( effective_len == 0 ) { ucol_close ( collator ) ; elog ( ERROR , " " ) ; } if ( effective_len > o_len ) { pfree ( output ) ; output = NULL ; } o_len = effective_len ; } while ( output == NULL ) ; ucol_close ( collator ) ; SET_VARSIZE ( output , o_len + VARHDRSZ - 1 ) ; PG_RETURN_BYTEA_P ( output ) ; }
Return a binary sort key corresponding to the string and
 the given collation.
Return a binary sort key corresponding to the string and the given collation .
/* first attempt */ /* should loop at most once, if buffer too small */ /* -1 excludes the ending NUL byte */