microsoft/qdk

Public

mirrored from https://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
6315a979be8df18c2bdfe93ba63edd2a28063e6c

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

compiler/qsc_data_structures/src/span.rs

75lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4use miette::SourceSpan;
5use std::{
6 fmt::{self, Display, Formatter},
7 ops::{Add, Bound, Index, RangeBounds},
8};
9
10/// A region between two offsets in an array. Spans are the half-open interval `[lo, hi)`.
11#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
12pub struct Span {
13 /// The smallest offset contained in the span.
14 pub lo: usize,
15 /// The next offset after the largest offset contained in the span.
16 pub hi: usize,
17}
18
19impl Add<usize> for Span {
20 type Output = Self;
21
22 fn add(self, rhs: usize) -> Self::Output {
23 Self {
24 lo: self.lo + rhs,
25 hi: self.hi + rhs,
26 }
27 }
28}
29
30impl Display for Span {
31 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
32 write!(f, "[{}-{}]", self.lo, self.hi)?;
33 Ok(())
34 }
35}
36
37impl Index<Span> for str {
38 type Output = str;
39
40 fn index(&self, index: Span) -> &Self::Output {
41 &self[index.lo..index.hi]
42 }
43}
44
45impl Index<&Span> for str {
46 type Output = str;
47
48 fn index(&self, index: &Span) -> &Self::Output {
49 &self[index.lo..index.hi]
50 }
51}
52
53impl Index<Span> for String {
54 type Output = str;
55
56 fn index(&self, index: Span) -> &Self::Output {
57 &self[index.lo..index.hi]
58 }
59}
60
61impl RangeBounds<usize> for &Span {
62 fn start_bound(&self) -> Bound<&usize> {
63 Bound::Included(&self.lo)
64 }
65
66 fn end_bound(&self) -> Bound<&usize> {
67 Bound::Excluded(&self.hi)
68 }
69}
70
71impl From<Span> for SourceSpan {
72 fn from(value: Span) -> Self {
73 Self::from(value.lo..value.hi)
74 }
75}
76