//! Byte spans into the source text. //! //! Every token and every AST node carries one, which is what lets a consumer //! that is not the formatter — an LSP server, a `verilog_format: off` fence, a //! `--lines M-N` range — go from a node back to the exact bytes it came from. /// A half-open byte range `[start, end)` into the source text. /// /// Offsets are **bytes**, not characters, so slicing `source[range]` is exact /// for multi-byte UTF-8. See `docs/features/spans/README.md` for the /// conventions (in particular: a node's span is its code extent; comments are /// not part of it and carry spans of their own). #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct TextRange { /// Byte offset of the first byte. pub start: u32, /// Byte offset one past the last byte. pub end: u32, } impl TextRange { /// A range from `start` to `end`; `end` is clamped up to `start` so a /// range is never inverted. pub fn new(start: u32, end: u32) -> Self { TextRange { start, end: end.max(start) } } /// The empty range at `offset`. pub fn empty(offset: u32) -> Self { TextRange { start: offset, end: offset } } /// Length in bytes. pub fn len(&self) -> u32 { self.end - self.start } /// True when the range covers no bytes. pub fn is_empty(&self) -> bool { self.start == self.end } /// True when `offset` falls inside the range (`end` is excluded). pub fn contains(&self, offset: u32) -> bool { self.start <= offset && offset < self.end } /// The range as a `usize` range, for slicing the source text. pub fn as_range(&self) -> std::ops::Range { self.start as usize..self.end as usize } } #[cfg(test)] mod tests { use super::*; #[test] fn basics() { let r = TextRange::new(3, 7); assert_eq!(r.len(), 4); assert!(!r.is_empty()); assert!(r.contains(3)); assert!(r.contains(6)); assert!(!r.contains(7), "end is excluded"); assert!(!r.contains(2)); assert_eq!(&"0123456789"[r.as_range()], "3456"); } #[test] fn empty_range_contains_nothing() { let r = TextRange::empty(5); assert!(r.is_empty()); assert_eq!(r.len(), 0); assert!(!r.contains(5)); } #[test] fn an_inverted_range_is_clamped_to_empty() { let r = TextRange::new(9, 4); assert_eq!((r.start, r.end), (9, 9)); } }