/*
 * Copyright (c) 2002, 2004 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_IDSTR(id, "@(#)$Id: t-bf-0.c,v 1.8 2006/07/16 02:07:39 ca Exp $")
#include "sm/io.h"
#include "sm/bf.h"
#include "sm/stat.h"
#include "sm/test.h"
#include <stdio.h>

/*
**  Test buffered file I/O
*/

#define BFBSIZ	8192
#define FN	"bf1"

int
main(int argc, char *argv[])
{
	sm_ret_T res;
	size_t l;
	ssize_t n;
	sm_file_T *fp;
	int r, m;
	char *str = "foo\n";
	uchar buf[1024];
	uchar in[16];
	struct stat sb;

	sm_test_begin(argc, argv, "test bf I/O");
	(void) unlink(FN);
	res = sm_io_open(&SmBfIO, FN, SM_IO_RDWR, &fp, SM_IO_WHAT_FMODE, 0644,
			SM_IO_WHAT_BF_BUFSIZE, (size_t) BFBSIZ, SM_IO_WHAT_END);
	SM_TEST(SM_SUCCESS == res);
	SM_TEST(fp != NULL);
	l = 0;
	if (SM_SUCCESS == res)
	{
		res = sm_io_write(fp, (uchar *) str, (size_t)4, &n);
		SM_TEST(SM_SUCCESS == res);
		SM_TEST(4 == n);

		l += n;
		for (r = 0; r < sizeof(buf); r++)
			buf[r] = ' ' + (r % 96);

		do
		{
			r = stat(FN, &sb);
			if (l < BFBSIZ)
			{
				SM_TEST(r < 0);
				SM_TEST(ENOENT == errno);
			}

			res = sm_io_write(fp, buf, sizeof(buf), &n);
			SM_TEST(SM_SUCCESS == res);
			SM_TEST(sizeof(buf) == n);
			l += n;
		} while (l <= 2 * BFBSIZ + sizeof(buf));

		r = stat(FN, &sb);
		SM_TEST(0 == r);

		res = sm_io_setinfo(fp, SM_IO_WHAT_BF_COMMIT, NULL);
		SM_TEST(SM_SUCCESS == res);

		res = sm_io_close(fp, SM_IO_CF_NONE);
		SM_TEST(SM_SUCCESS == res);

		res = sm_io_open(SmStStdio, FN, SM_IO_RDONLY, &fp,
				SM_IO_WHAT_END);
		SM_TEST(SM_SUCCESS == res);
		SM_TEST(fp != NULL);
		if (SM_SUCCESS == res)
		{
			r = sm_io_getinfo(fp, SM_IO_IS_READABLE, &m);
			SM_TEST(r > 0);
			res = sm_io_read(fp, in, (size_t)4, &n);
			SM_TEST(SM_SUCCESS == res);
			SM_TEST(4 == n);
			SM_TEST(strncmp(str, (char *) in, 4) == 0);
			r = sm_io_getinfo(fp, SM_IO_WHAT_MODE, &m);
			SM_TEST(0 == r);
			SM_TEST(SM_IO_RDONLY == m);
			res = sm_io_close(fp, SM_IO_CF_NONE);
			SM_TEST(SM_SUCCESS == res);
		}
		SM_TEST(0 == unlink(FN));
	}
	return sm_test_end();
}


syntax highlighted by Code2HTML, v. 0.9.1