constraints.rs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. use codec::{Decode, Encode};
  2. #[cfg(feature = "std")]
  3. use serde::{Deserialize, Serialize};
  4. /// Length constraint for input validation
  5. #[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
  6. #[derive(Encode, Decode, Default, Clone, PartialEq, Eq, Copy)]
  7. pub struct InputValidationLengthConstraint {
  8. /// Minimum length
  9. pub min: u16,
  10. /// Difference between minimum length and max length.
  11. /// While having max would have been more direct, this
  12. /// way makes max < min unrepresentable semantically,
  13. /// which is safer.
  14. pub max_min_diff: u16,
  15. }
  16. impl InputValidationLengthConstraint {
  17. /// Helper for computing max
  18. pub fn max(self) -> u16 {
  19. self.min + self.max_min_diff
  20. }
  21. pub fn ensure_valid(
  22. self,
  23. len: usize,
  24. too_short_msg: &'static str,
  25. too_long_msg: &'static str,
  26. ) -> Result<(), &'static str> {
  27. let length = len as u16;
  28. if length < self.min {
  29. Err(too_short_msg)
  30. } else if length > self.max() {
  31. Err(too_long_msg)
  32. } else {
  33. Ok(())
  34. }
  35. }
  36. /// Create default input text constraints.
  37. pub fn new(min: u16, max_min_diff: u16) -> Self {
  38. InputValidationLengthConstraint { min, max_min_diff }
  39. }
  40. }