/*
 * Copyright (c) 2002, 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: fgetint.c,v 1.7 2006/07/14 14:42:25 ca Exp $")
#include "sm/error.h"
#include "sm/types.h"
#include "sm/io.h"
#include "sm/assert.h"

/*
**  SM_IO_FGETUINT32 -- read an 32bit integer from a file
**
**	Parameters:
**		fp -- the file pointer for the buffer to be read from
**		n -- (pointer to) int to be read out of the file
**
**	Returns:
**		usual sm_error code
*/

sm_ret_T
sm_io_fgetuint32(sm_file_T *fp, uint32_t *n)
{
	sm_ret_T ret;
	uchar buf[sizeof(uint32_t)];

	SM_IS_FP(fp);
	SM_REQUIRE(n != NULL);
	*n = 0;
	if (f_r(*fp) >= (int) sizeof(uint32_t))
	{
		*n = * ((uint32_t *) f_p(*fp));
		f_r(*fp) -= sizeof(uint32_t);
		f_p(*fp) += sizeof(uint32_t);
		return SM_SUCCESS;
	}

	/* not enough data in buffer: use getc() */
	buf[0] = sm_getc(fp);
	if (sm_is_err(ret = buf[0]))
		goto error;
	buf[1] = sm_getc(fp);
	if (sm_is_err(ret = buf[1]))
		goto error;
	buf[2] = sm_getc(fp);
	if (sm_is_err(ret = buf[2]))
		goto error;
	buf[3] = sm_getc(fp);
	if (sm_is_err(ret = buf[3]))
		goto error;
	*n = * ((uint32_t *) buf);

	return SM_SUCCESS;

  error:
	if (ret == SM_IO_EOF)
		return sm_error_perm(SM_EM_RECCOM, EIO);
	return ret;
}


syntax highlighted by Code2HTML, v. 0.9.1