/*
 * 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;
	Numeric		num;
	int64		result;
	char		savedchar;
	char	   *tmpptr;

	str = text_to_cstring(arg);
	strptr = str;

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

	/* The first non-space char to check for emptiness later */
	tmpptr = 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 (tmpptr == strptr)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("\"%s\" is not a number", str)));

	/*
	 * Save the first char after possible number with space chars after it
	 * and set end-of-string mark to get cstring for "numeric_in".
	 * If there is no unit part in the arg then savedchar is '\0'.
	 */
	savedchar = *strptr;
	*strptr = '\0';

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

	if (savedchar != '\0')
	{
		int			multiplier;
		Numeric		mul_num;
		const char *hintmsg;
		const char *unitstr;

		/*
		 * unitstr points to a complete string related to a unit part. It is
		 * used as a part of an error message. The parse_memory_unit is called
		 * with this value, even if invalid format is detected to get hintstr
		 * for the error message. Otherwise trimmed value is used.
		 */
		unitstr = strptr;
		*strptr = savedchar;  /* Restore value which was replaced by '\0' */

		while (*strptr != '\0' && !isspace((unsigned char) *strptr))
			strptr++;

		tmpptr = strptr;  /* The first space char to set there '\0' later */
		while (isspace((unsigned char) *strptr))
			strptr++;

		/* If there are only spaces after the unit part, trim them. */
		if (*strptr == '\0')
			*tmpptr = '\0';

		/* 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);
}
