1use core::fmt;
30use core::str::FromStr;
31
32use oxicode::de::{Decode, Decoder};
33use oxicode::enc::{Encode, Encoder};
34use serde::{Deserialize, Deserializer, Serialize};
35
36use crate::error::{IdError, IdKind, codec_invalid, preview};
37
38pub const MAX_NAME_LEN: usize = 255;
45
46#[must_use]
63pub const fn is_name_char(ch: char) -> bool {
64 ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | '-')
65}
66
67pub fn validate_name(kind: IdKind, value: &str, max: usize) -> Result<(), IdError> {
85 if value.is_empty() {
86 return Err(IdError::Empty { kind });
87 }
88 if value.len() > max {
89 return Err(IdError::TooLong {
90 kind,
91 len: value.len(),
92 max,
93 });
94 }
95 for (index, ch) in value.char_indices() {
96 if !is_name_char(ch) {
97 return Err(IdError::InvalidChar {
98 kind,
99 value: preview(value),
100 ch,
101 index,
102 });
103 }
104 }
105 Ok(())
106}
107
108macro_rules! define_name_id {
115 (
116 $(#[$meta:meta])*
117 $name:ident, $kind:expr, $noun:literal
118 ) => {
119 $(#[$meta])*
120 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
121 #[serde(transparent)]
122 pub struct $name(String);
123
124 impl $name {
125 pub const KIND: IdKind = $kind;
127
128 pub const MAX_LEN: usize = MAX_NAME_LEN;
130
131 #[doc = concat!("Validates `value` and wraps it as a ", $noun, ".")]
132 #[doc = concat!("[`MAX_NAME_LEN`] bytes, or outside `[A-Za-z0-9_.-]`.")]
137 #[doc = concat!("use astrs_wire::", stringify!($name), ";")]
142 #[doc = concat!("assert!(", stringify!($name), "::new(\"valid-01\").is_ok());")]
144 #[doc = concat!("assert!(", stringify!($name), "::new(\"in valid\").is_err());")]
145 pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
147 let value = value.into();
148 validate_name(Self::KIND, &value, Self::MAX_LEN)?;
149 Ok(Self(value))
150 }
151
152 #[doc = concat!("Wraps `value` as a ", $noun, ", repairing it if it does not fit the grammar.")]
153 #[doc = concat!("use astrs_wire::", stringify!($name), ";")]
171 #[doc = concat!("assert_eq!(", stringify!($name), "::sanitized(\"camera.image\").as_str(), \"camera.image\");")]
173 #[doc = concat!("assert_eq!(", stringify!($name), "::sanitized(\"in valid\").as_str(), \"in_valid\");")]
174 #[doc = concat!("assert_eq!(", stringify!($name), "::sanitized(\"\").as_str(), \"_\");")]
175 #[must_use]
177 pub fn sanitized(value: &str) -> Self {
178 let mut repaired = String::with_capacity(value.len().min(Self::MAX_LEN));
179 for ch in value.chars() {
180 let ch = if is_name_char(ch) { ch } else { '_' };
181 if repaired.len() + ch.len_utf8() > Self::MAX_LEN {
182 break;
183 }
184 repaired.push(ch);
185 }
186 if repaired.is_empty() {
187 repaired.push('_');
188 }
189 Self(repaired)
190 }
191
192 #[must_use]
194 pub fn as_str(&self) -> &str {
195 &self.0
196 }
197
198 #[must_use]
200 pub fn into_string(self) -> String {
201 self.0
202 }
203
204 #[must_use]
206 pub fn len(&self) -> usize {
207 self.0.len()
208 }
209
210 #[must_use]
216 pub fn is_empty(&self) -> bool {
217 false
218 }
219 }
220
221 impl fmt::Display for $name {
222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223 f.write_str(&self.0)
224 }
225 }
226
227 impl fmt::Debug for $name {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 write!(f, "{}({:?})", stringify!($name), self.0)
230 }
231 }
232
233 impl FromStr for $name {
234 type Err = IdError;
235
236 fn from_str(value: &str) -> Result<Self, Self::Err> {
237 Self::new(value)
238 }
239 }
240
241 impl TryFrom<String> for $name {
242 type Error = IdError;
243
244 fn try_from(value: String) -> Result<Self, Self::Error> {
245 Self::new(value)
246 }
247 }
248
249 impl TryFrom<&str> for $name {
250 type Error = IdError;
251
252 fn try_from(value: &str) -> Result<Self, Self::Error> {
253 Self::new(value)
254 }
255 }
256
257 impl AsRef<str> for $name {
258 fn as_ref(&self) -> &str {
259 &self.0
260 }
261 }
262
263 impl core::borrow::Borrow<str> for $name {
264 fn borrow(&self) -> &str {
265 &self.0
266 }
267 }
268
269 impl PartialEq<str> for $name {
270 fn eq(&self, other: &str) -> bool {
271 self.0 == other
272 }
273 }
274
275 impl PartialEq<&str> for $name {
276 fn eq(&self, other: &&str) -> bool {
277 self.0 == *other
278 }
279 }
280
281 impl<'de> Deserialize<'de> for $name {
282 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
283 let raw = String::deserialize(deserializer)?;
284 Self::new(raw).map_err(serde::de::Error::custom)
285 }
286 }
287
288 impl Encode for $name {
289 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), oxicode::error::Error> {
290 self.0.encode(encoder)
291 }
292 }
293
294 impl<Context> Decode<Context> for $name {
295 fn decode<D: Decoder<Context = Context>>(
296 decoder: &mut D,
297 ) -> Result<Self, oxicode::error::Error> {
298 let raw = String::decode(decoder)?;
299 Self::new(raw).map_err(|err| codec_invalid(err.to_string()))
300 }
301 }
302 };
303}
304
305define_name_id! {
306 NodeId, IdKind::Node, "node id"
322}
323
324define_name_id! {
325 DataId, IdKind::Data, "data id"
338}
339
340define_name_id! {
341 OperatorId, IdKind::Operator, "operator id"
353}
354
355define_name_id! {
356 MachineName, IdKind::Machine, "machine name"
372}
373
374define_name_id! {
375 ParamKey, IdKind::Param, "parameter key"
392}
393
394impl ParamKey {
395 #[must_use]
411 pub fn is_internal(&self) -> bool {
412 self.as_str().starts_with('_')
413 }
414}
415
416#[cfg(test)]
417mod tests {
418 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
419
420 use super::*;
421 use crate::codec::{WireDecode, WireEncode};
422
423 #[test]
424 fn accepts_the_full_grammar() {
425 let all = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-";
426 assert!(NodeId::new(all).is_ok());
427 }
428
429 #[test]
430 fn rejects_the_empty_string() {
431 for result in [
432 NodeId::new("").err(),
433 DataId::new("").err(),
434 OperatorId::new("").err(),
435 MachineName::new("").err(),
436 ParamKey::new("").err(),
437 ] {
438 assert!(matches!(result, Some(IdError::Empty { .. })));
439 }
440 }
441
442 #[test]
443 fn rejects_characters_outside_the_grammar() {
444 for bad in ["a/b", "a b", "a:b", "a\u{0}b", "café", "a\nb", "a+b", "a*b"] {
445 match NodeId::new(bad) {
446 Err(IdError::InvalidChar { kind, .. }) => assert_eq!(kind, IdKind::Node),
447 other => panic!("{bad:?} should be rejected, got {other:?}"),
448 }
449 }
450 }
451
452 #[test]
453 fn reports_the_first_offending_character_and_offset() {
454 match DataId::new("ok.then/bad") {
455 Err(IdError::InvalidChar { ch, index, .. }) => {
456 assert_eq!(ch, '/');
457 assert_eq!(index, 7);
458 }
459 other => panic!("unexpected {other:?}"),
460 }
461 }
462
463 #[test]
464 fn enforces_the_length_cap() {
465 let at_limit = "a".repeat(MAX_NAME_LEN);
466 assert!(NodeId::new(&at_limit).is_ok());
467
468 let over = "a".repeat(MAX_NAME_LEN + 1);
469 match NodeId::new(&over) {
470 Err(IdError::TooLong { len, max, .. }) => {
471 assert_eq!(len, MAX_NAME_LEN + 1);
472 assert_eq!(max, MAX_NAME_LEN);
473 }
474 other => panic!("unexpected {other:?}"),
475 }
476 }
477
478 #[test]
479 fn error_messages_do_not_echo_unbounded_input() {
480 let hostile = format!("{}/", "z".repeat(10_000));
481 let err = NodeId::new(&hostile).unwrap_err();
482 assert!(err.to_string().len() < 200, "message: {err}");
483 }
484
485 #[test]
486 fn accessors_agree() {
487 let id = NodeId::new("camera").unwrap();
488 assert_eq!(id.as_str(), "camera");
489 assert_eq!(id.as_ref(), "camera");
490 assert_eq!(id.len(), 6);
491 assert!(!id.is_empty());
492 assert_eq!(id.to_string(), "camera");
493 assert_eq!(id, "camera");
494 assert_eq!(id.clone().into_string(), "camera");
495 assert_eq!(format!("{id:?}"), "NodeId(\"camera\")");
496 }
497
498 #[test]
499 fn borrow_enables_str_lookup_in_maps() {
500 use std::collections::BTreeMap;
501
502 let mut map = BTreeMap::new();
503 map.insert(NodeId::new("camera").unwrap(), 1);
504 assert_eq!(map.get("camera"), Some(&1));
505 }
506
507 #[test]
508 fn ordering_is_lexicographic() {
509 let mut ids = [
510 NodeId::new("zeta").unwrap(),
511 NodeId::new("alpha").unwrap(),
512 NodeId::new("Beta").unwrap(),
513 ];
514 ids.sort();
515 assert_eq!(ids[0].as_str(), "Beta");
516 assert_eq!(ids[1].as_str(), "alpha");
517 assert_eq!(ids[2].as_str(), "zeta");
518 }
519
520 #[test]
521 fn codec_round_trips() {
522 let id = DataId::new("image.raw-0").unwrap();
523 let bytes = id.encode_to_vec().unwrap();
524 assert_eq!(DataId::decode_exact(&bytes).unwrap(), id);
525 }
526
527 #[test]
528 fn decoding_validates_just_like_parsing() {
529 let hostile = "not a valid id".to_owned().encode_to_vec().unwrap();
532 let err = NodeId::decode_exact(&hostile).unwrap_err();
533 assert!(matches!(err, crate::WireError::Codec(_)), "{err:?}");
534 }
535
536 #[test]
537 fn decoding_enforces_the_length_cap() {
538 let hostile = "a".repeat(MAX_NAME_LEN + 1).encode_to_vec().unwrap();
539 assert!(NodeId::decode_exact(&hostile).is_err());
540 }
541
542 #[test]
543 fn decoding_rejects_the_empty_string() {
544 let empty = String::new().encode_to_vec().unwrap();
545 assert!(DataId::decode_exact(&empty).is_err());
546 }
547
548 #[test]
549 fn serde_round_trips_as_a_bare_string() {
550 let id = NodeId::new("planner").unwrap();
551 let json = serde_json::to_string(&id).unwrap();
552 assert_eq!(json, "\"planner\"");
553 assert_eq!(serde_json::from_str::<NodeId>(&json).unwrap(), id);
554 }
555
556 #[test]
557 fn serde_deserialization_validates() {
558 assert!(serde_json::from_str::<NodeId>("\"has space\"").is_err());
559 assert!(serde_json::from_str::<NodeId>("\"\"").is_err());
560 }
561
562 #[test]
563 fn try_from_variants_are_equivalent() {
564 assert_eq!(
565 NodeId::try_from("x").unwrap(),
566 NodeId::try_from("x".to_owned()).unwrap()
567 );
568 assert_eq!("x".parse::<NodeId>().unwrap(), NodeId::new("x").unwrap());
569 }
570
571 #[test]
572 fn each_type_reports_its_own_kind() {
573 assert_eq!(NodeId::KIND, IdKind::Node);
574 assert_eq!(DataId::KIND, IdKind::Data);
575 assert_eq!(OperatorId::KIND, IdKind::Operator);
576 assert_eq!(MachineName::KIND, IdKind::Machine);
577 assert_eq!(ParamKey::KIND, IdKind::Param);
578
579 let err = DataId::new("!").unwrap_err();
580 assert_eq!(err.kind(), IdKind::Data);
581 }
582
583 #[test]
584 fn param_keys_flag_internal_names() {
585 assert!(ParamKey::new("_schema_hash").unwrap().is_internal());
586 assert!(ParamKey::new("_trace").unwrap().is_internal());
587 assert!(!ParamKey::new("seq").unwrap().is_internal());
588 assert!(!ParamKey::new("goal.id").unwrap().is_internal());
589 }
590
591 #[test]
592 fn name_char_predicate_matches_the_validator() {
593 for byte in 0u8..=127 {
594 let ch = char::from(byte);
595 let mut buffer = String::from("a");
596 buffer.push(ch);
597 let accepted = NodeId::new(&buffer).is_ok();
598 assert_eq!(accepted, is_name_char(ch), "disagreement for {ch:?}");
599 }
600 }
601
602 #[test]
603 fn sanitized_keeps_a_legal_name_unchanged() {
604 for value in ["camera", "astrs.status", "node-01", "a_b.c-d"] {
605 assert_eq!(NodeId::sanitized(value).as_str(), value);
606 assert_eq!(DataId::sanitized(value).as_str(), value);
607 }
608 }
609
610 #[test]
611 fn sanitized_repairs_illegal_characters() {
612 assert_eq!(NodeId::sanitized("in valid").as_str(), "in_valid");
613 assert_eq!(NodeId::sanitized("a/b").as_str(), "a_b");
614 assert_eq!(NodeId::sanitized("a=b\0c").as_str(), "a_b_c");
615 }
616
617 #[test]
618 fn sanitized_never_returns_an_empty_name() {
619 assert_eq!(NodeId::sanitized("").as_str(), "_");
620 assert_eq!(DataId::sanitized("").as_str(), "_");
621 }
622
623 #[test]
624 fn sanitized_truncates_on_a_character_boundary() {
625 let long = "\u{00e9}".repeat(MAX_NAME_LEN);
626 let repaired = NodeId::sanitized(&long);
627 assert!(repaired.len() <= MAX_NAME_LEN);
628 assert_eq!(repaired.as_str(), "_".repeat(MAX_NAME_LEN));
631 }
632
633 #[test]
634 fn sanitized_output_always_passes_the_validator() {
635 for value in [
636 "",
637 " ",
638 "a/b/c",
639 "\u{1f600}",
640 &"x".repeat(MAX_NAME_LEN * 3),
641 ] {
642 let repaired = NodeId::sanitized(value);
643 assert!(
644 NodeId::new(repaired.as_str()).is_ok(),
645 "{value:?} repaired to {repaired:?}, which is still invalid"
646 );
647 }
648 }
649}