use std::time::Instant;
use crate::action::{ActionError, ActionOutcome, ActionSpec};
use crate::config::ConfigValue;
use crate::{Capabilities, Counter, LaneKey, Sdu, SecurityProperties};
pub type Frames = Vec<(LaneKey, Sdu)>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum LayerError {
#[error(
"{layer}: the layer below carries {below} bytes per SDU and this layer needs {needs}; \
nothing would fit"
)]
TooSmallBelow {
layer: &'static str,
needs: u16,
below: u16,
},
#[error("{layer}: lane {lane}: {reason}")]
Lane {
layer: &'static str,
lane: LaneKey,
reason: String,
},
#[error("{layer}: {reason}")]
Failed { layer: &'static str, reason: String },
#[error("{layer}: {reason}")]
Unsupported { layer: &'static str, reason: String },
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Decoded {
Accepted,
Refused {
reason: &'static str,
detail: String,
},
}
impl Decoded {
#[must_use]
pub fn refused(reason: &'static str, detail: impl Into<String>) -> Self {
Self::Refused {
reason,
detail: detail.into(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct LayerContext {
pub device: String,
pub state_dir: Option<std::path::PathBuf>,
}
impl LayerContext {
#[must_use]
pub fn new(device: impl Into<String>) -> Self {
Self {
device: device.into(),
state_dir: None,
}
}
#[must_use]
pub fn state_dir(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
self.state_dir = Some(dir.into());
self
}
}
pub trait Layer: Send {
fn kind(&self) -> &'static str;
fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError>;
fn lanes(&mut self, above: &[LaneKey]) -> Result<Vec<LaneKey>, LayerError> {
Ok(above.to_vec())
}
fn encode(
&mut self,
lane: &LaneKey,
sdu: Sdu,
now: Instant,
out: &mut Frames,
) -> Result<(), LayerError>;
fn decode(&mut self, lane: &LaneKey, frame: Sdu, now: Instant, out: &mut Frames) -> Decoded;
fn tick(&mut self, now: Instant, down: &mut Frames, up: &mut Frames) -> Option<Instant> {
let _ = (now, down, up);
None
}
fn security(&self, below: Option<&SecurityProperties>) -> Option<SecurityProperties> {
below.cloned()
}
fn counters(&self) -> Vec<Counter> {
Vec::new()
}
fn actions(&self) -> Vec<ActionSpec> {
Vec::new()
}
fn invoke(
&mut self,
name: &str,
arguments: &std::collections::BTreeMap<String, ConfigValue>,
) -> Result<ActionOutcome, ActionError> {
let _ = arguments;
Err(ActionError::UnknownAction(name.to_string()))
}
}