atlas_sanitize/
lib.rs

1//! A trait for sanitizing values and members of over the wire messages.
2
3#![no_std]
4#![cfg_attr(docsrs, feature(doc_cfg))]
5
6use core::{error::Error, fmt};
7
8#[derive(PartialEq, Debug, Eq, Clone)]
9pub enum SanitizeError {
10    IndexOutOfBounds,
11    ValueOutOfBounds,
12    InvalidValue,
13}
14
15impl Error for SanitizeError {}
16
17impl fmt::Display for SanitizeError {
18    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
19        match self {
20            SanitizeError::IndexOutOfBounds => f.write_str("index out of bounds"),
21            SanitizeError::ValueOutOfBounds => f.write_str("value out of bounds"),
22            SanitizeError::InvalidValue => f.write_str("invalid value"),
23        }
24    }
25}
26
27/// A trait for sanitizing values and members of over-the-wire messages.
28///
29/// Implementation should recursively descend through the data structure and
30/// sanitize all struct members and enum clauses. Sanitize excludes signature-
31/// verification checks, those are handled by another pass. Sanitize checks
32/// should include but are not limited to:
33///
34/// - All index values are in range.
35/// - All values are within their static max/min bounds.
36pub trait Sanitize {
37    fn sanitize(&self) -> Result<(), SanitizeError> {
38        Ok(())
39    }
40}
41
42impl<T: Sanitize> Sanitize for [T] {
43    fn sanitize(&self) -> Result<(), SanitizeError> {
44        for x in self.iter() {
45            x.sanitize()?;
46        }
47        Ok(())
48    }
49}