/*
 * 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_IDSTR(id, "@(#)$Id: t-mctx-0.c,v 1.2 2005/02/14 21:32:55 ca Exp $")

#include <stdio.h>
#include "sm/error.h"
#include "sm/debug.h"
#include "sm/mem.h"
#include "sm/sysexits.h"
#include "sm/io.h"
#include "sm/test.h"

static bool MemCheck = false;

static void
test(void)
{
	sm_ret_T ret;
	size_t s, i;
	void *p;
	sm_mctx_P sm_mctx;

	ret = sm_mctx_new(0, NULL, NULL, &sm_mctx);
	SM_TEST(ret == SM_SUCCESS);
	SM_TEST(sm_mctx != NULL);
	if (sm_mctx == NULL)
		goto error;
	if (MemCheck)
	{
		ret = sm_mctx_flags(sm_mctx, SM_MCTX_FL_CHK);
		SM_TEST(ret == SM_SUCCESS);
	}

	p = sm_ctxmalloc(sm_mctx, 0);
	SM_TEST(p != NULL);
	sm_ctxfree(sm_mctx, p);

	p = sm_ctxmalloc(sm_mctx, 10);
	SM_TEST(p != NULL);
	p = sm_ctxrealloc(sm_mctx, p, 20);
	SM_TEST(p != NULL);
	p = sm_ctxrealloc(sm_mctx, p, 30);
	SM_TEST(p != NULL);
	if (MemCheck)
	{
		sm_io_fprintf(smioout, "heap with 1 30-byte block allocated:\n");
		sm_ctxheap_report(sm_mctx, smioout, 3);
	}

	sm_ctxfree(sm_mctx, p);
	if (MemCheck)
	{
		sm_io_fprintf(smioout, "heap with 0 blocks allocated:\n");
		sm_ctxheap_report(sm_mctx, smioout, 3);
	}

	for (s = 10; s < 10000; s += 500)
	{
		p = sm_ctxzalloc(sm_mctx, s);
		SM_TEST(p != NULL);
		if (p != NULL)
		{
			char *ptr;

			ptr = p;
			for (i = 0; i < s; i++)
				SM_TEST(ptr[i] == '\0');
			sm_ctxfree(sm_mctx, p);
		}
	}
	ret = sm_mctx_destroy(sm_mctx);
	SM_TEST(ret == SM_SUCCESS);
	return;

  error:
	return;
}

static void
usage(const char *prg)
{
	sm_io_fprintf(smioerr, "usage: %s [options]\n", prg);
	exit(EX_USAGE);
}

int
main(int argc, char *argv[])
{
	char *prg;
	int c;

	prg = argv[0];
	while ((c = getopt(argc, argv, "H")) != -1)
	{
		switch (c)
		{
		  case 'H':
			MemCheck = true;
			break;
		  default:
			usage(argv[0]);
			return(EX_USAGE);
		}
	}
	sm_test_begin(argc, argv, "test memctx handling");
	test();
	return sm_test_end();
}


syntax highlighted by Code2HTML, v. 0.9.1