use crate::{Count, Field, Kind, Len, Segment};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Referent<'a> {
Message(&'a str),
Choice(&'a str),
}
impl<'a> Referent<'a> {
pub(crate) fn name(self) -> &'a str {
match self {
Referent::Message(n) | Referent::Choice(n) => n,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Reference<'a> {
pub(crate) to: Referent<'a>,
pub(crate) field: &'a str,
pub(crate) avoidable: bool,
pub(crate) indirect: bool,
}
impl Segment {
fn references(&self) -> Option<Reference<'_>> {
let edge = |to, field, avoidable, indirect| Reference { to, field, avoidable, indirect };
Some(match self {
Segment::Value { name, kind: Kind::Msg { ty, boxed, .. }, .. } => {
edge(Referent::Message(ty), name, false, *boxed)
}
Segment::Opt {
field: Field { name, kind: Kind::Msg { ty, boxed, .. }, .. }, ..
} => edge(Referent::Message(ty), name, true, *boxed),
Segment::Repeat { name, element: Kind::Msg { ty, .. }, count, .. } => edge(
Referent::Message(ty),
name,
!matches!(count, Count::Window(Len::Bytes(n)) if *n > 0),
true,
),
Segment::Placed { name, kind: Kind::Msg { ty, boxed, .. }, absent, .. } => {
edge(Referent::Message(ty), name, absent.is_some(), *boxed)
}
Segment::Switch { name, choice, .. } => {
edge(Referent::Choice(choice), name, false, false)
}
_ => return None,
})
}
}
pub(crate) fn references(segments: &[Segment]) -> Vec<Reference<'_>> {
segments.iter().filter_map(Segment::references).collect()
}
#[cfg(feature = "emit")]
pub(crate) fn defers_open_end(segments: &[Segment]) -> Option<Reference<'_>> {
match segments.last()? {
Segment::Switch { window: Some(_), .. } => None,
seg @ (Segment::Switch { .. }
| Segment::Value { kind: Kind::Msg { .. }, .. }
| Segment::Opt { field: Field { kind: Kind::Msg { .. }, .. }, .. }) => seg.references(),
_ => None,
}
}
#[cfg(all(test, feature = "emit"))]
mod tests {
use super::*;
use crate::{By, Scalar};
#[test]
fn a_windowed_repeat_defers_to_nothing() {
let segments = [
Segment::Block(vec![Field::new("len", Kind::Scalar(Scalar::U(16)))]),
Segment::repeat(
"items",
Kind::Scalar(Scalar::U(8)),
Count::Window(Len::Field { by: By::field("len"), cap: None, align: None }),
None,
crate::Collection::Vec,
),
];
assert!(defers_open_end(&segments).is_none());
}
}