Skip to content
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

add Bytes::is_unique #643

Merged
merged 5 commits into from
Jan 19, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,42 @@ impl Bytes {
self.len == 0
}

/// Returns true if this is the only reference to the data.
///
/// Always returns false if the data is backed by a static slice.
///
/// # Examples
///
/// ```
/// use bytes::Bytes;
///
/// let a = Bytes::from(vec![1, 2, 3]);
/// assert!(a.is_unique());
/// let b = a.clone();
/// assert!(!a.is_unique());
/// ```
pub fn is_unique(&self) -> bool {
if core::ptr::eq(self.vtable, &PROMOTABLE_EVEN_VTABLE)
|| core::ptr::eq(self.vtable, &PROMOTABLE_ODD_VTABLE)
{
let shared = self.data.load(Ordering::Acquire);
let kind = shared as usize & KIND_MASK;

if kind == KIND_ARC {
let ref_cnt = unsafe { (*shared.cast::<Shared>()).ref_cnt.load(Ordering::Relaxed) };
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am unsure if Relaxed is correct here

ref_cnt == 1
} else {
true
}
} else if core::ptr::eq(self.vtable, &SHARED_VTABLE) {
let shared = self.data.load(Ordering::Acquire);
let ref_cnt = unsafe { (*shared.cast::<Shared>()).ref_cnt.load(Ordering::Relaxed) };
ref_cnt == 1
} else {
false
}
}

/// Creates `Bytes` instance from slice, by copying it.
pub fn copy_from_slice(data: &[u8]) -> Self {
data.to_vec().into()
Expand Down