Skip to content

Use C23 checked arithmetic library#157

Draft
MisterDA wants to merge 1 commit intotrunkfrom
c23-stdckdint.h
Draft

Use C23 checked arithmetic library#157
MisterDA wants to merge 1 commit intotrunkfrom
c23-stdckdint.h

Conversation

@MisterDA
Copy link
Owner

@MisterDA MisterDA commented Dec 15, 2025

C23 defines ckd_add, ckd_sub, and ckd_mul, which provide portable functions for checked arithmetic, in <stdckdint.h>.

Use the header-only jtckdint.h library from Justine Alexandra Roberts Tunney, ISC-licensed, to provide a polyfill for platforms where <stdckdint.h> isn't available. Currently at commit d4c68b9559acdcc18b73c9fa463edc6b9c569c9f.

The transformation to C files was applied by Coccinelle using the following semantic patch:

@@
expression a;
expression b;
expression res;
@@
- caml_uadd_overflow(a, b, res)
+ ckd_add(res, a, b)
@@
expression a;
expression b;
expression res;
@@
- caml_usub_overflow(a, b, res)
+ ckd_sub(res, a, b)
@@
expression a;
expression b;
expression res;
@@
- caml_umul_overflow(a, b, res)
+ ckd_mul(res, a, b)

I believe this improves the portability of the code, as compilers not exposing the __builtin_ functions did not benefit from optimized checked arithmetic, and jtckdint.h provides an efficient implementation.

C23 defines `ckd_add`, `ckd_sub`, and `ckd_mul`, which provide
portable functions for checked arithmetic, in `<stdckdint.h>`.

Use the header-only `jtckdint.h` library from Justine Alexandra
Roberts Tunney, ISC-licensed, to provide a polyfill for platforms
where this header isn't available. Currently at commit
d4c68b9559acdcc18b73c9fa463edc6b9c569c9f

- https://en.cppreference.com/w/c/header/stdckdint.html
- https://github.com/jart/jtckdint

The transformation to C files was applied by Coccinelle using the
following semantic patch:

     @@
     expression a;
     expression b;
     expression res;
     @@
     - caml_uadd_overflow(a, b, res)
     + ckd_add(res, a, b)
     @@
     expression a;
     expression b;
     expression res;
     @@
     - caml_usub_overflow(a, b, res)
     + ckd_sub(res, a, b)
     @@
     expression a;
     expression b;
     expression res;
     @@
     - caml_umul_overflow(a, b, res)
    + ckd_mul(res, a, b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant