forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspan.rs
More file actions
96 lines (82 loc) · 1.95 KB
/
Copy pathspan.rs
File metadata and controls
96 lines (82 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use serde::{Deserialize, Serialize};
use std::ops::{Add, AddAssign, Range};
/// An exclusive span of byte offsets in a source file.
#[derive(Serialize, Deserialize, Debug, PartialEq, Copy, Clone, Hash, Eq)]
pub struct Span {
/// A byte offset specifying the inclusive start of a span.
pub start: usize,
/// A byte offset specifying the exclusive end of a span.
pub end: usize,
}
impl Span {
pub fn new(start: usize, end: usize) -> Self {
Span { start, end }
}
pub fn zero() -> Self {
Span { start: 0, end: 0 }
}
pub fn from_pair<S, E>(start_elem: S, end_elem: E) -> Self
where
S: Into<Span>,
E: Into<Span>,
{
let start_span: Span = start_elem.into();
let end_span: Span = end_elem.into();
Self {
start: start_span.start,
end: end_span.end,
}
}
}
pub trait Spanned {
fn span(&self) -> Span;
}
impl Add for Span {
type Output = Self;
fn add(self, other: Self) -> Self {
use std::cmp::{max, min};
Self {
start: min(self.start, other.start),
end: max(self.end, other.end),
}
}
}
impl Add<Option<Span>> for Span {
type Output = Self;
fn add(self, other: Option<Span>) -> Self {
if let Some(other) = other {
self + other
} else {
self
}
}
}
impl<'a, T> Add<Option<&'a T>> for Span
where
Span: Add<&'a T, Output = Self>,
{
type Output = Self;
fn add(self, other: Option<&'a T>) -> Self {
if let Some(other) = other {
self + other
} else {
self
}
}
}
impl<T> AddAssign<T> for Span
where
Span: Add<T, Output = Self>,
{
fn add_assign(&mut self, other: T) {
*self = *self + other
}
}
impl From<Span> for Range<usize> {
fn from(span: Span) -> Self {
Range {
start: span.start,
end: span.end,
}
}
}