sentry_types/
project_id.rs

1use std::fmt;
2use std::str::FromStr;
3
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7/// Raised if a project ID cannot be parsed from a string.
8#[derive(Debug, Error, PartialEq, Eq, PartialOrd, Ord)]
9pub enum ParseProjectIdError {
10    /// Raised if an empty value is parsed.
11    #[error("empty or missing project id")]
12    EmptyValue,
13}
14
15/// Represents a project ID.
16#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
17pub struct ProjectId(String);
18
19impl ProjectId {
20    /// Creates a new project ID from its string representation.
21    /// This assumes that the string is already well-formed and URL
22    /// encoded/decoded.
23    #[inline]
24    pub fn new(id: &str) -> Self {
25        Self(id.to_string())
26    }
27
28    /// Returns the string representation of the project ID.
29    #[inline]
30    pub fn value(&self) -> &str {
31        self.0.as_ref()
32    }
33}
34
35impl fmt::Display for ProjectId {
36    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37        write!(f, "{}", self.0)
38    }
39}
40
41impl FromStr for ProjectId {
42    type Err = ParseProjectIdError;
43
44    fn from_str(s: &str) -> Result<ProjectId, ParseProjectIdError> {
45        if s.is_empty() {
46            return Err(ParseProjectIdError::EmptyValue);
47        }
48        Ok(ProjectId::new(s))
49    }
50}
51
52#[cfg(test)]
53mod test {
54    use super::*;
55
56    #[test]
57    fn test_basic_api() {
58        let id: ProjectId = "42".parse().unwrap();
59        assert_eq!(id, ProjectId::new("42"));
60        assert_eq!("42xxx".parse::<ProjectId>().unwrap().value(), "42xxx");
61        assert_eq!(
62            "".parse::<ProjectId>(),
63            Err(ParseProjectIdError::EmptyValue)
64        );
65        assert_eq!(ProjectId::new("42").to_string(), "42");
66
67        assert_eq!(
68            serde_json::to_string(&ProjectId::new("42")).unwrap(),
69            "\"42\""
70        );
71        assert_eq!(
72            serde_json::from_str::<ProjectId>("\"42\"").unwrap(),
73            ProjectId::new("42")
74        );
75    }
76}