From 2bb07d6a4e1292b61b8ff550c19fcf9dafbc1a7a Mon Sep 17 00:00:00 2001 From: Ivan Enderlin Date: Mon, 18 Mar 2024 12:19:24 +0100 Subject: [PATCH] feat(sdk): Implement `LinkedChunk::items`. This patch implements the new `LinkedChunk::items` method that returns a forward iterator over items. --- .../src/event_cache/linked_chunk.rs | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/crates/matrix-sdk/src/event_cache/linked_chunk.rs b/crates/matrix-sdk/src/event_cache/linked_chunk.rs index 5173f45bc..029d7c846 100644 --- a/crates/matrix-sdk/src/event_cache/linked_chunk.rs +++ b/crates/matrix-sdk/src/event_cache/linked_chunk.rs @@ -406,6 +406,19 @@ impl LinkedChunk { .expect("`iter_items_from` cannot fail because at least one empty chunk must exist") } + /// Iterate over the items, forward. + /// + /// It iterates from the first to the last item. + pub fn items(&self) -> impl Iterator { + let first_chunk = self.first_chunk(); + let ChunkContent::Items(items) = first_chunk.content() else { + unreachable!("The first chunk is necessarily an `Items`"); + }; + + self.items_from(ItemPosition(ChunkIdentifierGenerator::FIRST_IDENTIFIER, items.len())) + .expect("`items` cannot fail because at least one empty chunk must exist") + } + /// Iterate over the items, starting from `position`, backward. /// /// It iterates from the item at `position` to the first item. @@ -447,6 +460,11 @@ impl LinkedChunk { .flatten()) } + /// Get the first chunk, as an immutable reference. + fn first_chunk(&self) -> &Chunk { + unsafe { self.first.as_ref() } + } + /// Get the latest chunk, as an immutable reference. fn latest_chunk(&self) -> &Chunk { unsafe { self.last.unwrap_or(self.first).as_ref() } @@ -1165,6 +1183,23 @@ mod tests { assert_matches!(iterator.next(), None); } + #[test] + fn test_items() { + let mut linked_chunk = LinkedChunk::::new(); + linked_chunk.push_items_back(['a', 'b']); + linked_chunk.push_gap_back(()); + linked_chunk.push_items_back(['c', 'd', 'e']); + + let mut iterator = linked_chunk.items(); + + assert_matches!(iterator.next(), Some((ItemPosition(ChunkIdentifier(0), 1), 'a'))); + assert_matches!(iterator.next(), Some((ItemPosition(ChunkIdentifier(0), 0), 'b'))); + assert_matches!(iterator.next(), Some((ItemPosition(ChunkIdentifier(2), 1), 'c'))); + assert_matches!(iterator.next(), Some((ItemPosition(ChunkIdentifier(2), 0), 'd'))); + assert_matches!(iterator.next(), Some((ItemPosition(ChunkIdentifier(3), 0), 'e'))); + assert_matches!(iterator.next(), None); + } + #[test] fn test_ritems_from() -> Result<(), LinkedChunkError> { let mut linked_chunk = LinkedChunk::::new();