Crates.io | floco |
lib.rs | floco |
version | 0.1.3 |
source | src |
created_at | 2024-01-30 04:25:25.2618 |
updated_at | 2024-09-07 01:58:18.960463 |
description | Floco validates floats against constraints. |
homepage | https://github.com/RileyLeff/floco |
repository | https://github.com/RileyLeff/floco |
max_upload_size | |
id | 1119816 |
size | 36,188 |
Floco validates floats against user-defined constraints.
use floco::{Floco, Constrained};
// We want to represent a value as f64, but we don't want to allow:
// - values below 5.0f64
// - values above 7.2f64
// We define an empty struct.
// This won't contain data, but will contain validation criteria in its impl.
struct Foo;
// The Constrained trait defines the above constraints, an error type, and a default value.
impl Constrained<f64> for Foo {
type Error = &'static str;
fn is_valid(value: f64) -> bool {
value >= 5.0f64 && value <= 7.2f64
}
fn emit_error(_value: f64) -> Self::Error {
"yikes this is a bad foo"
}
// Optionally, you can set a custom default.
// Floco::<F, YourType>::Default will respect the default value impl for YourType.
fn get_default() -> f64 {
5.2f64
}
}
// Now we can use Foo to constrain a Floco
let this_will_be_ok = Floco::<f64, Foo>::try_new(6.8);
let this_will_be_err = Floco::<f64, Foo>::try_new(4.2);
This crate provides a struct that wraps a floating-point number alongside a PhantomData marker type. The marker type defines arbitrary validation conditions for the inner float. These validation conditions are invoked during construction, conversion, and deserialization.
The marker type also provides an Error type and an optional default value (defaults to zero).
Floco is no_std compatible by default, but has optional support for the standard library behind a feature flag. This doesn't add any functionality, just changes math ops from libm to std and changes the errors from thiserror-core to thiserror. Floco should compile on stable if std is enabled, but will require the error_in_core feature for no_std builds.
Floco is compatible with any type that implements the float trait from the num_traits crate. TryFrom conversions are implemented from f32 and f64 for convenience.
Licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.