0

I'm looking for a way to implement a custom underflow. My code expects a range of 0-52 and if it goes outside this range it should overflow/underflow.

I've implemented a working simple solution for the overflow by doing value % 53 so if I'll give it a value over 52 it will still give me a value inside the range. For example, 53 = 0, 54 = 1, 55 = 2.

The underflow should work in the opposite way to the overflow, for example -1 = 52, -2 = 51, -3 = 50.

How can I implement that?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Adam
  • 25
  • 1
  • 4
  • It seems to me that you could define a new type to constrain the operations. `struct MyType(u8)` for example. The implementation could provide the APIs to add, subtract and to construct new instances. Something like `fn add(&self, other: &MyType) -> MyType` – Kendas Mar 03 '23 at 08:26

3 Answers3

2

You can use rem_euclid for this.

struct Limited(u8);

impl From<i32> for Limited {
    fn from(value: i32) -> Self {
        Self(value.rem_euclid(53) as u8) // guaranteed to fit in u8
    }
}
  
Holloway
  • 6,412
  • 1
  • 26
  • 33
0

Move the value to the positive numbers (by adding a suitable multiple of 53) before applying %53:

function custom_underflow(value):
    if value < 0:
        return (value + ((abs(value) / 53) + 1) * 53) % 53
    else:
        return value % 53
MrSmith42
  • 9,961
  • 6
  • 38
  • 49
-3

In this implementation, the value parameter is checked to see if it is less than 0. If it is, the function subtracts the absolute value of value from 52 and returns the result. Otherwise, if value is greater than or equal to 0, the function computes the remainder of value divided by 53 using the modulo operator % and returns the result.

function custom_underflow(value):
    if value < 0:
        return 52 - abs(value)
    else:
        return value % 53
mkrieger1
  • 19,194
  • 5
  • 54
  • 65