Skip to main content

source_tools/
source_offset.rs

1use crate::{Cursor, SourceToken, Span};
2
3/// A byte position in source text.
4#[repr(transparent)]
5#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
6#[cfg_attr(feature = "serde", derive(serde::Serialize))]
7pub struct SourceOffset(pub u32);
8
9impl SourceOffset {
10	/// A synthetic source position.
11	pub const DUMMY: Self = Self(u32::MAX);
12
13	/// Start of source text.
14	pub const ZERO: Self = Self(0);
15
16	/// Returns span occupied by `token` at this offset.
17	pub fn as_span<T: SourceToken>(&self, token: T) -> Span {
18		Span::new(*self, Self(self.0 + token.len()))
19	}
20
21	/// Places `token` at this offset.
22	pub const fn as_cursor<T>(&self, token: T) -> Cursor<T> {
23		Cursor::new(*self, token)
24	}
25}
26
27#[cfg(feature = "miette")]
28impl From<SourceOffset> for miette::SourceOffset {
29	fn from(value: SourceOffset) -> Self {
30		Self::from(value.0 as usize)
31	}
32}
33
34impl PartialEq<u32> for SourceOffset {
35	fn eq(&self, other: &u32) -> bool {
36		self.0 == *other
37	}
38}
39
40impl From<SourceOffset> for usize {
41	fn from(value: SourceOffset) -> Self {
42		value.0 as usize
43	}
44}