/*
 * Copyright (c) 2005 Sendmail, Inc. and its suppliers.
 *	All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 */

#include "sm/generic.h"
SM_RCSID("@(#)$Id: u32totxtwsuffix.c,v 1.1 2005/06/20 19:03:15 ca Exp $")

#include "sm/assert.h"
#include "sm/error.h"
#include "sm/sm-conf.h"
#include "sm/io.h"
#include "prtcnf.h"

/*
**  SM_U32TOTXTWSUFFIX -- Convert val into human readable format
**
**	Parameters:
**		val -- value
**		fp -- file for output
**
**	Returns:
**		usual sm_error code
**
**	Last code review:
**	Last code change:
*/

#define SM_PRT_UNIT(fp, value, unit) do {				\
	if ((value) != 0)						\
	{								\
		ret = sm_io_fprintf(fp, "%u%s", (value), (unit));	\
		if (sm_is_err(ret))					\
			return ret;					\
		empty = false;						\
	}								\
	} while (0)

#define SM_CNF_MAX_SUFF	16

sm_ret_T
sm_u32totxtwsuffix(sm_conf_definition_T const *def, uint32_t val, sm_file_T *fp)
{
	sm_ret_T ret;
	uint32_t m, values[SM_CNF_MAX_SUFF];
	int i, maxs;
	bool empty;
	sm_conf_definition_T const *suffix;

	SM_REQUIRE(def != NULL);

	empty = true;
	suffix = def->scd_contents;
	if (suffix == NULL)
		return sm_err_perm(EINVAL); /* ??? better error code??? */

	maxs = 0;
	values[0] = 0;
	while (val > 0 && suffix != NULL && suffix->scd_name != NULL
	       && maxs < SM_ARRAY_SIZE(values))
	{
		m = suffix->scd_size;
		if (m == 0)
			break;
		values[maxs++] = val % m;
		val /= m;
		++suffix;
	}
	if (maxs >= SM_ARRAY_SIZE(values))
		return sm_err_perm(SM_E_OVFLW_NS);
	for (i = maxs - 1; i >= 0; i--)
	{
		--suffix;
		SM_PRT_UNIT(fp, values[i], suffix->scd_name);
	}
	if (empty)
	{
		ret = sm_io_fprintf(fp, "%u%s", values[0], suffix->scd_name);
		if (sm_is_err(ret))
			return ret;
	}
	return SM_SUCCESS;
}


syntax highlighted by Code2HTML, v. 0.9.1