/*
 * Copyright (c) 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_RCSID("@(#)$Id: t-bitstring.c,v 1.5 2004/12/26 04:08:54 ca Exp $")

#include "sm/heap.h"
#include "sm/bitstring.h"
#include "sm/test.h"

static int
testb1(uint s)
{
	uint i, j;
	int id;
	bitstr_t *ba;

	SM_TEST(s > 0);
	if (s == 0)
		return -1;
	ba = bit_alloc(s);
	SM_TEST(ba != NULL);
	if (ba == NULL)
		return -1;
	j = bitstr_size(s);
	SM_TEST(j >= s / 8);
	bit_nclear(ba, 0, s - 1);
	for (i = 0; i < s; i++)
		SM_TEST(!bit_test(ba,i));
	bit_nset(ba, 0, s - 1);
	for (i = 0; i < s; i++)
		SM_TEST(bit_test(ba,i));
	for (i = 0; i < s; i++)
	{
		bit_clear(ba, i);
		SM_TEST(!bit_test(ba,i));
		bit_set(ba, i);
		SM_TEST(bit_test(ba,i));
	}
	bit_nclear(ba, 0, s - 1);
	for (j = 2; j < s / 2; j++)
	{
		for (i = 0; i < s; i += j)
		{
			bit_set(ba, i);
			SM_TEST(bit_test(ba,i));
		}
	}
	bit_nset(ba, 0, s - 1);
	for (j = 2; j < s / 2; j++)
	{
		for (i = 0; i < s; i += j)
		{
			bit_clear(ba, i);
			SM_TEST(!bit_test(ba,i));
		}
	}
	bit_nset(ba, 0, s - 1);
	for (j = 2; j < s / 2; j++)
	{
		for (i = 0; i < s; i += j)
		{
			bit_set(ba, i);
			SM_TEST(bit_test(ba,i));
		}
	}
	bit_nclear(ba, 0, s - 1);
	for (j = 2; j < s / 2; j++)
	{
		for (i = 0; i < s; i += j)
		{
			bit_clear(ba, i);
			SM_TEST(!bit_test(ba,i));
		}
	}
	sm_free(ba);

	s = 2;
	ba = bit_alloc(s);
	SM_TEST(ba != NULL);
	if (ba == NULL)
		return -1;
	bit_set(ba, 0);
	bit_ffc(ba, s, &id);
	SM_TEST(id != -1);
	SM_TEST(id == 1);
	bit_ffs(ba, s, &id);
	SM_TEST(id != -1);
	SM_TEST(id == 0);

	bit_clear(ba, 0);
	bit_ffc(ba, s, &id);
	SM_TEST(id != -1);
	SM_TEST(id == 0);
	bit_ffs(ba, s, &id);
	SM_TEST(id == -1);

	bit_set(ba, 1);
	bit_ffc(ba, s, &id);
	SM_TEST(id != -1);
	SM_TEST(id == 0);
	bit_ffs(ba, s, &id);
	SM_TEST(id == 1);

	bit_set(ba, 0);
	bit_ffc(ba, s, &id);
	SM_TEST(id == -1);
	bit_ffs(ba, s, &id);
	SM_TEST(id == 0);

	return 0;
}

int
main(int argc, char *argv[])
{
	uint s;
	int r;

	s = 1000;
	while ((r = getopt(argc, argv, "s:")) != -1)
	{
		switch (r)
		{
		  case 's':
			s = strtoul(optarg, NULL, 0);
			break;
		  default:
			break;
		}
	}
	sm_test_begin(argc, argv, "test bitstring");
	testb1(s);
	return sm_test_end();
}


syntax highlighted by Code2HTML, v. 0.9.1