Giter VIP home page Giter VIP logo

sanitizer's People

Contributors

daksh14 avatar pratiktri avatar rabidfire avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

sumeetattree

sanitizer's Issues

Allow custom functions for sanitizing some struct fields

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.

Support for Option<T> and Vec<T> with T as a struct/enum

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. ๐Ÿ™‚

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.