rialo_sanitize/
lib.rs

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