dashxhq / sanitizer Goto Github PK
View Code? Open in Web Editor NEWDead easy sanitizing for rust structs
License: MIT License
Dead easy sanitizing for rust structs
License: MIT License
Make use of macros and write unit tests in a modular fashion, follow DRY principles
Example
#[derive(Sanitize)]
struct Test {
#[sanitize(custom(sanitize_string))]
field: String
}
fn sanitize_string(field: String) -> String {
// sanitize field here
field
}
fn main() {
let instance: Test = Default::default();
instance.sanitize()?;
}
A custom function to sanitize a field will be called in the sanitize trait itself. The signature should match the type of the field. Rust will take care of the return type so we won't have to worry about that.
Hello maintainers! ๐ The crate seems to lack of support for Option<T>
, where T
is a struct or an enum and for Vec<T>
.
Currently, it's not possible to sanitize
a struct as a whole which relies on generic types other than Option<T>
, with T
as a primitive.
Here's an example:
use sanitizer::prelude::*;
#[derive(Sanitize, Debug, PartialEq)]
struct Person {
#[sanitize(trim)]
first_name: Option<String>,
// Optional nested struct should be sanitized if it's present
#[sanitize]
personal_details: Option<PersonalDetails>,
// Optional nested enum should be sanitized if it's present
#[sanitize]
job: Option<Job>,
// Vec should be sanitized if it's present.
#[sanitize]
pets: Vec<Pet>,
}
#[derive(Sanitize, Debug, PartialEq)]
struct PersonalDetails {
#[sanitize(trim)]
last_name: Option<String>,
#[sanitize(trim)]
address: Option<Option<String>>,
}
#[derive(Sanitize, Debug, PartialEq)]
enum Job {
Plumber,
Scientist,
#[sanitize(trim)]
Other(String),
}
#[derive(Sanitize, Debug, PartialEq)]
enum Pet {
Dog,
Cat,
#[sanitize(trim)]
Other(String)
}
#[test]
fn optional_nested_fields_are_sanitized_if_present_test() {
let mut instance = Person {
first_name: Some(String::from(" Gordon ")),
personal_details: Some(PersonalDetails {
last_name: Some(String::from(" Freeman ")),
address: Some(Some(String::from(" unknown "))),
}),
job: Some(Job::Other(String::from(" Resistance leader "))),
pets: vec![Pet::Other(String::from(" Headcrab "))],
};
let expected = Person {
first_name: Some(String::from("Gordon")),
personal_details: Some(PersonalDetails {
last_name: Some(String::from("Freeman")),
address: Some(Some(String::from("unknown"))),
}),
job: Some(Job::Other(String::from("Resistance leader"))),
pets: vec![Pet::Other(String::from("Headcrab"))],
};
instance.sanitize();
assert_eq!(instance, expected);
}
When running such code it fails with the following errors:
> cargo test --test example
Compiling sanitizer_macros v0.2.2 (/Users/owner/Projects/sanitizer/sanitizer-macros)
error[E0308]: mismatched types
--> sanitizer-macros/tests/example.rs:3:10
|
3 | #[derive(Sanitize, Debug, PartialEq)]
| ^^^^^^^^ expected enum `Job`, found enum `Option`
|
= note: expected mutable reference `&mut Job`
found mutable reference `&mut Option<Job>`
= note: this error originates in the derive macro `Sanitize` (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0308]: mismatched types
--> sanitizer-macros/tests/example.rs:3:10
|
3 | #[derive(Sanitize, Debug, PartialEq)]
| ^^^^^^^^ expected struct `PersonalDetails`, found enum `Option`
|
= note: expected mutable reference `&mut PersonalDetails`
found mutable reference `&mut Option<PersonalDetails>`
= note: this error originates in the derive macro `Sanitize` (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0107]: missing generics for struct `Vec`
--> sanitizer-macros/tests/example.rs:15:11
|
15 | pets: Vec<Pet>,
| ^^^ expected at least 1 generic argument
|
note: struct defined here, with at least 1 generic parameter: `T`
--> /Users/owner/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:398:12
|
398 | pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
| ^^^ -
help: add missing generic argument
|
15 | pets: Vec<T><Pet>,
| ~~~~~~
Some errors have detailed explanations: E0107, E0308.
For more information about an error, try `rustc --explain E0107`.
error: could not compile `sanitizer_macros` due to 3 previous errors
I came up with a simple workaround for now, but it's quite bothersome to handle for more complex structs. It also requires to drop #[sanitize]
proc macro to make it work.
Here's a rough idea, based on an example shared above:
fn optional_nested_fields_are_sanitized_manually_if_present_test() {
// (...)
instance.sanitize();
instance.personal_details.as_mut().map(sanitizer::Sanitize::sanitize);
instance.job.as_mut().map(sanitizer::Sanitize::sanitize);
instance.pets.iter_mut().map(sanitizer::Sanitize::sanitize).collect::<Vec<_>>();
assert_eq!(instance, expected);
}
Based on my initial research it seems that handling Option<T>
for structs/enums might be not that hard to implement.
However, I'm not so sure about Vec<T>
(and perhaps other iterables too).
Looking forward to hear your thoughts about it. ๐
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.