-
Notifications
You must be signed in to change notification settings - Fork 60
Introduce ArcVec<T> to improve Copy performance of messages #2015
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+126
−1
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -8,13 +8,17 @@ | |
// the Business Source License, use of this software will be governed | ||
// by the Apache License, Version 2.0. | ||
|
||
use core::fmt; | ||
use std::marker::PhantomData; | ||
use std::mem; | ||
use std::ops::Deref; | ||
use std::sync::Arc; | ||
|
||
use bytes::{Buf, BufMut, Bytes, BytesMut}; | ||
use downcast_rs::{impl_downcast, DowncastSync}; | ||
use serde::de::{DeserializeOwned, Error as DeserializationError}; | ||
use serde::ser::Error as SerializationError; | ||
use serde::ser::SerializeSeq; | ||
use serde::{Deserialize, Serialize}; | ||
use tracing::error; | ||
|
||
|
@@ -395,6 +399,126 @@ pub fn decode_from_flexbuffers<T: DeserializeOwned, B: Buf>( | |
} | ||
} | ||
|
||
/// [`ArcVec`] mainly used by `message` types to improve | ||
/// cloning of messages. | ||
/// | ||
/// It can replace [`Vec<T>`] most of the time in all structures | ||
/// that need to be serialized over the wire. | ||
/// | ||
/// Internally it keeps the data inside an [`Arc<[T]>`] | ||
#[derive(Debug)] | ||
pub struct ArcVec<T> { | ||
inner: Arc<[T]>, | ||
} | ||
|
||
impl<T> Deref for ArcVec<T> { | ||
type Target = [T]; | ||
fn deref(&self) -> &Self::Target { | ||
&self.inner | ||
} | ||
} | ||
|
||
impl<T> serde::Serialize for ArcVec<T> | ||
where | ||
T: serde::Serialize, | ||
{ | ||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> | ||
where | ||
S: serde::Serializer, | ||
{ | ||
let mut seq = serializer.serialize_seq(Some(self.len()))?; | ||
for elem in self.iter() { | ||
seq.serialize_element(elem)?; | ||
} | ||
|
||
seq.end() | ||
} | ||
} | ||
|
||
impl<'de, T> serde::Deserialize<'de> for ArcVec<T> | ||
where | ||
T: serde::Deserialize<'de>, | ||
{ | ||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> | ||
where | ||
D: serde::Deserializer<'de>, | ||
{ | ||
deserializer.deserialize_seq(ArcVecVisitor::default()) | ||
} | ||
} | ||
|
||
struct ArcVecVisitor<T> { | ||
_phantom: PhantomData<T>, | ||
} | ||
|
||
impl<T> Default for ArcVecVisitor<T> { | ||
fn default() -> Self { | ||
Self { | ||
_phantom: PhantomData, | ||
} | ||
} | ||
} | ||
|
||
impl<'de, T> serde::de::Visitor<'de> for ArcVecVisitor<T> | ||
where | ||
T: serde::Deserialize<'de>, | ||
{ | ||
type Value = ArcVec<T>; | ||
|
||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { | ||
write!(formatter, "expecting an array") | ||
} | ||
|
||
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> | ||
where | ||
A: serde::de::SeqAccess<'de>, | ||
{ | ||
let mut vec: Vec<T> = Vec::with_capacity(seq.size_hint().unwrap_or_default()); | ||
while let Some(value) = seq.next_element()? { | ||
vec.push(value); | ||
} | ||
|
||
Ok(vec.into()) | ||
Comment on lines
+476
to
+481
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Once rust-lang/rust#129401 lands with Rust 1.82, we can avoid the extra allocation of a |
||
} | ||
} | ||
|
||
impl<T> Clone for ArcVec<T> { | ||
fn clone(&self) -> Self { | ||
Self { | ||
inner: Arc::clone(&self.inner), | ||
} | ||
} | ||
} | ||
|
||
impl<T> From<ArcVec<T>> for Arc<[T]> { | ||
fn from(value: ArcVec<T>) -> Self { | ||
value.inner | ||
} | ||
} | ||
|
||
impl<T> From<ArcVec<T>> for Vec<T> | ||
where | ||
T: Clone, | ||
{ | ||
fn from(value: ArcVec<T>) -> Self { | ||
Vec::from_iter(value.iter().cloned()) | ||
} | ||
} | ||
|
||
impl<T> From<Vec<T>> for ArcVec<T> { | ||
fn from(value: Vec<T>) -> Self { | ||
Self { | ||
inner: value.into(), | ||
} | ||
} | ||
} | ||
|
||
impl<T> From<Arc<[T]>> for ArcVec<T> { | ||
fn from(value: Arc<[T]>) -> Self { | ||
Self { inner: value } | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use bytes::Bytes; | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there a benefit over
Arc<Vec<T>>
? If I understand the API correctly, then converting fromVec<T>
into anArc<[T]>
requires an extra allocation whereas the former adds another level of pointer indirection.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The only reason that I used
Arc<[T]>
instead ofArc<Vec<T>>
is becauseArc<[T]>
is very common type in Bifrost.In Bifrost the
Loglet::enqueue_batch
method accepts anArc<[Record]>
as a param, but when we actually need to send this over the wire (in case of replicated loglet client, or to log servers), the message data types are usingVec<Record>
type. This requires copying all records to build, which can be quite heavy in case we sending the same set of records to multiple log servers for example.In other wards, the most common usage patter is to build an ArcVec from an
Arc<[Record]>
not from Vec.That being said, I should actually
Arc<[T]>::from(vec)
instead offrom_iter
to build the ArcVec from a Vec (in case of deseralization) to avoid one extra allocation. as per hereThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the explanation.
I think that
Arc<[T]>::from(vec)
will also require one additional allocation.Once this becomes a problem and measurable, we can revisit it.