STDCKDINT(3)

πŸ“¦ version 15.1, in freebsd 14.5, freebsd 15.1, nixpkgs unstable

🌸 NAME 🌸

okay bestie, meet stdckdint β€” checked integer arithmetic. This is the STDCKDINT(3) page from the Library Functions Manual, and it's here to keep your integer math from silently going feral. πŸ’…

✨ SYNOPSIS ✨

#include <stdckdint.h>

bool
ckd_add(type1 *result, type2 a, type3 b);

bool
ckd_sub(type1 *result, type2 a, type3 b);

bool
ckd_mul(type1 *result, type2 a, type3 b);

πŸ¦‹ DESCRIPTION πŸ¦‹

The function-like macros ckd_add, ckd_sub, and ckd_mul perform checked integer addition, subtraction, and multiplication, respectively. Like, they're the group chat mods for your arithmetic. 😌

Here's the tea: if the result of adding, subtracting, or multiplying a and b β€” as if their respective types had infinite range β€” fits in type1, it gets stored in the location pointed to by result, and the macro evaluates to false. Slay, no overflow.

Otherwise, the macro evaluates to true, and the contents of the location pointed to by result is the result of the operation wrapped to the range of type1. So yeah, it tells you when things got weird, and gives you the wrapped value. πŸ’€

πŸ’– RETURN VALUES πŸ’–

The ckd_add, ckd_sub, and ckd_mul macros evaluate to true if the requested operation overflowed the result type and false otherwise. That's the whole vibe check. ✨

πŸŽ€ EXAMPLES πŸŽ€

#include <assert.h>
#include <limits.h>
#include <stdckdint.h>

int main(void)
{
        int result;

        assert(!ckd_add(&result, INT_MAX, 0));
        assert(result == INT_MAX);
        assert(ckd_add(&result, INT_MAX, 1));
        assert(result == INT_MIN);

        assert(!ckd_sub(&result, INT_MIN, 0));
        assert(result == INT_MIN);
        assert(ckd_sub(&result, INT_MIN, 1));
        assert(result == INT_MAX);

        assert(!ckd_mul(&result, INT_MAX / 2, 2));
        assert(result == INT_MAX - 1);
        assert(ckd_mul(&result, INT_MAX / 2 + 1, 2));
        assert(result == INT_MIN);

        return 0;
}

🌈 HISTORY 🌈

The ckd_add, ckd_sub, and ckd_mul macros were first introduced in FreeBSD 14.0. iconic behavior, honestly. πŸ‘‘

πŸ‘‘ AUTHORS πŸ‘‘

The ckd_add, ckd_sub, and ckd_mul macros and this manual page were written by Dag-Erling SmΓΈrgrav (<des@FreeBSD.org>). Give them their flowers. πŸ’


πŸ’– this cute little page is sourced from the Debian version of STDCKDINT(3), dated September 5, 2023 β€” okay bestie, go do checked math and stay safe! 🫢

πŸ“¦ where this page comes from