Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 39 additions & 4 deletions attributed_text/src/attribute_segments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,15 +263,23 @@ impl<'w, 'a, T: Debug + TextStorage, Attr: Debug> AttributeSegments<'w, 'a, T, A
impl<T: Debug + TextStorage, Attr: Debug> Iterator for AttributeSegments<'_, '_, T, Attr> {
type Item = Range<usize>;

fn size_hint(&self) -> (usize, Option<usize>) {
// Remaining segments are remaining adjacent boundary pairs: [i, i + 1).
let remaining = self
.workspace
.boundaries
.len()
.saturating_sub(self.index + 1);
(remaining, Some(remaining))
}

fn next(&mut self) -> Option<Self::Item> {
while self.index + 1 < self.workspace.boundaries.len() {
if self.index + 1 < self.workspace.boundaries.len() {
self.update_active_for_boundary(self.index);
let start = self.workspace.boundaries[self.index] as usize;
let end = self.workspace.boundaries[self.index + 1] as usize;
self.index += 1;
if start == end {
continue;
}
debug_assert!(start < end, "boundaries are sorted + deduped");

return Some(start..end);
}
Expand All @@ -280,6 +288,16 @@ impl<T: Debug + TextStorage, Attr: Debug> Iterator for AttributeSegments<'_, '_,
}
}

impl<T: Debug + TextStorage, Attr: Debug> ExactSizeIterator for AttributeSegments<'_, '_, T, Attr> {
fn len(&self) -> usize {
// Remaining segments are remaining adjacent boundary pairs: [i, i + 1).
self.workspace
.boundaries
.len()
.saturating_sub(self.index + 1)
}
}

/// A view of the attribute spans active over a particular segment.
///
/// Provides iteration in both application order (ascending span id) and reverse
Expand Down Expand Up @@ -356,6 +374,23 @@ mod tests {
assert_eq!(segments.next(), None);
}

#[test]
fn size_hint_tracks_remaining_segments() {
let mut at = AttributedText::new("hello");
at.apply_attribute(TextRange::new(at.text(), 1..3).unwrap(), Color::Red);
let mut workspace = AttributeSegmentsWorkspace::new();
let mut segments = workspace.segments(&at);

assert_eq!(segments.size_hint(), (3, Some(3)));
assert_eq!(segments.next(), Some(0..1));
assert_eq!(segments.size_hint(), (2, Some(2)));
assert_eq!(segments.next(), Some(1..3));
assert_eq!(segments.size_hint(), (1, Some(1)));
assert_eq!(segments.next(), Some(3..5));
assert_eq!(segments.size_hint(), (0, Some(0)));
assert_eq!(segments.next(), None);
}

#[test]
fn single_full_span() {
let mut at = AttributedText::new("hello");
Expand Down