summaryrefslogtreecommitdiff
path: root/src/math.c
blob: 90cea264c107251722ee91ceaf5374554c7295b0 (plain) (blame)
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
#include <s.h>

#include <assert.h>
#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

#include "math.h"



int
add_size(const size_t x, const size_t y, size_t *const out) {
	int rc = EOVERFLOW;

	const bool overflows = (SIZE_MAX - x) < y;
	if (overflows) {
		goto out;
	}

	*out = x + y;
	rc = 0;
out:
	return rc;
}

int
mul_size(const size_t x, const size_t y, size_t *const out) {
	int rc = EOVERFLOW;

	assert(x != 0U);
	assert(y != 0U);

	const bool overflows = x > (SIZE_MAX / y);
	if (overflows) {
		goto out;
	}

	*out = x * y;
	rc = 0;
out:
	return rc;
}

size_t
max_size(const size_t x, const size_t y) {
	return x > y ? x : y;
}