Skip to main content

flow_span/
place.rs

1//! Places in a run (`history.md`, *Identity*; `runs.md`, *Places in a run*):
2//! a run's id, a task's path, a call's id and a moment in one task.
3//!
4//! A run's id is 128 bits written as 32 lowercase hexadecimal digits. The
5//! other three share one grammar:
6//!
7//! ```text
8//! [p<segment>:]<task>[#<count>[+<steps>]]
9//! task = root ( /<spawn> )*
10//! ```
11//!
12//! A [`TaskPath`] is the task alone. A [`CallRef`] adds the call's count and
13//! may carry its segment. A [`Moment`] adds the count of calls answered and
14//! the steps since. A segment, a spawn and a call's count are numbers from
15//! 1, while a moment's count and steps are numbers from 0. Every number is
16//! written in decimal with no sign and no leading zero and fits in 64 bits.
17//! Segment 0, the run's first, has no prefix. Each type reads exactly the
18//! text its `Display` writes, so a place is checked once, where text becomes
19//! one, and is a place from then on.
20
21use std::fmt;
22use std::num::NonZeroU64;
23use std::str::FromStr;
24
25/// How many digits a run id has.
26const DIGITS: usize = 32;
27
28/// How many of its digits a run id is shown to a person with
29/// (`guides/cli.md`).
30const SHOWN: usize = 12;
31
32/// The count `n`, which counts from 1: a spawn's or a call's, as a test
33/// writes it.
34///
35/// # Panics
36///
37/// When `n` is 0.
38#[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/// A run's id: 128 bits, written as exactly 32 lowercase hexadecimal digits.
45/// Text becomes one only through [`RunId::parse`], so an id read from a
46/// history, a frame or a command line that has any other form is refused
47/// where it is read. Ids order as their written digits do. It keeps its
48/// digits beside its bits, so it is `Copy` and lends them as text without
49/// allocating.
50#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
51pub struct RunId {
52    bits: u128,
53    digits: [u8; DIGITS],
54}
55
56impl RunId {
57    /// The run id `text` is.
58    ///
59    /// # Errors
60    ///
61    /// A [`ParsePlaceError`] when `text` is not exactly 32 lowercase
62    /// hexadecimal digits.
63    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    /// The id made of `bits`, as a minted id is written.
73    #[must_use]
74    pub fn from_bits(bits: [u8; 16]) -> RunId {
75        RunId::of(u128::from_be_bytes(bits))
76    }
77
78    /// Its 16 bits, most significant byte first, as [`RunId::from_bits`]
79    /// reads them.
80    #[must_use]
81    pub fn bits(&self) -> [u8; 16] {
82        self.bits.to_be_bytes()
83    }
84
85    /// The id of `bits`, its digits written once.
86    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    /// The id whose digits are `n` written in hexadecimal and padded with
97    /// zeros: a fixed id for tests, never a minted one.
98    #[cfg(any(test, feature = "test-support"))]
99    #[must_use]
100    pub fn example(n: u128) -> RunId {
101        RunId::of(n)
102    }
103
104    /// Its 32 digits.
105    ///
106    /// # Panics
107    ///
108    /// Never: an id's digits are written from `0-9a-f` alone.
109    #[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    /// Its first 12 digits, as it is shown to a person.
115    #[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/// Which task a call came from: its parent's path plus the parent's count of
134/// spawns at the moment it was spawned (`history.md`, *Identity*).
135///
136/// The root task's path is empty and is written `root`; its first child is
137/// `root/1`. Counters never restart: a task spawned after a checkpoint has
138/// the path a replay from fact 1 gives it.
139#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
140pub struct TaskPath {
141    counts: Vec<NonZeroU64>,
142}
143
144impl TaskPath {
145    /// The root task.
146    #[must_use]
147    pub fn root() -> TaskPath {
148        TaskPath::new(Vec::new())
149    }
150
151    /// The task whose spawn counts from the root down are `counts`.
152    #[must_use]
153    pub fn new(counts: Vec<NonZeroU64>) -> TaskPath {
154        TaskPath { counts }
155    }
156
157    /// The task this one spawned as its `count`th spawn.
158    #[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    /// The spawn counts from the root down, empty for the root.
166    #[must_use]
167    pub fn counts(&self) -> &[NonZeroU64] {
168        &self.counts
169    }
170
171    /// The task path `text` writes: `root`, then `/` and a spawn count any
172    /// number of times.
173    ///
174    /// # Errors
175    ///
176    /// A [`ParsePlaceError`] when `text` is any other text.
177    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/// A Tool call's id (`history.md`, *Identity*): the segment it was first
200/// recorded in, its task and the task's count of Tool calls, written
201/// `root/1#4` in the first segment and `p1:root/1#4` in the second.
202#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
203pub struct CallRef {
204    segment: u64,
205    task: TaskPath,
206    index: NonZeroU64,
207}
208
209impl CallRef {
210    /// The call `index` of `task`, first recorded in `segment`, 0 for the
211    /// run's first.
212    #[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    /// The call `index` of `task` in the run's first segment: a call's
222    /// position.
223    #[must_use]
224    pub fn first(task: TaskPath, index: NonZeroU64) -> CallRef {
225        CallRef::new(0, task, index)
226    }
227
228    /// The call id `text` writes: an optional segment `pK:`, a task path,
229    /// `#`, then the task's count of Tool calls.
230    ///
231    /// # Errors
232    ///
233    /// A [`ParsePlaceError`] when `text` is any other text.
234    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    /// The segment the call was first recorded in, 0 for the run's first.
251    #[must_use]
252    pub fn segment(&self) -> u64 {
253        self.segment
254    }
255
256    /// The task that made the call.
257    #[must_use]
258    pub fn task(&self) -> &TaskPath {
259        &self.task
260    }
261
262    /// The task's count of Tool calls, this one included: 1 for its first.
263    #[must_use]
264    pub fn index(&self) -> NonZeroU64 {
265        self.index
266    }
267
268    /// The call's position: its task and count, in the first segment.
269    #[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/// A place in one task's evaluation (`runs.md`, *Places in a run*): the
289/// segment whose program is evaluating, the task, the count of its calls
290/// whose answers were handed to it, and the steps it has taken since,
291/// written `root/2#4+17` or `p1:root#4+5`.
292#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
293pub struct Moment {
294    /// The segment, 0 for the run's first.
295    pub segment: u64,
296    /// The task.
297    pub task: TaskPath,
298    /// The index of its last call whose answer was handed to it; 0 before
299    /// its first.
300    pub call: u64,
301    /// Its steps since: 0 is the call's own step, or the task's start.
302    pub steps: u64,
303}
304
305impl Moment {
306    /// The moment `text` writes: a call's id whose count may be 0, `+`,
307    /// then the steps.
308    ///
309    /// # Errors
310    ///
311    /// A [`ParsePlaceError`] when `text` is any other text.
312    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
336/// A segment's prefix: `pK:` for segment `K` after the first, nothing for
337/// the first.
338fn write_segment(f: &mut fmt::Formatter<'_>, segment: u64) -> fmt::Result {
339    if segment > 0 {
340        write!(f, "p{segment}:")?;
341    }
342    Ok(())
343}
344
345/// The parts of the grammar a text writes, each read once.
346struct Written {
347    /// The segment its `pK:` prefix names, if it has one.
348    segment: Option<NonZeroU64>,
349    /// The task.
350    task: TaskPath,
351    /// The number after `#`, and the steps after `+`, if written.
352    count: Option<(u64, Option<u64>)>,
353}
354
355impl Written {
356    /// The parts `text` writes, or `None` when it follows no part of the
357    /// grammar.
358    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
393/// The number `text` writes in decimal with no sign and no leading zero,
394/// within 64 bits.
395fn number(text: &str) -> Option<u64> {
396    let n: u64 = text.parse().ok()?;
397    (n.to_string() == text).then_some(n)
398}
399
400/// What a text was read as.
401#[derive(Clone, Copy, PartialEq, Eq, Debug)]
402pub enum PlaceKind {
403    /// A [`RunId`].
404    Run,
405    /// A [`TaskPath`].
406    Task,
407    /// A [`CallRef`].
408    Call,
409    /// A [`Moment`].
410    Moment,
411}
412
413impl PlaceKind {
414    /// What the kind is and how it is written.
415    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/// Text that is not the place it was read as, as it was given.
426#[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    /// What the text was read as.
441    #[must_use]
442    pub fn kind(&self) -> PlaceKind {
443        self.kind
444    }
445
446    /// The text, as it was given.
447    #[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
466/// `FromStr` through the type's `parse`, and serde as the text its
467/// `Display` writes: one form for each place, read and written.
468macro_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;