use std::fmt;
use std::num::NonZeroU64;
use std::str::FromStr;
const DIGITS: usize = 32;
const SHOWN: usize = 12;
#[cfg(any(test, feature = "test-support"))]
#[must_use]
pub fn count(n: u64) -> NonZeroU64 {
NonZeroU64::new(n).expect("a count from 1")
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RunId {
bits: u128,
digits: [u8; DIGITS],
}
impl RunId {
pub fn parse(text: &str) -> Result<RunId, ParsePlaceError> {
let digits =
text.len() == DIGITS && text.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
match u128::from_str_radix(text, 16) {
Ok(bits) if digits => Ok(RunId::of(bits)),
_ => Err(ParsePlaceError::new(PlaceKind::Run, text)),
}
}
#[must_use]
pub fn from_bits(bits: [u8; 16]) -> RunId {
RunId::of(u128::from_be_bytes(bits))
}
#[must_use]
pub fn bits(&self) -> [u8; 16] {
self.bits.to_be_bytes()
}
fn of(bits: u128) -> RunId {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut digits = [0_u8; DIGITS];
for (place, digit) in digits.iter_mut().enumerate() {
let shift = 4 * (DIGITS - 1 - place);
*digit = HEX[usize::from(u8::try_from((bits >> shift) & 0xf).unwrap_or(0))];
}
RunId { bits, digits }
}
#[cfg(any(test, feature = "test-support"))]
#[must_use]
pub fn example(n: u128) -> RunId {
RunId::of(n)
}
#[must_use]
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.digits).expect("a run id's digits are ASCII")
}
#[must_use]
pub fn shown(&self) -> &str {
&self.as_str()[..SHOWN]
}
}
impl fmt::Display for RunId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl fmt::Debug for RunId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "RunId({self})")
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct TaskPath {
counts: Vec<NonZeroU64>,
}
impl TaskPath {
#[must_use]
pub fn root() -> TaskPath {
TaskPath::new(Vec::new())
}
#[must_use]
pub fn new(counts: Vec<NonZeroU64>) -> TaskPath {
TaskPath { counts }
}
#[must_use]
pub fn child(&self, count: NonZeroU64) -> TaskPath {
let mut counts = self.counts.clone();
counts.push(count);
TaskPath::new(counts)
}
#[must_use]
pub fn counts(&self) -> &[NonZeroU64] {
&self.counts
}
pub fn parse(text: &str) -> Result<TaskPath, ParsePlaceError> {
match Written::read(text) {
Some(Written {
segment: None,
task,
count: None,
}) => Ok(task),
_ => Err(ParsePlaceError::new(PlaceKind::Task, text)),
}
}
}
impl fmt::Display for TaskPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("root")?;
for count in &self.counts {
write!(f, "/{count}")?;
}
Ok(())
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CallRef {
segment: u64,
task: TaskPath,
index: NonZeroU64,
}
impl CallRef {
#[must_use]
pub fn new(segment: u64, task: TaskPath, index: NonZeroU64) -> CallRef {
CallRef {
segment,
task,
index,
}
}
#[must_use]
pub fn first(task: TaskPath, index: NonZeroU64) -> CallRef {
CallRef::new(0, task, index)
}
pub fn parse(text: &str) -> Result<CallRef, ParsePlaceError> {
let refused = || ParsePlaceError::new(PlaceKind::Call, text);
match Written::read(text).ok_or_else(refused)? {
Written {
segment,
task,
count: Some((index, None)),
} => Ok(CallRef::new(
segment.map_or(0, NonZeroU64::get),
task,
NonZeroU64::new(index).ok_or_else(refused)?,
)),
Written { .. } => Err(refused()),
}
}
#[must_use]
pub fn segment(&self) -> u64 {
self.segment
}
#[must_use]
pub fn task(&self) -> &TaskPath {
&self.task
}
#[must_use]
pub fn index(&self) -> NonZeroU64 {
self.index
}
#[must_use]
pub fn position(&self) -> CallRef {
CallRef::first(self.task.clone(), self.index)
}
}
impl fmt::Display for CallRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write_segment(f, self.segment)?;
write!(f, "{}#{}", self.task, self.index)
}
}
impl fmt::Debug for CallRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CallRef({self})")
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Moment {
pub segment: u64,
pub task: TaskPath,
pub call: u64,
pub steps: u64,
}
impl Moment {
pub fn parse(text: &str) -> Result<Moment, ParsePlaceError> {
match Written::read(text) {
Some(Written {
segment,
task,
count: Some((call, Some(steps))),
}) => Ok(Moment {
segment: segment.map_or(0, NonZeroU64::get),
task,
call,
steps,
}),
_ => Err(ParsePlaceError::new(PlaceKind::Moment, text)),
}
}
}
impl fmt::Display for Moment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write_segment(f, self.segment)?;
write!(f, "{}#{}+{}", self.task, self.call, self.steps)
}
}
fn write_segment(f: &mut fmt::Formatter<'_>, segment: u64) -> fmt::Result {
if segment > 0 {
write!(f, "p{segment}:")?;
}
Ok(())
}
struct Written {
segment: Option<NonZeroU64>,
task: TaskPath,
count: Option<(u64, Option<u64>)>,
}
impl Written {
fn read(text: &str) -> Option<Written> {
let (segment, rest) = match text.strip_prefix('p') {
Some(prefixed) => {
let (segment, rest) = prefixed.split_once(':')?;
(Some(NonZeroU64::new(number(segment)?)?), rest)
}
None => (None, text),
};
let (task, count) = match rest.split_once('#') {
Some((task, count)) => (task, Some(count)),
None => (rest, None),
};
let counts = match task.strip_prefix("root")? {
"" => Vec::new(),
spawns => spawns
.strip_prefix('/')?
.split('/')
.map(|count| NonZeroU64::new(number(count)?))
.collect::<Option<_>>()?,
};
let count = match count {
None => None,
Some(count) => Some(match count.split_once('+') {
None => (number(count)?, None),
Some((count, steps)) => (number(count)?, Some(number(steps)?)),
}),
};
Some(Written {
segment,
task: TaskPath::new(counts),
count,
})
}
}
fn number(text: &str) -> Option<u64> {
let n: u64 = text.parse().ok()?;
(n.to_string() == text).then_some(n)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum PlaceKind {
Run,
Task,
Call,
Moment,
}
impl PlaceKind {
const fn written(self) -> &'static str {
match self {
PlaceKind::Run => "a run id: an id is 32 lowercase hexadecimal digits",
PlaceKind::Task => "a task id, such as root or root/2/1",
PlaceKind::Call => "a call id, such as root#1, root/2#3 or p1:root#6",
PlaceKind::Moment => "a moment, such as root#0+3, root/2#4+17 or p1:root#4+5",
}
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct ParsePlaceError {
kind: PlaceKind,
text: String,
}
impl ParsePlaceError {
fn new(kind: PlaceKind, text: &str) -> ParsePlaceError {
ParsePlaceError {
kind,
text: text.to_owned(),
}
}
#[must_use]
pub fn kind(&self) -> PlaceKind {
self.kind
}
#[must_use]
pub fn text(&self) -> &str {
&self.text
}
}
impl fmt::Display for ParsePlaceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"`{}` is not {}",
self.text.escape_debug(),
self.kind.written()
)
}
}
impl std::error::Error for ParsePlaceError {}
macro_rules! written_as_text {
($($place:ty),+) => {$(
impl FromStr for $place {
type Err = ParsePlaceError;
fn from_str(text: &str) -> Result<$place, ParsePlaceError> {
<$place>::parse(text)
}
}
impl serde::Serialize for $place {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> serde::Deserialize<'de> for $place {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<$place, D::Error> {
let text = String::deserialize(deserializer)?;
<$place>::parse(&text).map_err(serde::de::Error::custom)
}
}
)+};
}
written_as_text!(RunId, TaskPath, CallRef, Moment);
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests;