use core::fmt;
use smol_bytes::Utf8Bytes;
use crate::{Slot, name::folds_to};
use super::{LaneIdent, LanguageTag};
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Lane {
key: &'static LaneIdent,
accepts: &'static [&'static LaneIdent],
catch_all: bool,
}
impl Lane {
#[inline]
#[must_use]
pub const fn of(key: &'static LaneIdent) -> Self {
Self {
key,
accepts: &[],
catch_all: false,
}
}
#[inline]
#[must_use]
pub const fn accepting(mut self, accepts: &'static [&'static LaneIdent]) -> Self {
self.accepts = accepts;
self
}
#[inline]
#[must_use]
pub const fn catch_all(mut self) -> Self {
self.catch_all = true;
self
}
#[inline]
#[must_use]
pub const fn is_catch_all(&self) -> bool {
self.catch_all
}
#[inline]
#[must_use]
pub const fn key(&self) -> &'static LaneIdent {
self.key
}
#[inline]
#[must_use]
pub const fn accepts(&self) -> &'static [&'static LaneIdent] {
self.accepts
}
}
#[diagnostic::on_unimplemented(
message = "`{Self}` publishes no lane roster",
label = "no lanes",
note = "a fanned corpus states its partitions here; an unfanned one takes the default roster by \
writing `impl Lanes for {Self} {{}}`"
)]
pub trait Lanes: Slot {
const LANES: &'static [Lane] = &[Lane::of(LaneIdent::UND)];
}
#[diagnostic::on_unimplemented(
message = "`{Self}` states no lane probe",
label = "no probe type",
note = "a router wired to this slot answers in its probe currency; state it with `impl LanedStore \
for {Self} {{ type Probe = …; }}`"
)]
pub trait LanedStore: Lanes {
type Probe;
}
pub fn lane_for(tag: &str, lanes: &'static [Lane]) -> Result<&'static Lane, UnknownLane> {
let Some(reduced) = LanguageTag::parse(tag) else {
return catch_all(lanes).ok_or_else(|| UnknownLane::new(tag, lanes));
};
for lane in lanes {
if reduced.matches(lane.key()) {
return Ok(lane);
}
}
for lane in lanes {
for accepted in lane.accepts() {
if reduced.matches(accepted) {
return Ok(lane);
}
}
}
for lane in lanes {
if reduced.matches_language(lane.key()) {
return Ok(lane);
}
}
for lane in lanes {
for accepted in lane.accepts() {
if reduced.matches_language(accepted) {
return Ok(lane);
}
}
}
catch_all(lanes).ok_or_else(|| UnknownLane::new(tag, lanes))
}
fn catch_all(lanes: &'static [Lane]) -> Option<&'static Lane> {
lanes.iter().find(|lane| lane.is_catch_all())
}
pub fn lane_collisions(lanes: &'static [Lane]) -> Result<(), LaneCollision> {
let mut catch_alls = lanes.iter().filter(|lane| lane.is_catch_all());
if let (Some(first), Some(second)) = (catch_alls.next(), catch_alls.next()) {
return Err(LaneCollision::over_the_catch_all(first.key(), second.key()));
}
let mut at = 0;
while let Some((word, owner)) = lane_claim(lanes, at) {
let mut other = at + 1;
while let Some((against, also)) = lane_claim(lanes, other) {
if folds_to(word, against) {
return Err(LaneCollision::new(word, owner, also));
}
other += 1;
}
at += 1;
}
Ok(())
}
#[inline]
#[must_use]
pub const fn lane_claims(lanes: &[Lane]) -> usize {
let mut lane = 0;
let mut claimed = 0;
while lane < lanes.len() {
claimed += 1 + lanes[lane].accepts.len();
lane += 1;
}
claimed
}
#[must_use]
pub const fn lane_claim(lanes: &[Lane], at: usize) -> Option<(&LaneIdent, &LaneIdent)> {
let mut lane = 0;
let mut before = 0;
while lane < lanes.len() {
let here = 1 + lanes[lane].accepts.len();
if at < before + here {
let within = at - before;
let word = if within == 0 {
lanes[lane].key
} else {
lanes[lane].accepts[within - 1]
};
return Some((word, lanes[lane].key));
}
before += here;
lane += 1;
}
None
}
#[must_use]
pub const fn lane_claim_repeats(lanes: &[Lane], at: usize) -> bool {
let Some((word, _)) = lane_claim(lanes, at) else {
return false;
};
let mut before = 0;
while before < at {
let Some((earlier, _)) = lane_claim(lanes, before) else {
return false;
};
if folds_to(word.as_str(), earlier.as_str()) {
return true;
}
before += 1;
}
false
}
#[must_use]
pub const fn lane_catch_all_repeats(lanes: &[Lane], at: usize) -> bool {
if at >= lanes.len() || !lanes[at].catch_all {
return false;
}
let mut before = 0;
while before < at {
if lanes[before].catch_all {
return true;
}
before += 1;
}
false
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownLane {
tag: Utf8Bytes,
lanes: &'static [Lane],
}
impl UnknownLane {
#[inline]
#[must_use]
pub fn new(tag: &str, lanes: &'static [Lane]) -> Self {
Self {
tag: Utf8Bytes::from(tag.to_owned()),
lanes,
}
}
#[inline]
#[must_use]
pub fn tag(&self) -> &str {
self.tag.as_str()
}
#[inline]
#[must_use]
pub const fn lanes(&self) -> &'static [Lane] {
self.lanes
}
}
impl fmt::Display for UnknownLane {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"no lane answers the tag `{}`; this corpus holds",
self.tag
)?;
if self.lanes.is_empty() {
return f.write_str(" no lanes at all");
}
for (at, lane) in self.lanes.iter().enumerate() {
let separator = if at == 0 { " " } else { ", " };
write!(f, "{separator}`{}`", &**lane.key())?;
let mut accepts = lane.accepts().iter().copied();
if let Some(first) = accepts.next() {
write!(f, " (also accepting `{}`", &**first)?;
for accepted in accepts {
write!(f, ", `{}`", &**accepted)?;
}
f.write_str(")")?;
}
}
f.write_str(", and no catch-all is declared")
}
}
impl core::error::Error for UnknownLane {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Claimed {
Word(Utf8Bytes),
CatchAll,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LaneCollision {
claimed: Claimed,
first: &'static LaneIdent,
second: &'static LaneIdent,
}
impl LaneCollision {
#[inline]
#[must_use]
pub fn new(word: &LaneIdent, first: &'static LaneIdent, second: &'static LaneIdent) -> Self {
let word: &str = word;
Self {
claimed: Claimed::Word(Utf8Bytes::from(word.to_owned())),
first,
second,
}
}
#[inline]
#[must_use]
pub const fn over_the_catch_all(first: &'static LaneIdent, second: &'static LaneIdent) -> Self {
Self {
claimed: Claimed::CatchAll,
first,
second,
}
}
#[inline]
#[must_use]
pub const fn claimed(&self) -> &Claimed {
&self.claimed
}
#[inline]
#[must_use]
pub fn word(&self) -> Option<&str> {
match &self.claimed {
Claimed::Word(word) => Some(word.as_str()),
Claimed::CatchAll => None,
}
}
#[inline]
#[must_use]
pub const fn first(&self) -> &'static LaneIdent {
self.first
}
#[inline]
#[must_use]
pub const fn second(&self) -> &'static LaneIdent {
self.second
}
}
impl fmt::Display for LaneCollision {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match &self.claimed {
Claimed::Word(word) => format!(
"the word `{word}` is claimed by lane `{}` and by lane `{}`; one tag cannot name two lanes",
&**self.first, &**self.second
),
Claimed::CatchAll => format!(
"lane `{}` and lane `{}` are both declared the catch-all; a roster declares exactly one",
&**self.first, &**self.second
),
}
)
}
}
impl core::error::Error for LaneCollision {}