/*
 * Convert human readable size to long int.
 *
 * Due to support for decimal values and case insensitivity of units
 * a function parse_int cannot be used.
 */
Datum
pg_size_bytes(PG_FUNCTION_ARGS)
{
	text	   *arg = PG_GETARG_TEXT_PP(0);
	char	   *str,
			   *strptr;
	char	   *buffer,
			   *bufptr;
	Numeric		num;
	int64		result;
	size_t		len;

	str = text_to_cstring(arg);
	strptr = str;

	/* Skip leading spaces */
	while (isspace((unsigned char) *strptr))
		strptr++;

	bufptr = strptr;
	for(;*strptr != '\0'; strptr++)
	{
		if (isdigit((unsigned char) *strptr) ||
			isspace((unsigned char) *strptr) ||
			*strptr == '.' || *strptr == '+' || *strptr == '-')
			continue;

		break;
	}

	/* don't allow empty string */
	if (bufptr == strptr)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("\"%s\" is not a number", str)));

	/* prepare buffer for parts of parsed input string */
	buffer = (char *) palloc(VARSIZE_ANY_EXHDR(arg) + 1);

	len = strptr - str;
	memcpy(buffer, str, len);
	buffer[len] = '\0';

	num = DatumGetNumeric(DirectFunctionCall3(numeric_in,
							CStringGetDatum(buffer), 0, -1));

	/* Handle possible unit */
	if (*strptr != '\0')
	{
		int			multiplier;
		Numeric		mul_num;
		const char *hintmsg;
		const char *unitstr;

		bufptr = buffer;

		/*
		 * unitstr holds complete string related to unit part. Used
		 * as part of error message. The parse_memory_unit is called
		 * with this value, when we detected invalid format, and we
		 * would to emit error result to ger hintstr. Elsewhere is
		 * used space trimmed buffer.
		 */
		unitstr = strptr;

		/* copy chars to buffer and stop on first space or end string */
		while (*strptr != '\0' && !isspace((unsigned char) *strptr))
			*bufptr++ = *strptr++;

		*bufptr = '\0';

		/* We allow ending spaces. Skip all spaces. */
		while (isspace((unsigned char) *strptr))
			strptr++;

		/* Use buffer as unitstr, when we didn't find more words. */
		if (*strptr == '\0')
			unitstr = buffer;

		/* Still, the unit can be invalid: too long, unknown */
		if (!parse_memory_unit(unitstr, &multiplier, &hintmsg))
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
					 errmsg("invalid unit: \"%s\"", unitstr),
					 errhint("%s", _(hintmsg))));

		/*
		 * Now, the multiplier is in KB units. It should be multiplied by 1024
		 * before usage.
		 */
		mul_num = DatumGetNumeric(DirectFunctionCall1(int8_numeric,
						    Int64GetDatum(multiplier * 1024L)));

		num = DatumGetNumeric(DirectFunctionCall2(numeric_mul,
							    NumericGetDatum(mul_num),
							    NumericGetDatum(num)));
	}

	result = DatumGetInt64(DirectFunctionCall1(numeric_int8, NumericGetDatum(num)));

	PG_RETURN_INT64(result);
}
