| Crates.io | rotary-add |
| lib.rs | rotary-add |
| version | 0.2.1 |
| created_at | 2024-03-16 21:11:39.587054+00 |
| updated_at | 2025-04-29 18:27:32.74092+00 |
| description | This crate adds a few simple methods to the three lowest unsigned integer types, u8, u16 and u32 to allow cyclical addition and subtraction around the same 0 to (limit - 1) range or from 1 to a limit |
| homepage | |
| repository | https://github.com/neilg63/rotary-add |
| max_upload_size | |
| id | 1175979 |
| size | 10,630 |
This library crate provides an extension trait, CycleAdd, for performing cyclical (modular) addition and subtraction with unsigned integer types (u8, u16, and u32). Unlike the default + and - operators, these operations never overflow below zero or beyond the defined modulus.mo
let first_number: u8 = 22;
let second_number: u8 = 6;
let result = first_number.cycle_add(second_number, 24);
// Result: 4 (22 + 6 wraps around at 24)
let first_number: u8 = 37;
let result = first_number.cycle_sub(78, 100);
// Result: 59 (37 - 78 wraps around at 100)
Many common series (e.g., months, weekdays) start from 1. Modular arithmetic typically assumes 0-based indexing, which can lead to unexpected results. The series_add, series_sub, and series_mod methods handle these conversions for you.
let sample_month_1: u8 = 11;
let limit = 12; // Months of the year
let result = sample_month_1.series_add(1, limit);
// Result: 12 (November + 1 = December)
let sample_month_2: u8 = 3;
let result = sample_month_2.series_sub(3, limit);
// Result: 12 (March - 3 = December)
let sample_month_value: u8 = 24; // 24th month
let result = sample_month_value.series_mod(limit);
// Result: 12 (24 wraps around to December)
Unlike the Ring360 crate, RotaryAdd focuses exclusively on extending core unsigned integer types. It is designed for use cases such as:
T.rotary_add(&T) and T.rotary_sub(&T) as they were functionally equivalent to T.wrapping_add(T) and T.wrapping_sub(T) in the Rust core library (but with the first parameter passed by reference).series_add, series_sub, and series_mod methods for 1-based series operations.