summaryrefslogtreecommitdiff
path: root/lib/ccan/tally/test/run-total.c
blob: d7d73e58a5dd290f9f6c6de3d7b57df405a6f367 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <ccan/tally/tally.c>
#include <ccan/tap/tap.h>

int main(void)
{
	struct tally *tally;
	ssize_t total, overflow;
	ssize_t min, max;

	max = (ssize_t)~(1ULL << (sizeof(max)*CHAR_BIT - 1));
	min = (ssize_t)(1ULL << (sizeof(max)*CHAR_BIT - 1));

	plan_tests(15);

	/* Simple case. */
	tally = tally_new(0);
	tally_add(tally, min);
	ok1(tally_total(tally, NULL) == min);
	ok1(tally_total(tally, &overflow) == min);
	ok1(overflow == -1);

	/* Underflow. */
	tally_add(tally, min);
	total = tally_total(tally, &overflow);
	ok1(overflow == -1);
	ok1((size_t)total == 0);
	ok1(tally_total(tally, NULL) == min);
	free(tally);

	/* Simple case. */
	tally = tally_new(0);
	tally_add(tally, max);
	ok1(tally_total(tally, NULL) == max);
	ok1(tally_total(tally, &overflow) == max);
	ok1(overflow == 0);

	/* Overflow into sign bit... */
	tally_add(tally, max);
	total = tally_total(tally, &overflow);
	ok1(overflow == 0);
	ok1((size_t)total == (size_t)-2);
	ok1(tally_total(tally, NULL) == max);

	/* Overflow into upper size_t. */
	tally_add(tally, max);
	total = tally_total(tally, &overflow);
	ok1(overflow == 1);
	if (sizeof(size_t) == 4)
		ok1((size_t)total == 0x7FFFFFFD);
	else if (sizeof(size_t) == 8)
		ok1((size_t)total == 0x7FFFFFFFFFFFFFFDULL);
	ok1(tally_total(tally, NULL) == max);
	free(tally);

	return exit_status();
}