checked-rs
checked-rs
(referred to as checked
) is a Rust library that includes generic types providing semantics for clamped unsigned integers and a general-purpose type that associates a data type with a validation type. This library was extracted from a larger side-project to make it generally available and showcase Rust skills and knowledge.
Installation
The checked
library is compatible with rustc 1.79.0-nightly (a07f3eb43 2024-04-11)
but does not use any opt-in language features. To install checked-rs
, add the following to your Cargo.toml
:
[]
= "0.1.0"
Panicking vs Saturating
Behavior types are provide that configure the types to follow either panicking or saturating semantics when an underflow or overflow occurs. The clamped
attribute macro defaults to panicking behavior if it is not otherwise specified.
Usage
Hard Clamp (Direct Interaction)
use HardClamp;
use Saturating;
let mut clamp = new?;
assert_eq!;
clamp += 5;
assert_eq!;
clamp -= 15;
assert_eq!;
clamp += 20;
assert_eq!;
Hard Clamp Guard
use ;
use Saturating;
let mut clamp = new?;
assert_eq!;
let mut g = clamp.modify;
assert_eq!;
*g = 10;
assert_eq!;
g.commit?;
assert_eq!;
let mut g = clamp.modify;
assert_eq!;
*g = 15;
assert_eq!;
assert!;
assert_eq!;
Soft Clamp
use SoftClamp;
use Saturating;
let mut clamp = new;
assert_eq!;
assert!;
clamp += 5;
assert_eq!;
assert!;
clamp -= 15;
assert_eq!;
assert!;
*clamp = 30;
assert_eq!;
assert_eq!;
View
use ;
;
let mut item = with_validator;
assert_eq!;
assert!;
*item = 1;
assert_eq!;
assert!;
*item = -1;
assert_eq!;
assert!;
*item = 12;
assert_eq!;
assert!;
*item = 7;
assert_eq!;
let item = match item.try_unwrap ;
item.discard;
#[clamped(..)]
Attribute Macro
use clamped;
let a: Example = Default default;
let b: Example = 254.into;
let c = a + b;
assert!;
assert!;
assert!;
let d: Example = c - u8MAX;
assert!;
Features
- HardClamp: Provides clamped unsigned integers with hard limits.
- SoftClamp: Similar to HardClamp but allows invalid states.
- View: Combines a data type with a validation type.
- Guard: Allows temporary modifications with validation checks before committing changes.
- Attribute Macro:
#[clamped(..)]
for creating enums with clamping behavior.
Contribution
Contributions are welcome! To contribute, please open a PR or a GitHub issue.
License
This project is dual-licensed under the Apache 2.0 and MIT licenses.
Contact and Support
For support or further questions, please open a GitHub issue.