gcloud_observability/
ids.rs1use crate::errors::{GcloudObservabilityError, GcloudObservabilityResult};
9use serde::{Deserialize, Serialize, Serializer};
10use std::borrow::Cow;
11use std::fmt::{Display, Formatter};
12use std::str::FromStr;
13
14const LOG_ID_RULE: &str = "must be 1 to 511 letters, digits and any of / _ - .";
15
16#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
30#[serde(try_from = "String")]
31pub struct LogId(Cow<'static, str>);
32
33impl LogId {
34 pub fn new(id: impl Into<String>) -> GcloudObservabilityResult<Self> {
39 let id = id.into();
40 if is_log_id(&id) {
41 Ok(Self(Cow::Owned(id)))
42 } else {
43 Err(GcloudObservabilityError::invalid_parameters(
44 "log_id",
45 format!("{LOG_ID_RULE}, got {id:?}"),
46 ))
47 }
48 }
49
50 pub const fn from_static(id: &'static str) -> Self {
57 if !is_log_id(id) {
58 panic!("{}", LOG_ID_RULE);
59 }
60 Self(Cow::Borrowed(id))
61 }
62}
63
64impl Display for LogId {
65 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
66 Display::fmt(&*self.0, f)
67 }
68}
69
70impl FromStr for LogId {
71 type Err = GcloudObservabilityError;
72
73 fn from_str(id: &str) -> Result<Self, Self::Err> {
74 Self::new(id)
75 }
76}
77
78impl TryFrom<String> for LogId {
79 type Error = GcloudObservabilityError;
80
81 fn try_from(id: String) -> Result<Self, Self::Error> {
82 Self::new(id)
83 }
84}
85
86impl Serialize for LogId {
87 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
88 serializer.serialize_str(&self.0)
89 }
90}
91
92const fn is_log_id(id: &str) -> bool {
95 const LOG_ID_CHARACTERS: &[u8] =
96 b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/_-.";
97 !id.is_empty() && id.len() < 512 && consists_of(id.as_bytes(), LOG_ID_CHARACTERS)
98}
99
100const fn consists_of(bytes: &[u8], allowed: &[u8]) -> bool {
104 let mut rest = bytes;
105 while let [byte, tail @ ..] = rest {
106 if position_of(*byte, allowed).is_none() {
107 return false;
108 }
109 rest = tail;
110 }
111 true
112}
113
114const fn position_of(byte: u8, bytes: &[u8]) -> Option<usize> {
115 let mut index = 0;
116 while index < bytes.len() {
117 if bytes[index] == byte {
118 return Some(index);
119 }
120 index += 1;
121 }
122 None
123}
124
125#[cfg(test)]
126mod tests {
127 use super::*;
128
129 fn refused_field<T: std::fmt::Debug>(result: GcloudObservabilityResult<T>) -> String {
130 match result {
131 Err(GcloudObservabilityError::InvalidParametersError(error)) => error.field,
132 other => panic!("expected an InvalidParametersError, got {other:?}"),
133 }
134 }
135
136 #[test]
137 fn log_id_follows_cloud_loggings_naming_rules() {
138 let longest = "a".repeat(511);
139 for accepted in ["o", "Orders/check-out_v1.2", longest.as_str()] {
140 assert!(LogId::new(accepted).is_ok(), "{accepted:?} is a log ID");
141 }
142
143 let too_long = "a".repeat(512);
144 for refused in [
145 "",
146 too_long.as_str(),
147 "orders log",
148 "orders:log",
149 "orders%2Flog",
150 ] {
151 assert_eq!(
152 refused_field(LogId::new(refused)),
153 "log_id",
154 "{refused:?} is not a log ID"
155 );
156 }
157 }
158
159 #[test]
160 fn log_id_is_checked_on_every_way_in() {
161 let checkout = LogId::from_static("orders/checkout");
162
163 assert_eq!("orders/checkout".parse::<LogId>().unwrap(), checkout);
164 assert_eq!(
165 LogId::try_from("orders/checkout".to_string()).unwrap(),
166 checkout
167 );
168 assert!("orders checkout".parse::<LogId>().is_err());
169 assert!(LogId::try_from("orders checkout".to_string()).is_err());
170 assert!(serde_json::from_str::<LogId>(r#""orders checkout""#).is_err());
171
172 let json = serde_json::to_string(&checkout).unwrap();
173 assert_eq!(json, r#""orders/checkout""#);
174 assert_eq!(serde_json::from_str::<LogId>(&json).unwrap(), checkout);
175 }
176}