css_lexer/
source_offset.rs

1use crate::{Cursor, Span, Token};
2
3/// Represents a position in the underlying source.
4///
5/// This is just a [u32] but wrapped in a newtype struct to help differentiate it from other [u32s][u32].
6#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize))]
8pub struct SourceOffset(pub u32);
9
10impl SourceOffset {
11	/// Represents a fake SourceOffset with [u32::MAX] as the number.
12	pub const DUMMY: SourceOffset = SourceOffset(u32::MAX);
13	pub const ZERO: SourceOffset = SourceOffset(0);
14
15	/// Providing a [Token] can produce a [Span].
16	pub fn as_span(&self, t: Token) -> Span {
17		Span::new(*self, Self(self.0 + t.len()))
18	}
19
20	/// Providing a [Token] can produce a [Cursor], with the token embedded. This is a convenience wrapper around
21	/// `Cursor::new(source_offset, token);`
22	pub fn as_cursor(&self, t: Token) -> Cursor {
23		Cursor::new(*self, t)
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}