1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
//! # checked-rs
//!
//! > A library for encoding validation semantics into the type system.
//!
//! ## Overview
//!
//! The main components of this library is the the attribute macro `clamped` and the `View` struct _(plus the `Validator` trait)_.
//! Additionally, there are some traits and types such as `Behavior` and `ClampGuard` that either configure how overflow is handled or provide an alternative way to interact with the clamped types.
//!
//! ### `clamped` attribute macro
//!
//! The `clamped` attribute macro is used to create a specialized clamped type. The macro can be used on either field-less structs or enums with field-less variants.
//! Whe used on a struct, the struct will be transformed to have a single field that is the clamped value. When used on an enum, the enum will be transformed to have a variant for each state within the clamped range.
//!
//! > For the remainder of these docs, `int` will be used to refer to the integer type used for the clamped value.
//!
//! The macro requires the following positional arguments:
//! - `integer`: The integer type to use for the clamped value.
//!
//! The macro accepts the following arguments _(in any order)_:
//! - `behavior`: The behavior to use when the value overflows the limits. The default behavior is `Panicking`.
//! - `default`: The default value to use when the value is not provided. The default default value is the minimum value.
//! - `lower`: The lower limit of the clamped value. The default lower limit is the minimum value of the integer type.
//! - `upper`: The upper limit of the clamped value. The default upper limit is the maximum value of the integer type.
//!
//! The transformed type will have the following inherent implementations:
//! - `new(value: int) -> Self`: A constructor that creates a new clamped value from the provided value.
//! - `rand() -> Self`: A method that generates a random value within the clamped range.
//! - `validate(value: int) -> Result<int, Error>`: A method that validates the provided value and returns the value if it is within the clamped range.
//! - `modify<'a>(&'a mut self) -> Guard<'a>`: A method that returns a guard that can be used to stage _(potentially out-of-bounds)_ changes to the clamped value and either commit or discard the changes.
//!
//! The transformed type will have the following custom traits implemented:
//! - `InherentLimits<int>`: A trait that defines the minimum and maximum values of the clamped range.
//! - `InherentBehavior`: A trait that defines the behavior to use when the value overflows the limits.
//! - `ClampedInteger<int>`: A trait that defines the methods for converting to and from the underlying integer type.
//!
//! The transformed type will have the following standard traits implemented:
//! - `Default`, `Deref`, `AsRef`, `FromStr`, `PartialEq`, `PartialOrd`, `Eq`, `Ord`, `Add`, `AddAssign`, `Sub`, `SubAssign`, `Mul`, `MulAssign`, `Div`, `DivAssign`, `Rem`, `RemAssign`, `Neg`, `Not`, `BitAnd`, `BitAndAssign`, `BitOr`, `BitOrAssign`, `BitXor`, `BitXorAssign`.
//! - `From` implementations are provided to support conversions for the same machine integer types as the underlying integer type.
//!
//! > **NOTE**: The `std::cmp` and `std::ops` traits support `rhs` values of the clamped type or the underlying integer type.
//!
//! The transformed type will have the following external traits implemented:
//! - `serde::Serialize`, `serde::Deserialize`
//!
//! ### Struct Usage
//!
//! When used on a struct, you can optionally specify if it should be a `Soft` or `Hard` clamped type.
//!
//! #### Soft Clamps
//!
//! Soft clamps are clamped types that **_DO NOT_** enforce the limits on the value. Instead, the value is clamped when it is assigned via the `set` method. The method `set_unchecked` can be used to set the value without clamping. Alternatively, the method `get_mut` can be used to get a mutable reference to the inner value or the arithmetic traits can be used to perform operations on the value without clamping.
//!
//! Additionally, they will have the following extra standard traits implemented:
//! - `DerefMut`, `AsMut`
//!
//! #### Hard Clamps
//!
//! Hard clamps are clamped types that **_DO_** enforce the limits on the value. The value is clamped when it is created and any operations that would cause the value to overflow the limits will be handled according to the specified behavior.
//!
//! > **UNSAFE NOTE**: The `set_unchecked` and `as_mut` methods are available but marked unsafe because they can be used to assign an out-of-bounds value.
//!
//! ### Enum Usage
//!
//! Each variant of the enum will either represent a specific value within the overall clamped range, a hard clamped sub-range or a special variant that represents any value that is not explicitly handled. The variants will have corresponding methods that can be used to create a new instances of that variant or check if the contained value is that variant.
//!
//! > **NOTE**: The enum must account for all possible values within the clamped range. This can be done by using the `#[eq]` and `#[range]` attributes on the variants.
//! > The `#[other]` attribute can be used to account for any values that are not explicitly handled.
//!
//! #### Example
//!
//! ```ignore
//! use checked_rs::prelude::*;
//!
//! #[clamped(u16, default = 600, behavior = Saturating, lower = 100, upper = 600)]
//! #[derive(Debug, Clone, Copy)]
//! enum ResponseCode {
//! #[eq(100)]
//! Continue,
//! #[eq(200)]
//! Success,
//! #[eq(300)]
//! Redirection,
//! #[eq(400)]
//! BadRequest,
//! #[eq(404)]
//! NotFound,
//! #[range(500..=599)]
//! ServerError,
//! #[other]
//! Unknown,
//! #[eq(600)]
//! Invalid,
//! }
//!
//! ```
//!
//! ### `View`
//!
//! The `View` struct is a wrapper around a value that encodes it's validation logic into the wrapper. The `Validator` trait is used to define the validation logic for a `View`.
//! This wrapper is lightweight and can be used in place of the raw value via the `Deref` and/or `AsRef` traits.
//!
//! ```no_run
//! use checked_rs::prelude::*;
//!
//! #[derive(Clone, Copy)]
//! struct NotSeven;
//!
//! impl Validator for NotSeven {
//! type Item = i32;
//! type Error = anyhow::Error;
//!
//! fn validate(item: &Self::Item) -> Result<()> {
//! if *item == 7 {
//! Err(anyhow::anyhow!("Value must not be 7"))
//! } else {
//! Ok(())
//! }
//! }
//! }
//!
//! let mut item = View::with_validator(0, NotSeven);
//! let mut g = item.modify();
//!
//! *g = 7;
//! assert_eq!(*g, 7);
//! assert!(g.check().is_err());
//!
//! *g = 10;
//! assert!(g.commit().is_ok());
//!
//! // the guard is consumed by commit, so we can't check it again
//! // the `View`'s value should be updated
//! assert_eq!(&*item, &10);
//!
//! ```
use std::{
num,
ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Rem, Sub},
};
pub mod clamp;
pub mod guard;
pub mod view;
mod reexports {
#[doc(hidden)]
pub use anyhow::{anyhow, bail, ensure, format_err, Chain, Context, Error, Result};
#[doc(hidden)]
pub use serde;
}
pub mod prelude {
pub use crate::reexports::*;
pub use crate::clamp::*;
pub use crate::commit_or_bail;
pub use crate::view::*;
pub use crate::{Behavior, InherentBehavior, InherentLimits};
pub use checked_rs_macros::clamped;
}
pub trait Behavior: Copy + 'static {
// Binary Ops
fn add<T: Add<Output = T>>(lhs: T, rhs: T, min: T::Output, max: T::Output) -> T::Output
where
T::Output: Eq + Ord,
num::Saturating<T>: Add<Output = num::Saturating<T>>;
fn sub<T: Sub<Output = T>>(lhs: T, rhs: T, min: T::Output, max: T::Output) -> T::Output
where
T::Output: Eq + Ord,
num::Saturating<T>: Sub<Output = num::Saturating<T>>;
fn mul<T: Mul<Output = T>>(lhs: T, rhs: T, min: T::Output, max: T::Output) -> T::Output
where
T::Output: Eq + Ord,
num::Saturating<T>: Mul<Output = num::Saturating<T>>;
fn div<T: Div<Output = T>>(lhs: T, rhs: T, min: T::Output, max: T::Output) -> T::Output
where
T::Output: Eq + Ord,
num::Saturating<T>: Div<Output = num::Saturating<T>>;
fn rem<T: Rem<Output = T>>(lhs: T, rhs: T, min: T::Output, max: T::Output) -> T::Output
where
T::Output: Eq + Ord,
num::Saturating<T>: Rem<Output = num::Saturating<T>>;
fn bitand<T: BitAnd<Output = T>>(lhs: T, rhs: T, min: T::Output, max: T::Output) -> T::Output
where
T::Output: Eq + Ord,
num::Saturating<T>: BitAnd<Output = num::Saturating<T>>;
fn bitor<T: BitOr<Output = T>>(lhs: T, rhs: T, min: T::Output, max: T::Output) -> T::Output
where
T::Output: Eq + Ord,
num::Saturating<T>: BitOr<Output = num::Saturating<T>>;
fn bitxor<T: BitXor<Output = T>>(lhs: T, rhs: T, min: T::Output, max: T::Output) -> T::Output
where
T::Output: Eq + Ord,
num::Saturating<T>: BitXor<Output = num::Saturating<T>>;
// fn shl<T: Shl<Output = T>>(lhs: T, rhs: T, min: T::Output, max: T::Output) -> T::Output
// where
// T::Output: Eq + Ord,
// num::Saturating<T>: Shl<Output = num::Saturating<T>>;
// fn shr<T: Shr<Output = T>>(lhs: T, rhs: T, min: T::Output, max: T::Output) -> T::Output
// where
// T::Output: Eq + Ord,
// num::Saturating<T>: Shr<Output = num::Saturating<T>>;
// Unary Ops
fn neg<T: std::ops::Neg<Output = T>>(value: T, min: T::Output, max: T::Output) -> T::Output
where
T::Output: Eq + Ord,
num::Saturating<T>: std::ops::Neg<Output = num::Saturating<T>>;
fn not<T: std::ops::Not<Output = T>>(value: T, min: T::Output, max: T::Output) -> T::Output
where
T::Output: Eq + Ord,
num::Saturating<T>: std::ops::Not<Output = num::Saturating<T>>;
}
pub trait InherentLimits<T>: 'static {
const MIN: T;
const MAX: T;
}
pub trait InherentBehavior: 'static {
type Behavior: Behavior;
}
#[cfg(test)]
mod tests {
use crate::prelude::*;
#[clamped(u16, default = 600, behavior = Saturating, lower = 100, upper = 600)]
#[derive(Debug, Clone, Copy)]
enum ResponseCode {
#[eq(100)]
Continue,
#[eq(200)]
Success,
#[eq(300)]
Redirection,
#[eq(400)]
BadRequest,
#[eq(404)]
NotFound,
#[range(500..=599)]
ServerError,
#[other]
Unknown,
#[eq(600)]
Invalid,
}
#[test]
fn test_response_code() {
let mut code = ResponseCode::new_success();
assert!(code.is_success());
code += 100;
assert!(code.is_redirection());
code += u16::MAX;
assert!(code.is_invalid());
code -= 10;
assert!(code.is_server_error());
let mut g = code.modify();
*g = 111;
assert!(g.commit().is_ok());
assert!(code.is_unknown());
}
#[test]
fn test_from_str() -> Result<()> {
let code: ResponseCode = "200".parse()?;
assert!(code.is_success());
Ok(())
}
}