dynix/src/line.rs
2026-03-31 19:50:11 +02:00

69 lines
1.5 KiB
Rust

// SPDX-FileCopyrightText: 2026 Qyriad <qyriad@qyriad.me>
//
// SPDX-License-Identifier: EUPL-1.1
use std::num::NonZeroU64;
#[allow(unused_imports)]
use crate::prelude::*;
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Line(pub u64);
/// Constructors.
impl Line {
pub const fn from_index(index: u64) -> Self {
Self(index)
}
pub const fn from_linenr(linenr: NonZeroU64) -> Self {
Self(linenr.get() - 1)
}
pub const fn next(self) -> Self {
Self::from_index(self.index() + 1)
}
/// Panics if self is line index 0.
pub const fn prev(self) -> Self {
Self::from_index(self.index() - 1)
}
}
/// Getters.
impl Line {
/// 0-indexed
pub const fn index(self) -> u64 {
self.0
}
#[cfg(target_pointer_width = "64")]
pub const fn index_usize(self) -> usize {
self.0 as usize
}
/// 1-indexed
pub const fn linenr(self) -> u64 {
self.0 + 1
}
}
/// [Alternate](Formatter::alternate) flag capitalizes "line".
///
/// ```
/// # use dynix::Line;
/// let line = Line::from_index(22);
/// assert_eq!(format!("{line}"), "line 23");
/// assert_eq!(format!("{line:#}"), "Line 23");
/// ```
impl Display for Line {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
if f.alternate() {
write!(f, "Line {}", self.linenr())?;
} else {
write!(f, "line {}", self.linenr())?;
}
Ok(())
}
}