use core::marker::PhantomData;
pub trait Scale: Copy + core::fmt::Debug {
const NAME: &'static str;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Bytes;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Chars;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Utf16Units;
impl Scale for Bytes {
const NAME: &'static str = "bytes";
}
impl Scale for Chars {
const NAME: &'static str = "chars";
}
impl Scale for Utf16Units {
const NAME: &'static str = "utf16";
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Offset<S: Scale> {
raw: usize,
_scale: PhantomData<S>,
}
impl<S: Scale> Clone for Offset<S> {
fn clone(&self) -> Self {
*self
}
}
impl<S: Scale> Copy for Offset<S> {}
impl<S: Scale> Offset<S> {
pub const ZERO: Self = Self {
raw: 0,
_scale: PhantomData,
};
#[must_use]
pub const fn new(raw: usize) -> Self {
Self {
raw,
_scale: PhantomData,
}
}
#[must_use]
pub const fn raw(self) -> usize {
self.raw
}
#[must_use]
pub const fn scale_name() -> &'static str {
S::NAME
}
#[must_use]
pub const fn advance(self, by: usize) -> Self {
Self::new(self.raw.saturating_add(by))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Bound {
#[default]
Inclusive,
Exclusive,
}
impl Bound {
#[must_use]
pub const fn admits_forward(self, candidate: usize, anchor: usize) -> bool {
match self {
Self::Inclusive => candidate >= anchor,
Self::Exclusive => candidate > anchor,
}
}
#[must_use]
pub const fn admits_backward(self, candidate: usize, anchor: usize) -> bool {
match self {
Self::Inclusive => candidate <= anchor,
Self::Exclusive => candidate < anchor,
}
}
#[must_use]
pub fn first_matching(self, starts: &[usize], anchor: usize, forward: bool) -> Option<usize> {
if forward {
starts.iter().position(|&s| self.admits_forward(s, anchor))
} else {
starts
.iter()
.rposition(|&s| self.admits_backward(s, anchor))
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Anchored<T, G: PartialEq + Copy> {
value: T,
at: G,
}
impl<T, G: PartialEq + Copy> Anchored<T, G> {
#[must_use]
pub const fn new(value: T, at: G) -> Self {
Self { value, at }
}
#[must_use]
pub fn get(&self, now: G) -> Option<&T> {
(self.at == now).then_some(&self.value)
}
#[must_use]
pub const fn generation(&self) -> G {
self.at
}
#[must_use]
pub const fn get_possibly_stale(&self) -> &T {
&self.value
}
#[must_use]
pub fn is_fresh(&self, now: G) -> bool {
self.at == now
}
}
#[derive(Debug, Clone, Copy)]
pub struct Ruler<'a> {
text: &'a str,
}
impl<'a> Ruler<'a> {
#[must_use]
pub const fn new(text: &'a str) -> Self {
Self { text }
}
#[must_use]
pub const fn end_bytes(&self) -> Offset<Bytes> {
Offset::new(self.text.len())
}
#[must_use]
pub fn end_chars(&self) -> Offset<Chars> {
Offset::new(self.text.chars().count())
}
#[must_use]
pub fn snap(&self, at: Offset<Bytes>) -> Offset<Bytes> {
let mut raw = at.raw().min(self.text.len());
while raw > 0 && !self.text.is_char_boundary(raw) {
raw -= 1;
}
Offset::new(raw)
}
#[must_use]
pub fn to_chars(&self, at: Offset<Bytes>) -> Offset<Chars> {
let b = self.snap(at).raw();
Offset::new(self.text[..b].chars().count())
}
#[must_use]
pub fn to_bytes(&self, at: Offset<Chars>) -> Offset<Bytes> {
self.text
.char_indices()
.nth(at.raw())
.map_or_else(|| self.end_bytes(), |(b, _)| Offset::new(b))
}
#[must_use]
pub fn to_utf16(&self, at: Offset<Bytes>) -> Offset<Utf16Units> {
let b = self.snap(at).raw();
Offset::new(self.text[..b].chars().map(char::len_utf16).sum())
}
}
#[cfg(test)]
mod tests {
use super::*;
const CORPUS: &[&str] = &[
"",
"a",
"hello world",
"héllo", "日本語 foo", "🔥🔥🔥", "a\nb\nc",
"x🔥y",
];
#[test]
fn law_the_three_scales_disagree_and_the_ruler_knows_it() {
let r = Ruler::new("héllo");
let end = r.end_bytes();
assert_eq!(end.raw(), 6, "bytes");
assert_eq!(r.to_chars(end).raw(), 5, "chars");
assert_eq!(r.to_utf16(end).raw(), 5, "utf16");
let r = Ruler::new("🔥");
let end = r.end_bytes();
assert_eq!(end.raw(), 4, "bytes");
assert_eq!(r.to_chars(end).raw(), 1, "chars");
assert_eq!(r.to_utf16(end).raw(), 2, "utf16 — a surrogate pair");
}
#[test]
fn law_byte_char_roundtrip_is_identity_on_boundaries() {
for text in CORPUS {
let r = Ruler::new(text);
for (b, _) in text
.char_indices()
.chain(core::iter::once((text.len(), ' ')))
{
let start = Offset::<Bytes>::new(b);
let round = r.to_bytes(r.to_chars(start));
assert_eq!(round, start, "roundtrip failed at {b} in {text:?}");
}
}
}
#[test]
fn law_conversion_is_monotonic() {
for text in CORPUS {
let r = Ruler::new(text);
let mut prev = 0;
for b in 0..=text.len() {
let c = r.to_chars(Offset::new(b)).raw();
assert!(c >= prev, "non-monotonic at {b} in {text:?}");
prev = c;
}
}
}
#[test]
fn law_snap_is_total_and_idempotent_over_every_byte() {
for text in CORPUS {
let r = Ruler::new(text);
for b in 0..=text.len() + 5 {
let once = r.snap(Offset::new(b));
assert!(
text.is_char_boundary(once.raw()),
"snap({b}) left {once:?} mid-codepoint in {text:?}",
);
assert_eq!(r.snap(once), once, "snap not idempotent at {b}");
}
}
}
#[test]
fn law_snap_never_moves_forward() {
for text in CORPUS {
let r = Ruler::new(text);
for b in 0..=text.len() {
assert!(r.snap(Offset::new(b)).raw() <= b, "moved forward at {b}");
}
}
}
#[test]
fn a_mid_codepoint_offset_does_not_panic() {
let r = Ruler::new("🔥🔥🔥");
assert_eq!(r.snap(Offset::new(1)).raw(), 0);
assert_eq!(r.to_chars(Offset::new(1)).raw(), 0);
assert_eq!(r.to_utf16(Offset::new(1)).raw(), 0);
}
#[test]
fn law_an_inclusive_forward_search_finds_a_match_at_zero() {
let starts = [0_usize, 10, 20];
assert_eq!(
Bound::Inclusive.first_matching(&starts, 0, true),
Some(0),
"an inclusive search from 0 must find the match AT 0",
);
assert_eq!(
Bound::Exclusive.first_matching(&starts, 0, true),
Some(1),
"an exclusive search from 0 must skip it",
);
}
#[test]
fn law_the_two_bounds_differ_only_at_the_anchor() {
let starts = [0_usize, 5, 9];
for anchor in 0..12 {
let inc = Bound::Inclusive.first_matching(&starts, anchor, true);
let exc = Bound::Exclusive.first_matching(&starts, anchor, true);
if starts.contains(&anchor) {
assert_ne!(inc, exc, "must differ when the anchor IS a match");
} else {
assert_eq!(inc, exc, "must agree when the anchor is not a match");
}
}
}
#[test]
fn law_backward_is_the_mirror_of_forward() {
let starts = [0_usize, 5, 9];
assert_eq!(Bound::Inclusive.first_matching(&starts, 5, false), Some(1));
assert_eq!(Bound::Exclusive.first_matching(&starts, 5, false), Some(0));
assert_eq!(
Bound::Exclusive.first_matching(&starts, 0, false),
None,
"nothing lies strictly before the first match",
);
}
#[test]
fn law_no_bound_ever_underflows() {
for b in [Bound::Inclusive, Bound::Exclusive] {
assert_eq!(b.first_matching(&[], 0, true), None);
assert_eq!(b.first_matching(&[], 0, false), None);
let _ = b.first_matching(&[0], 0, true);
let _ = b.first_matching(&[0], 0, false);
}
}
#[test]
fn law_a_value_from_an_older_generation_reads_as_absent() {
let (g0, g1) = (0_u64, 1_u64);
let a = Anchored::new(Offset::<Chars>::new(7), g0);
assert_eq!(a.get(g0), Some(&Offset::new(7)), "fresh");
assert_eq!(
a.get(g1),
None,
"stale reads as absent, not as a wrong number"
);
assert!(!a.is_fresh(g1));
assert_eq!(a.get_possibly_stale().raw(), 7);
}
#[test]
fn law_freshness_is_not_ordering() {
let a = Anchored::new(1_u8, 1_u64);
assert_eq!(a.get(0_u64), None);
}
#[test]
fn offsets_of_different_scales_are_different_types() {
let b = Offset::<Bytes>::new(6);
let c = Offset::<Chars>::new(5);
assert_eq!(Offset::<Bytes>::scale_name(), "bytes");
assert_eq!(Offset::<Chars>::scale_name(), "chars");
assert_eq!(b.raw(), 6);
assert_eq!(c.raw(), 5);
}
}