Add Row::overall_indices

This commit is contained in:
Alexandre Bury 2018-02-16 16:56:25 -08:00
parent 7772cd146d
commit 0ff08f3a9f
2 changed files with 32 additions and 5 deletions

View File

@ -1,5 +1,5 @@
use super::Segment; use super::Segment;
use utils::span::{Span, AsSpannedStr}; use utils::span::{AsSpannedStr, IndexedCow, Span};
/// A list of segments representing a row of text /// A list of segments representing a row of text
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
@ -23,4 +23,17 @@ impl Row {
.map(|seg| seg.resolve(source.clone())) .map(|seg| seg.resolve(source.clone()))
.collect() .collect()
} }
/// Returns indices in the source string, if possible.
///
/// Returns overall `(start, end)`, or `None` if the segments are owned.
pub fn overall_indices<S>(&self, spans: &[S]) -> Option<(usize, usize)>
where
S: AsRef<IndexedCow>,
{
let (start, _) = self.segments.get(0)?.source_indices(spans)?;
let (_, end) = self.segments.last()?.source_indices(spans)?;
Some((start, end))
}
} }

View File

@ -1,4 +1,4 @@
use utils::span::{SpannedStr, Span, SpannedText}; use utils::span::{Span, SpannedStr, SpannedText, IndexedCow};
/// Refers to a part of a span /// Refers to a part of a span
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@ -17,9 +17,7 @@ pub struct Segment {
impl Segment { impl Segment {
/// Resolve this segment to a string slice and an attribute. /// Resolve this segment to a string slice and an attribute.
pub fn resolve<'a, T>( pub fn resolve<'a, T>(&self, source: SpannedStr<'a, T>) -> Span<'a, T> {
&self, source: SpannedStr<'a, T>
) -> Span<'a, T> {
let span = &source.spans_raw()[self.span_id]; let span = &source.spans_raw()[self.span_id];
let content = span.content.resolve(source.source()); let content = span.content.resolve(source.source());
@ -43,4 +41,20 @@ impl Segment {
content content
} }
/// Returns indices in the source string, if possible.
///
/// Returns `(start, end)`, or `None` if the target span is an owned string.
pub fn source_indices<S>(&self, spans: &[S]) -> Option<(usize, usize)>
where
S: AsRef<IndexedCow>,
{
let span = spans[self.span_id].as_ref();
if let &IndexedCow::Borrowed { start, .. } = span {
Some((self.start + start, self.end + start))
} else {
None
}
}
} }