1use std::fmt;
22use std::num::NonZeroU64;
23use std::str::FromStr;
24
25const DIGITS: usize = 32;
27
28const SHOWN: usize = 12;
31
32#[cfg(any(test, feature = "test-support"))]
39#[must_use]
40pub fn count(n: u64) -> NonZeroU64 {
41 NonZeroU64::new(n).expect("a count from 1")
42}
43
44#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
51pub struct RunId {
52 bits: u128,
53 digits: [u8; DIGITS],
54}
55
56impl RunId {
57 pub fn parse(text: &str) -> Result<RunId, ParsePlaceError> {
64 let digits =
65 text.len() == DIGITS && text.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
66 match u128::from_str_radix(text, 16) {
67 Ok(bits) if digits => Ok(RunId::of(bits)),
68 _ => Err(ParsePlaceError::new(PlaceKind::Run, text)),
69 }
70 }
71
72 #[must_use]
74 pub fn from_bits(bits: [u8; 16]) -> RunId {
75 RunId::of(u128::from_be_bytes(bits))
76 }
77
78 #[must_use]
81 pub fn bits(&self) -> [u8; 16] {
82 self.bits.to_be_bytes()
83 }
84
85 fn of(bits: u128) -> RunId {
87 const HEX: &[u8; 16] = b"0123456789abcdef";
88 let mut digits = [0_u8; DIGITS];
89 for (place, digit) in digits.iter_mut().enumerate() {
90 let shift = 4 * (DIGITS - 1 - place);
91 *digit = HEX[usize::from(u8::try_from((bits >> shift) & 0xf).unwrap_or(0))];
92 }
93 RunId { bits, digits }
94 }
95
96 #[cfg(any(test, feature = "test-support"))]
99 #[must_use]
100 pub fn example(n: u128) -> RunId {
101 RunId::of(n)
102 }
103
104 #[must_use]
110 pub fn as_str(&self) -> &str {
111 std::str::from_utf8(&self.digits).expect("a run id's digits are ASCII")
112 }
113
114 #[must_use]
116 pub fn shown(&self) -> &str {
117 &self.as_str()[..SHOWN]
118 }
119}
120
121impl fmt::Display for RunId {
122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 f.write_str(self.as_str())
124 }
125}
126
127impl fmt::Debug for RunId {
128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129 write!(f, "RunId({self})")
130 }
131}
132
133#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
140pub struct TaskPath {
141 counts: Vec<NonZeroU64>,
142}
143
144impl TaskPath {
145 #[must_use]
147 pub fn root() -> TaskPath {
148 TaskPath::new(Vec::new())
149 }
150
151 #[must_use]
153 pub fn new(counts: Vec<NonZeroU64>) -> TaskPath {
154 TaskPath { counts }
155 }
156
157 #[must_use]
159 pub fn child(&self, count: NonZeroU64) -> TaskPath {
160 let mut counts = self.counts.clone();
161 counts.push(count);
162 TaskPath::new(counts)
163 }
164
165 #[must_use]
167 pub fn counts(&self) -> &[NonZeroU64] {
168 &self.counts
169 }
170
171 pub fn parse(text: &str) -> Result<TaskPath, ParsePlaceError> {
178 match Written::read(text) {
179 Some(Written {
180 segment: None,
181 task,
182 count: None,
183 }) => Ok(task),
184 _ => Err(ParsePlaceError::new(PlaceKind::Task, text)),
185 }
186 }
187}
188
189impl fmt::Display for TaskPath {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 f.write_str("root")?;
192 for count in &self.counts {
193 write!(f, "/{count}")?;
194 }
195 Ok(())
196 }
197}
198
199#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
203pub struct CallRef {
204 segment: u64,
205 task: TaskPath,
206 index: NonZeroU64,
207}
208
209impl CallRef {
210 #[must_use]
213 pub fn new(segment: u64, task: TaskPath, index: NonZeroU64) -> CallRef {
214 CallRef {
215 segment,
216 task,
217 index,
218 }
219 }
220
221 #[must_use]
224 pub fn first(task: TaskPath, index: NonZeroU64) -> CallRef {
225 CallRef::new(0, task, index)
226 }
227
228 pub fn parse(text: &str) -> Result<CallRef, ParsePlaceError> {
235 let refused = || ParsePlaceError::new(PlaceKind::Call, text);
236 match Written::read(text).ok_or_else(refused)? {
237 Written {
238 segment,
239 task,
240 count: Some((index, None)),
241 } => Ok(CallRef::new(
242 segment.map_or(0, NonZeroU64::get),
243 task,
244 NonZeroU64::new(index).ok_or_else(refused)?,
245 )),
246 Written { .. } => Err(refused()),
247 }
248 }
249
250 #[must_use]
252 pub fn segment(&self) -> u64 {
253 self.segment
254 }
255
256 #[must_use]
258 pub fn task(&self) -> &TaskPath {
259 &self.task
260 }
261
262 #[must_use]
264 pub fn index(&self) -> NonZeroU64 {
265 self.index
266 }
267
268 #[must_use]
270 pub fn position(&self) -> CallRef {
271 CallRef::first(self.task.clone(), self.index)
272 }
273}
274
275impl fmt::Display for CallRef {
276 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277 write_segment(f, self.segment)?;
278 write!(f, "{}#{}", self.task, self.index)
279 }
280}
281
282impl fmt::Debug for CallRef {
283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284 write!(f, "CallRef({self})")
285 }
286}
287
288#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
293pub struct Moment {
294 pub segment: u64,
296 pub task: TaskPath,
298 pub call: u64,
301 pub steps: u64,
303}
304
305impl Moment {
306 pub fn parse(text: &str) -> Result<Moment, ParsePlaceError> {
313 match Written::read(text) {
314 Some(Written {
315 segment,
316 task,
317 count: Some((call, Some(steps))),
318 }) => Ok(Moment {
319 segment: segment.map_or(0, NonZeroU64::get),
320 task,
321 call,
322 steps,
323 }),
324 _ => Err(ParsePlaceError::new(PlaceKind::Moment, text)),
325 }
326 }
327}
328
329impl fmt::Display for Moment {
330 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331 write_segment(f, self.segment)?;
332 write!(f, "{}#{}+{}", self.task, self.call, self.steps)
333 }
334}
335
336fn write_segment(f: &mut fmt::Formatter<'_>, segment: u64) -> fmt::Result {
339 if segment > 0 {
340 write!(f, "p{segment}:")?;
341 }
342 Ok(())
343}
344
345struct Written {
347 segment: Option<NonZeroU64>,
349 task: TaskPath,
351 count: Option<(u64, Option<u64>)>,
353}
354
355impl Written {
356 fn read(text: &str) -> Option<Written> {
359 let (segment, rest) = match text.strip_prefix('p') {
360 Some(prefixed) => {
361 let (segment, rest) = prefixed.split_once(':')?;
362 (Some(NonZeroU64::new(number(segment)?)?), rest)
363 }
364 None => (None, text),
365 };
366 let (task, count) = match rest.split_once('#') {
367 Some((task, count)) => (task, Some(count)),
368 None => (rest, None),
369 };
370 let counts = match task.strip_prefix("root")? {
371 "" => Vec::new(),
372 spawns => spawns
373 .strip_prefix('/')?
374 .split('/')
375 .map(|count| NonZeroU64::new(number(count)?))
376 .collect::<Option<_>>()?,
377 };
378 let count = match count {
379 None => None,
380 Some(count) => Some(match count.split_once('+') {
381 None => (number(count)?, None),
382 Some((count, steps)) => (number(count)?, Some(number(steps)?)),
383 }),
384 };
385 Some(Written {
386 segment,
387 task: TaskPath::new(counts),
388 count,
389 })
390 }
391}
392
393fn number(text: &str) -> Option<u64> {
396 let n: u64 = text.parse().ok()?;
397 (n.to_string() == text).then_some(n)
398}
399
400#[derive(Clone, Copy, PartialEq, Eq, Debug)]
402pub enum PlaceKind {
403 Run,
405 Task,
407 Call,
409 Moment,
411}
412
413impl PlaceKind {
414 const fn written(self) -> &'static str {
416 match self {
417 PlaceKind::Run => "a run id: an id is 32 lowercase hexadecimal digits",
418 PlaceKind::Task => "a task id, such as root or root/2/1",
419 PlaceKind::Call => "a call id, such as root#1, root/2#3 or p1:root#6",
420 PlaceKind::Moment => "a moment, such as root#0+3, root/2#4+17 or p1:root#4+5",
421 }
422 }
423}
424
425#[derive(Clone, PartialEq, Eq, Debug)]
427pub struct ParsePlaceError {
428 kind: PlaceKind,
429 text: String,
430}
431
432impl ParsePlaceError {
433 fn new(kind: PlaceKind, text: &str) -> ParsePlaceError {
434 ParsePlaceError {
435 kind,
436 text: text.to_owned(),
437 }
438 }
439
440 #[must_use]
442 pub fn kind(&self) -> PlaceKind {
443 self.kind
444 }
445
446 #[must_use]
448 pub fn text(&self) -> &str {
449 &self.text
450 }
451}
452
453impl fmt::Display for ParsePlaceError {
454 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
455 write!(
456 f,
457 "`{}` is not {}",
458 self.text.escape_debug(),
459 self.kind.written()
460 )
461 }
462}
463
464impl std::error::Error for ParsePlaceError {}
465
466macro_rules! written_as_text {
469 ($($place:ty),+) => {$(
470 impl FromStr for $place {
471 type Err = ParsePlaceError;
472
473 fn from_str(text: &str) -> Result<$place, ParsePlaceError> {
474 <$place>::parse(text)
475 }
476 }
477
478 impl serde::Serialize for $place {
479 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
480 serializer.collect_str(self)
481 }
482 }
483
484 impl<'de> serde::Deserialize<'de> for $place {
485 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<$place, D::Error> {
486 let text = String::deserialize(deserializer)?;
487 <$place>::parse(&text).map_err(serde::de::Error::custom)
488 }
489 }
490 )+};
491}
492
493written_as_text!(RunId, TaskPath, CallRef, Moment);
494
495#[cfg(test)]
496#[cfg_attr(coverage, coverage(off))]
497mod tests;