Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Add support for Rocket forms #445

Merged
merged 6 commits into from
Nov 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ bytes = { default-features = false, optional = true, version = "1.0" }
diesel = { default-features = false, features = ["postgres"], optional = true, version = "1.4" }
num-traits = { default-features = false, features = ["i128"], version = "0.2" }
postgres = { default-features = false, optional = true, version = "0.19" }
rocket = { default-features = false, optional = true, version = "0.5.0-rc.1" }
serde = { default-features = false, optional = true, version = "1.0" }
serde_json = { default-features = false, optional = true, version = "1.0" }
tokio-postgres = { default-features = false, optional = true, version = "0.7" }
Expand All @@ -51,6 +52,7 @@ default = ["serde", "std"]
legacy-ops = []
maths = []
maths-nopanic = ["maths"]
rocket-traits = ["rocket"]
rust-fuzz = ["arbitrary"]
serde-arbitrary-precision = ["serde", "serde_json/arbitrary_precision"]
serde-bincode = ["serde-str"] # Backwards compatability
Expand Down
5 changes: 5 additions & 0 deletions Makefile.toml
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ dependencies = [
"test-maths",
"test-misc",
"test-db",
"test-rocket-traits",
"test-serde",
"test-macros"
]
Expand Down Expand Up @@ -186,6 +187,10 @@ args = ["test", "--workspace", "--tests", "--features=db-tokio-postgres", "db",
command = "cargo"
args = ["test", "--workspace", "--tests", "--features=db-diesel-postgres", "db", "--", "--skip", "generated"]

[tasks.test-rocket-traits]
command = "cargo"
args = ["test", "--workspace", "--features=rocket-traits"]

[tasks.test-serde-float]
command = "cargo"
args = ["test", "--workspace", "--tests", "--features=serde-float", "serde", "--", "--skip", "generated"]
Expand Down
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ assert_eq!(total.to_string(), "27.26");
* [db-diesel-postgres](#db-diesel-postgres)
* [legacy-ops](#legacy-ops)
* [maths](#maths)
* [rocket-traits](#rocket-traits)
* [rust-fuzz](#rust-fuzz)
* [serde-float](#serde-float)
* [serde-str](#serde-str)
Expand Down Expand Up @@ -117,6 +118,10 @@ Please note that `ln` and `log10` will panic on invalid input with `checked_ln`
to curb against this. When the `maths` feature was first developed the library would return `0` on invalid input. To re-enable this
non-panicking behavior, please use the feature: `maths-nopanic`.

### `rocket-traits`

Enable support for Rocket forms by implementing the `FromFormField` trait.

### `rust-fuzz`

Enable `rust-fuzz` support by implementing the `Arbitrary` trait.
Expand Down Expand Up @@ -164,4 +169,4 @@ Please refer to the [Build document](BUILD.md) for more information on building

This library maintains support for rust compiler versions at least one year old and only updates the minimum version if and
when required. The current minimum compiler version is [`1.46.0`](https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-1460-2020-08-27)
which was released on `2020-08-27`.
which was released on `2020-08-27`.
9 changes: 8 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
//! * [db-diesel-postgres](#db-diesel-postgres)
//! * [legacy-ops](#legacy-ops)
//! * [maths](#maths)
//! * [rocket-traits](#rocket-traits)
//! * [rust-fuzz](#rust-fuzz)
//! * [serde-float](#serde-float)
//! * [serde-str](#serde-str)
Expand Down Expand Up @@ -111,12 +112,16 @@
//!
//! The `maths` feature enables additional complex mathematical functions such as `pow`, `ln`, `enf`, `exp` etc.
//! Documentation detailing the additional functions can be found on the
//! [`MathematicalOps`](https://docs.rs/rust_decimal/latest/rust_decimal/trait.MathematicalOps.html) trait.
//! [`MathematicalOps`](https://docs.rs/rust_decimal/latest/rust_decimal/trait.MathematicalOps.html) trait.
//!
//! Please note that `ln` and `log10` will panic on invalid input with `checked_ln` and `checked_log10` the preferred functions
//! to curb against this. When the `maths` feature was first developed the library would return `0` on invalid input. To re-enable this
//! non-panicing behavior, please use the feature: `maths-nopanic`.
//!
//! ### `rocket-traits`
//!
//! Enable support for forms by implementing the `FromFormField` trait.
//!
//! ### `rust-fuzz`
//!
//! Enable `rust-fuzz` support by implementing the `Arbitrary` trait.
Expand Down Expand Up @@ -176,6 +181,8 @@ mod db;
mod fuzz;
#[cfg(feature = "maths")]
mod maths;
#[cfg(feature = "rocket-traits")]
mod rocket;
#[cfg(feature = "serde")]
mod serde;

Expand Down
12 changes: 12 additions & 0 deletions src/rocket.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use crate::Decimal;
use rocket::form::{self, FromFormField, ValueField};
use std::str::FromStr;

impl<'v> FromFormField<'v> for Decimal {
fn default() -> Option<Self> {
None
}
fn from_value(field: ValueField<'v>) -> form::Result<'v, Self> {
Decimal::from_str(field.value).map_err(|_| form::Error::validation("not a valid number").into())
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Newbie question: do you need to do anything to handle empty strings? Or is that handled by Rocket if you mark the Decimal as Option?

Copy link
Contributor Author

@Misterio77 Misterio77 Nov 20, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The latter.

If you require a Decimal and from_str (thus from_value) fails, the request also fails (similary to how other types can fail, such as ints). If you require an Option<Decimal>, values that fail from_value become a None.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops my mistake. I've implemented default, so when from_value (if running on lenient mode, which is the default one) fails it is called and returns Decimal::default(), which was not intended and could be misleading.

I'm gonna go ahead and remove that

}
}
23 changes: 23 additions & 0 deletions tests/decimal_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4304,6 +4304,29 @@ mod generated {
gen_test!(test_sub_111_111, "Sub_111_111.csv", checked_sub);
}

#[cfg(feature = "rocket-traits")]
mod rocket {
use crate::Decimal;
use rocket::form::{Form, FromForm};
use std::str::FromStr;

#[derive(FromForm)]
struct Example {
foo: Decimal,
bar: Decimal,
}

#[test]
fn it_can_parse_form() {
let parsed: Example = Form::parse("bar=0.12345678901234567890123456789&foo=-123456.78").unwrap();
assert_eq!(parsed.foo, Decimal::from_str("-123456.78").unwrap());
assert_eq!(
parsed.bar,
Decimal::from_str("0.12345678901234567890123456789").unwrap()
);
}
}

#[cfg(feature = "rust-fuzz")]
mod rust_fuzz {
use arbitrary::{Arbitrary, Unstructured};
Expand Down