in_toto/models/
helpers.rs

1//! Supporting Functions and Types (VirtualTargetPath)
2use std::collections::HashMap;
3use std::fmt;
4use std::fmt::Debug;
5use std::str;
6
7use serde::de::{Deserialize, Deserializer, Error as DeserializeError};
8use serde::Serialize;
9
10use crate::crypto::{HashAlgorithm, HashValue};
11use crate::{Error, Result};
12
13/// Description of a target, used in verification.
14pub type TargetDescription = HashMap<HashAlgorithm, HashValue>;
15
16/// Wrapper for the Virtual path to a target.
17#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord, Serialize)]
18pub struct VirtualTargetPath(String);
19
20impl VirtualTargetPath {
21    /// Create a new `VirtualTargetPath` from a `String`.
22    ///
23    pub fn new(path: String) -> Result<Self> {
24        Ok(VirtualTargetPath(path))
25    }
26
27    /// The string value of the path.
28    pub fn value(&self) -> &str {
29        &self.0
30    }
31
32    /// Judge if this [`VirtualTargetPath`] matches the given pattern
33    pub(crate) fn matches(&self, pattern: &str) -> Result<bool> {
34        let matcher = glob::Pattern::new(pattern).map_err(|e| {
35            Error::IllegalArgument(format!(
36                "Pattern matcher creation failed: {}",
37                e
38            ))
39        })?;
40        Ok(matcher.matches(self.value()))
41    }
42}
43
44impl fmt::Display for VirtualTargetPath {
45    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
46        write!(f, "{}", self.0)
47    }
48}
49
50impl From<&str> for VirtualTargetPath {
51    fn from(s: &str) -> Self {
52        Self(s.to_string())
53    }
54}
55
56impl AsRef<str> for VirtualTargetPath {
57    fn as_ref(&self) -> &str {
58        &self.0
59    }
60}
61
62impl<'de> Deserialize<'de> for VirtualTargetPath {
63    fn deserialize<D: Deserializer<'de>>(
64        de: D,
65    ) -> ::std::result::Result<Self, D::Error> {
66        let s: String = Deserialize::deserialize(de)?;
67        VirtualTargetPath::new(s)
68            .map_err(|e| DeserializeError::custom(format!("{:?}", e)))
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use crate::models::VirtualTargetPath;
75
76    #[test]
77    fn serialize_virtual_target_path() {
78        let path = VirtualTargetPath::from("foo.py");
79        let serialized =
80            serde_json::to_string(&path).expect("serialize failed");
81        let expected = "\"foo.py\"";
82        assert!(serialized == expected);
83    }
84
85    #[test]
86    fn deserialize_virtual_target_path() {
87        let path = VirtualTargetPath::from("foo.py");
88        let deserialized: VirtualTargetPath =
89            serde_json::from_str("\"foo.py\"").expect("serialize failed");
90        assert!(path == deserialized);
91    }
92}