Initial Idea: Bounded Numbers

⚓ Rust    📅 2025-09-20    👤 surdeus    👁️ 8      

surdeus

Warning

This post was published 41 days ago. The information described in this article may have changed.

In a lot of my projects I argue in some way or another along the lines:

Those inputs are (per API specifications) guaranteed to be smaller than X, therefore summing two of them up can never overflow within u8.

Thinking about this problem more. I was wondering if we could move this argumentation from a purely meta level to the type level and let the compiler do the reasoning.

This is what I want to achieve with my project GitHub - blacktemplar/bounded-num.

It is in a very prototype state and the API is very minimal and documentation is missing fully.

The idea is that instead of:

let a: u8 = ...;
let b: u8 = ...;
let c: u8 = a + b;

one would do:

let a: BoundedNum<u8, P5, P100> = ...;
let b: BoundedNum<u8, P7, P150> = ...;
// type hint is unnecessary here, I just put it here for illustration,
// the compiler could figure it out just fine
let c: BoundedNum<u8, P12, P250> = a + b;

This has multiple benefits: One sees directly from the type the potential range of the value AND operators like Add can be implemented in a way that they never overflow. I consider the latter part the more important part given the motivation of this project. For me overflows can be quite dangerous, especially since they can happen silently in production (and are hard to debug if you cannot reproduce production with overflow checks turned on).

Just to illustrate how the compiler helps to avoid overflows, this would not compile

let a: BoundedNum<u8, P5, P100> = ...;
let b: BoundedNum<u8, P7, P156> = ...;
let c = a + b;

because a might be 100 and b might be 156 which would lead to an overflow of u8 when added.

It would be great to hear from others if this idea could be useful and if there are no other crates that achieve the same / a similar thing (I have tried searching for such crates but couldn't find one that satisfied me). Also, of course if someone wants to review my very early prototype code I am very happy to get feedback :slight_smile: (although at this stage a review of the idea is more important for me than the code).

1 post - 1 participant

Read full topic

🏷️ Rust_feed