Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #[derive(Debug)]
- struct Error(String);
- trait ValidateInput {
- fn validate_input(&self, field: &str) -> Result<(), Error>; //New 'field'
- }
- // Method for ion validation
- fn validate_input_string(input: impl AsRef<str>, field: &str) -> Result<(), Error> {
- let input = input.as_ref();
- if input == "foo" {
- Err(Error(format!("Invalid string in field: '{}'", field)))
- }
- else {
- Ok(())
- }
- }
- macro_rules! stringify_replace_self {
- ($e: expr, $replacement: expr) => {{
- let s = stringify!($e);
- if !$replacement.is_empty() {
- s.replace("&self", $replacement)
- }
- else {
- s.replace("&self.", $replacement)
- }
- }}
- }
- macro_rules! fn_field {
- ($self_name: expr, $field: expr, $func: expr) => {
- $func($field, &stringify_replace_self!($field, $self_name))
- }
- }
- macro_rules! fn_index {
- ($self_name: expr, $field: expr, $index: expr, $func: expr) => {
- $func($field, &format!("{}[{}]", $self_name, $index))
- }
- }
- struct Input {
- foo: Bar
- }
- struct Bar {
- bar: Vec<String>
- }
- impl ValidateInput for String {
- fn validate_input(&self, field: &str) -> Result<(), Error> {
- validate_input_string(self, field)
- }
- }
- impl<S: ValidateInput> ValidateInput for Vec<S> {
- fn validate_input(&self, field: &str) -> Result<(), Error> {
- self.iter()
- .enumerate()
- .map(|(index, i)| fn_index!(field, i, index, ValidateInput::validate_input))
- .collect::<Result<Vec<_>, Error>>()?;
- Ok(())
- }
- }
- // Derived from proc macro:
- impl ValidateInput for Input {
- fn validate_input(&self, field: &str) -> Result<(), Error> {
- // Add validation with: fn_field!(field, &self.foo, validate_input_string)?;
- fn_field!(field, &self.foo, ValidateInput::validate_input)?;
- Ok(())
- }
- }
- // Derived from proc macro:
- impl ValidateInput for Bar {
- fn validate_input(&self, field: &str) -> Result<(), Error> {
- fn_field!(field, &self.bar, ValidateInput::validate_input)?;
- Ok(())
- }
- }
- fn main() -> Result<(), Error> {
- let input = Input {
- foo: Bar{
- bar: vec![
- "bar".to_string(),
- "foo".to_string()
- ]
- }
- };
- input.validate_input("")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement