sentry_types/
project_id.rs
1use std::fmt;
2use std::str::FromStr;
3
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7#[derive(Debug, Error, PartialEq, Eq, PartialOrd, Ord)]
9pub enum ParseProjectIdError {
10 #[error("empty or missing project id")]
12 EmptyValue,
13}
14
15#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
17pub struct ProjectId(String);
18
19impl ProjectId {
20 #[inline]
24 pub fn new(id: &str) -> Self {
25 Self(id.to_string())
26 }
27
28 #[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}