xref: /freebsd/share/man/man3/stdckdint.3 (revision 5c2bc3db201a4fe8d7911cf816bea104d5dc2138)
1.\"-
2.\" Copyright (c) 2023 Dag-Erling Smørgrav
3.\"
4.\" SPDX-License-Identifier: BSD-2-Clause
5.\"
6.Dd September 5, 2023
7.Dt STDCKDINT 3
8.Os
9.Sh NAME
10.Nm stdckdint
11.Nd checked integer arithmetic
12.Sh SYNOPSIS
13.In stdckdint.h
14.Ft bool
15.Fn ckd_add "type1 *result" "type2 a" "type3 b"
16.Ft bool
17.Fn ckd_sub "type1 *result" "type2 a" "type3 b"
18.Ft bool
19.Fn ckd_mul "type1 *result" "type2 a" "type3 b"
20.Sh DESCRIPTION
21The function-like macros
22.Nm ckd_add ,
23.Nm ckd_sub ,
24and
25.Nm ckd_mul
26perform checked integer addition, subtraction, and multiplication,
27respectively.
28If the result of adding, subtracting, or multiplying
29.Fa a
30and
31.Fa b
32as if their respective types had infinite range fits in
33.Ft type1 ,
34it is stored in the location pointed to by
35.Fa result
36and the macro evaluates to
37.Dv false .
38Otherwise, the macro evaluates to
39.Dv true
40and the contents of the location pointed to by
41.Fa result
42is the result of the operation wrapped to the range of
43.Ft type1 .
44.Sh RETURN VALUES
45The
46.Nm ckd_add ,
47.Nm ckd_sub ,
48and
49.Nm ckd_mul
50macros evaluate to
51.Dv true
52if the requested operation overflowed the result type and
53.Dv false
54otherwise.
55.Sh EXAMPLES
56.Bd -literal -offset indent
57#include <assert.h>
58#include <limits.h>
59#include <stdckdint.h>
60
61int main(void)
62{
63	int result;
64
65	assert(!ckd_add(&result, INT_MAX, 0));
66	assert(result == INT_MAX);
67	assert(ckd_add(&result, INT_MAX, 1));
68	assert(result == INT_MIN);
69
70	assert(!ckd_sub(&result, INT_MIN, 0));
71	assert(result == INT_MIN);
72	assert(ckd_sub(&result, INT_MIN, 1));
73	assert(result == INT_MAX);
74
75	assert(!ckd_mul(&result, INT_MAX / 2, 2));
76	assert(result == INT_MAX - 1);
77	assert(ckd_mul(&result, INT_MAX / 2 + 1, 2));
78	assert(result == INT_MIN);
79
80	return 0;
81}
82.Ed
83.\" .Sh STANDARDS
84.\" The
85.\" .Nm ckd_add ,
86.\" .Nm ckd_sub ,
87.\" and
88.\" .Nm ckd_mul
89.\" macros conform to
90.\" .St -isoC-23 .
91.Sh HISTORY
92The
93.Nm ckd_add ,
94.Nm ckd_sub ,
95and
96.Nm ckd_mul
97macros were first introduced in
98.Fx 14.0 .
99.Sh AUTHORS
100The
101.Nm ckd_add ,
102.Nm ckd_sub ,
103and
104.Nm ckd_mul
105macros and this manual page were written by
106.An Dag-Erling Sm\(/orgrav Aq Mt des@FreeBSD.org .
107