From 0b48b27024cf0b2247d0c3110aa622f453deda2b Mon Sep 17 00:00:00 2001 From: Riccardo Mazzarini Date: Sun, 28 Jan 2024 11:49:03 +0100 Subject: [PATCH] implement `Encode` for `Backlog` --- src/backlog.rs | 102 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/src/backlog.rs b/src/backlog.rs index bcaa180..119905e 100644 --- a/src/backlog.rs +++ b/src/backlog.rs @@ -111,6 +111,16 @@ impl InsertionsBacklog { self.insertions.insert(offset, insertion); } + + #[inline(always)] + fn iter(&self) -> impl Iterator + '_ { + self.insertions.iter() + } + + #[inline(always)] + fn len(&self) -> usize { + self.insertions.len() + } } /// Stores the backlogged [`Deletion`]s of a particular replica. @@ -159,6 +169,16 @@ impl DeletionsBacklog { self.deletions.insert(offset, deletion); } + + #[inline(always)] + fn iter(&self) -> impl Iterator + '_ { + self.deletions.iter() + } + + #[inline(always)] + fn len(&self) -> usize { + self.deletions.len() + } } /// An iterator over the backlogged deletions that are ready to be @@ -282,3 +302,85 @@ impl Iterator for BackloggedInsertions<'_> { } impl core::iter::FusedIterator for BackloggedInsertions<'_> {} + +#[cfg(feature = "encode")] +mod encode { + use super::*; + use crate::encode::Encode; + + impl Encode for Backlog { + #[inline] + fn encode(&self, buf: &mut Vec) { + for (id, insertions) in &self.insertions { + ReplicaIdInsertions::new(*id, insertions).encode(buf); + } + for (id, deletions) in &self.deletions { + ReplicaIdDeletions::new(*id, deletions).encode(buf); + } + } + } + + struct ReplicaIdInsertions<'a> { + replica_id: ReplicaId, + insertions: &'a InsertionsBacklog, + } + + impl<'a> ReplicaIdInsertions<'a> { + #[inline] + fn new( + replica_id: ReplicaId, + insertions: &'a InsertionsBacklog, + ) -> Self { + Self { replica_id, insertions } + } + } + + impl Encode for ReplicaIdInsertions<'_> { + #[inline] + fn encode(&self, buf: &mut Vec) { + self.replica_id.encode(buf); + + (self.insertions.len() as u64).encode(buf); + + for insertion in self.insertions.iter() { + insertion.anchor().encode(buf); + let range = insertion.text().temporal_range(); + range.start.encode(buf); + range.len().encode(buf); + insertion.run_ts().encode(buf); + insertion.lamport_ts().encode(buf); + } + } + } + + struct ReplicaIdDeletions<'a> { + replica_id: ReplicaId, + deletions: &'a DeletionsBacklog, + } + + impl<'a> ReplicaIdDeletions<'a> { + #[inline] + fn new( + replica_id: ReplicaId, + deletions: &'a DeletionsBacklog, + ) -> Self { + Self { replica_id, deletions } + } + } + + impl Encode for ReplicaIdDeletions<'_> { + #[inline] + fn encode(&self, buf: &mut Vec) { + self.replica_id.encode(buf); + + (self.deletions.len() as u64).encode(buf); + + for deletion in self.deletions.iter() { + deletion.start().encode(buf); + deletion.end().encode(buf); + deletion.version_map().encode(buf); + deletion.deletion_ts().encode(buf); + } + } + } +}