#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Lifespan {
Ephemeral(Span),
Immortal,
}
impl Lifespan {
pub fn with_span(span: impl Into<Span>) -> Self {
Self::Ephemeral(span.into())
}
pub fn is_alive(&self) -> bool {
match self {
Lifespan::Ephemeral(span) => span.length() > 0,
Lifespan::Immortal => true,
}
}
pub fn shorten(&mut self) -> &Self {
self.shorten_by(Span::with_length(1))
}
pub fn lengthen(&mut self) -> &Self {
self.lengthen_by(Span::with_length(1))
}
pub fn shorten_by(&mut self, amount: impl Into<Span>) -> &Self {
let amount = amount.into();
if let Lifespan::Ephemeral(span) = self {
span.shorten_by(amount.into());
}
self
}
pub fn lengthen_by(&mut self, amount: impl Into<Span>) -> &Self {
let amount = amount.into();
if let Lifespan::Ephemeral(span) = self {
span.lengthen_by(amount.into());
}
self
}
pub fn clear(&mut self) {
*self = Lifespan::Ephemeral(Span::empty())
}
pub fn span(self) -> Option<Span> {
if let Lifespan::Ephemeral(span) = self {
Some(span)
} else {
None
}
}
pub fn length(self) -> Option<u64> {
self.span().map(|span| span.length())
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Span {
length: u64,
}
impl From<u64> for Span {
fn from(length: u64) -> Self {
Self { length }
}
}
impl From<Span> for u64 {
fn from(span: Span) -> Self {
span.length
}
}
impl Span {
pub fn with_length(length: u64) -> Self {
Self { length }
}
pub fn empty() -> Self {
Self { length: 0 }
}
pub fn length(self) -> u64 {
self.length
}
pub fn shorten_by(&mut self, length: u64) {
self.length = self.length.saturating_sub(length);
}
pub fn lengthen_by(&mut self, length: u64) {
self.length = self.length.saturating_add(length);
}
pub fn shorten(&mut self) {
self.shorten_by(1);
}
pub fn lengthen(&mut self) {
self.lengthen_by(1);
}
pub fn clear(&mut self) {
self.length = 0;
}
}