aboutsummaryrefslogtreecommitdiffstats
path: root/src/validators.rs
blob: 31344d8bc50cffe55a1b01d7d64351c4c15fa0b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/// Custom validators incoming data

use log::error;
use serde::de::{Deserializer, Error as DeserializerError, Unexpected};
use serde::ser::{Error as SerializerError, Serializer};
use serde::Deserialize;

pub mod validate_block {
    use super::*;

    const ERROR_MESSAGE: &str = "block cannot have an empty transaction list";

    pub fn deserialize<'de, D>(deserializer: D) -> Result<u8, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = u8::deserialize(deserializer)?;

        if value > 100 {
            error!("{}", ERROR_MESSAGE);

            return Err(DeserializerError::invalid_value(
                Unexpected::Unsigned(u64::from(value)),
                &ERROR_MESSAGE,
            ));
        }

        Ok(value)
    }

    #[allow(clippy::trivially_copy_pass_by_ref)]
    pub fn serialize<S>(value: &u8, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if *value > 100 {
            error!("{}", ERROR_MESSAGE);

            return Err(SerializerError::custom(ERROR_MESSAGE));
        }

        serializer.serialize_u8(*value)
    }
}