summaryrefslogtreecommitdiff
path: root/vendor/beef/src
diff options
context:
space:
mode:
authormo khan <mo@mokhan.ca>2025-07-02 18:36:06 -0600
committermo khan <mo@mokhan.ca>2025-07-02 18:36:06 -0600
commit8cdfa445d6629ffef4cb84967ff7017654045bc2 (patch)
tree22f0b0907c024c78d26a731e2e1f5219407d8102 /vendor/beef/src
parent4351c74c7c5f97156bc94d3a8549b9940ac80e3f (diff)
chore: add vendor directory
Diffstat (limited to 'vendor/beef/src')
-rw-r--r--vendor/beef/src/generic.rs553
-rw-r--r--vendor/beef/src/lean.rs69
-rw-r--r--vendor/beef/src/lib.rs285
-rw-r--r--vendor/beef/src/serde.rs149
-rw-r--r--vendor/beef/src/traits.rs175
-rw-r--r--vendor/beef/src/wide.rs42
6 files changed, 1273 insertions, 0 deletions
diff --git a/vendor/beef/src/generic.rs b/vendor/beef/src/generic.rs
new file mode 100644
index 00000000..1d7fa2da
--- /dev/null
+++ b/vendor/beef/src/generic.rs
@@ -0,0 +1,553 @@
+//! This module contains the actual, albeit generic, implementaiton of the `Cow`,
+//! and the traits that are available to it.
+
+use alloc::borrow::{Borrow, Cow as StdCow};
+use alloc::string::String;
+use alloc::vec::Vec;
+use core::cmp::Ordering;
+use core::fmt;
+use core::hash::{Hash, Hasher};
+use core::marker::PhantomData;
+use core::mem::ManuallyDrop;
+use core::ptr::NonNull;
+
+#[cfg(target_pointer_width = "64")]
+use crate::lean::internal::Lean;
+use crate::traits::{Beef, Capacity};
+use crate::wide::internal::Wide;
+
+/// A clone-on-write smart pointer, mostly compatible with [`std::borrow::Cow`](https://doc.rust-lang.org/std/borrow/enum.Cow.html).
+///
+/// This type is using a generic `U: Capacity`. Use either [`beef::Cow`](../type.Cow.html) or [`beef::lean::Cow`](../lean/type.Cow.html) in your code.
+pub struct Cow<'a, T: Beef + ?Sized + 'a, U: Capacity> {
+ /// Pointer to data
+ ptr: NonNull<T::PointerT>,
+
+ /// This usize contains length, but it may contain other
+ /// information pending on impl of `Capacity`, and must therefore
+ /// always go through `U::len` or `U::unpack`
+ fat: usize,
+
+ /// Capacity field. For `beef::lean::Cow` this is 0-sized!
+ cap: U::Field,
+
+ /// Lifetime marker
+ marker: PhantomData<&'a T>,
+}
+
+impl<T, U> Cow<'_, T, U>
+where
+ T: Beef + ?Sized,
+ U: Capacity,
+{
+ /// Owned data.
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// use beef::Cow;
+ ///
+ /// let owned: Cow<str> = Cow::owned("I own my content".to_string());
+ /// ```
+ #[inline]
+ pub fn owned(val: T::Owned) -> Self {
+ let (ptr, fat, cap) = T::owned_into_parts::<U>(val);
+
+ Cow {
+ ptr,
+ fat,
+ cap,
+ marker: PhantomData,
+ }
+ }
+}
+
+impl<'a, T, U> Cow<'a, T, U>
+where
+ T: Beef + ?Sized,
+ U: Capacity,
+{
+ /// Borrowed data.
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// use beef::Cow;
+ ///
+ /// let borrowed: Cow<str> = Cow::borrowed("I'm just a borrow");
+ /// ```
+ #[inline]
+ pub fn borrowed(val: &'a T) -> Self {
+ let (ptr, fat, cap) = T::ref_into_parts::<U>(val);
+
+ Cow {
+ ptr,
+ fat,
+ cap,
+ marker: PhantomData,
+ }
+ }
+
+ /// Extracts the owned data.
+ ///
+ /// Clones the data if it is not already owned.
+ #[inline]
+ pub fn into_owned(self) -> T::Owned {
+ let cow = ManuallyDrop::new(self);
+
+ match cow.capacity() {
+ Some(capacity) => unsafe { T::owned_from_parts::<U>(cow.ptr, cow.fat, capacity) },
+ None => unsafe { &*T::ref_from_parts::<U>(cow.ptr, cow.fat) }.to_owned(),
+ }
+ }
+
+ /// Extracts borrowed data.
+ ///
+ /// Panics: If the data is owned.
+ #[inline]
+ pub fn unwrap_borrowed(self) -> &'a T {
+ if self.capacity().is_some() {
+ panic!("Can not turn owned beef::Cow into a borrowed value")
+ }
+ unsafe { &*T::ref_from_parts::<U>(self.ptr, self.fat) }
+ }
+
+ /// Returns `true` if data is borrowed or had no capacity.
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// use beef::Cow;
+ ///
+ /// let borrowed: Cow<str> = Cow::borrowed("Borrowed");
+ /// let no_capacity: Cow<str> = Cow::owned(String::new());
+ /// let owned: Cow<str> = Cow::owned(String::from("Owned"));
+ ///
+ /// assert_eq!(borrowed.is_borrowed(), true);
+ /// assert_eq!(no_capacity.is_borrowed(), true);
+ /// assert_eq!(owned.is_borrowed(), false);
+ /// ```
+ #[inline]
+ pub fn is_borrowed(&self) -> bool {
+ self.capacity().is_none()
+ }
+
+ /// Returns `true` if data is owned and has non-0 capacity.
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// use beef::Cow;
+ ///
+ /// let borrowed: Cow<str> = Cow::borrowed("Borrowed");
+ /// let no_capacity: Cow<str> = Cow::owned(String::new());
+ /// let owned: Cow<str> = Cow::owned(String::from("Owned"));
+ ///
+ /// assert_eq!(borrowed.is_owned(), false);
+ /// assert_eq!(no_capacity.is_owned(), false);
+ /// assert_eq!(owned.is_owned(), true);
+ /// ```
+ #[inline]
+ pub fn is_owned(&self) -> bool {
+ self.capacity().is_some()
+ }
+
+ /// Internal convenience method for casting `ptr` into a `&T`
+ #[inline]
+ fn borrow(&self) -> &T {
+ unsafe { &*T::ref_from_parts::<U>(self.ptr, self.fat) }
+ }
+
+ #[inline]
+ fn capacity(&self) -> Option<U::NonZero> {
+ U::maybe(self.fat, self.cap)
+ }
+}
+
+impl<'a> Cow<'a, str, Wide> {
+ /// Borrowed data.
+ ///
+ /// This is functionally identical to [`borrow`](./generic/struct.Cow.html#method.borrow).
+ /// We use impl specialization to allow this function to be `const`.
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// use beef::Cow;
+ ///
+ /// const HELLO: Cow<str> = Cow::const_str("Hello");
+ /// ```
+ pub const fn const_str(val: &'a str) -> Self {
+ Cow {
+ // We are casting *const T to *mut T, however for all borrowed values
+ // this raw pointer is only ever dereferenced back to &T.
+ ptr: unsafe { NonNull::new_unchecked(val.as_ptr() as *mut u8) },
+ fat: val.len(),
+ cap: None,
+ marker: PhantomData,
+ }
+ }
+}
+
+#[cfg(target_pointer_width = "64")]
+impl<'a> Cow<'a, str, Lean> {
+ /// Borrowed data.
+ ///
+ /// This is functionally identical to [`borrow`](./generic/struct.Cow.html#method.borrow).
+ /// We use impl specialization to allow this function to be `const`.
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// use beef::lean::Cow;
+ ///
+ /// const HELLO: Cow<str> = Cow::const_str("Hello");
+ /// ```
+ pub const fn const_str(val: &'a str) -> Self {
+ Cow {
+ // We are casting *const T to *mut T, however for all borrowed values
+ // this raw pointer is only ever dereferenced back to &T.
+ ptr: unsafe { NonNull::new_unchecked(val.as_ptr() as *mut u8) },
+ fat: Lean::mask_len(val.len()),
+ cap: Lean,
+ marker: PhantomData,
+ }
+ }
+}
+
+// This requires nightly:
+// https://github.com/rust-lang/rust/issues/57563
+#[cfg(feature = "const_fn")]
+impl<'a, T> Cow<'a, [T], Wide>
+where
+ T: Clone,
+{
+ /// Borrowed data.
+ ///
+ /// This is functionally identical to [`borrow`](./generic/struct.Cow.html#method.borrow).
+ /// We use impl specialization to allow this function to be `const`.
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// use beef::Cow;
+ ///
+ /// const HELLO: Cow<[u8]> = Cow::const_slice(&[1, 2, 3]);
+ /// ```
+ pub const fn const_slice(val: &'a [T]) -> Self {
+ Cow {
+ // We are casting *const T to *mut T, however for all borrowed values
+ // this raw pointer is only ever dereferenced back to &T.
+ ptr: unsafe { NonNull::new_unchecked(val.as_ptr() as *mut T) },
+ fat: val.len(),
+ cap: None,
+ marker: PhantomData,
+ }
+ }
+}
+
+// This requires nightly:
+// https://github.com/rust-lang/rust/issues/57563
+#[cfg(all(feature = "const_fn", target_pointer_width = "64"))]
+impl<'a, T> Cow<'a, [T], Lean>
+where
+ T: Clone,
+{
+ /// Borrowed data.
+ ///
+ /// This i functionally identical to [`borrow`](./generic/struct.Cow.html#method.borrow).
+ /// We use impl specialization to allow this function to be `const`.
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// use beef::lean::Cow;
+ ///
+ /// const HELLO: Cow<[u8]> = Cow::const_slice(&[1, 2, 3]);
+ /// ```
+ pub const fn const_slice(val: &'a [T]) -> Self {
+ Cow {
+ // We are casting *const T to *mut T, however for all borrowed values
+ // this raw pointer is only ever dereferenced back to &T.
+ ptr: unsafe { NonNull::new_unchecked(val.as_ptr() as *mut T) },
+ fat: Lean::mask_len(val.len()),
+ cap: Lean,
+ marker: PhantomData,
+ }
+ }
+}
+
+impl<T, U> Hash for Cow<'_, T, U>
+where
+ T: Hash + Beef + ?Sized,
+ U: Capacity,
+{
+ #[inline]
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.borrow().hash(state)
+ }
+}
+
+impl<'a, T, U> Default for Cow<'a, T, U>
+where
+ T: Beef + ?Sized,
+ U: Capacity,
+ &'a T: Default,
+{
+ #[inline]
+ fn default() -> Self {
+ Cow::borrowed(Default::default())
+ }
+}
+
+impl<T, U> Eq for Cow<'_, T, U>
+where
+ T: Eq + Beef + ?Sized,
+ U: Capacity,
+{
+}
+
+impl<A, B, U, V> PartialOrd<Cow<'_, B, V>> for Cow<'_, A, U>
+where
+ A: Beef + ?Sized + PartialOrd<B>,
+ B: Beef + ?Sized,
+ U: Capacity,
+ V: Capacity,
+{
+ #[inline]
+ fn partial_cmp(&self, other: &Cow<'_, B, V>) -> Option<Ordering> {
+ PartialOrd::partial_cmp(self.borrow(), other.borrow())
+ }
+}
+
+impl<T, U> Ord for Cow<'_, T, U>
+where
+ T: Ord + Beef + ?Sized,
+ U: Capacity,
+{
+ #[inline]
+ fn cmp(&self, other: &Self) -> Ordering {
+ Ord::cmp(self.borrow(), other.borrow())
+ }
+}
+
+impl<'a, T, U> From<&'a T> for Cow<'a, T, U>
+where
+ T: Beef + ?Sized,
+ U: Capacity,
+{
+ #[inline]
+ fn from(val: &'a T) -> Self {
+ Cow::borrowed(val)
+ }
+}
+
+impl<U> From<String> for Cow<'_, str, U>
+where
+ U: Capacity,
+{
+ #[inline]
+ fn from(s: String) -> Self {
+ Cow::owned(s)
+ }
+}
+
+impl<T, U> From<Vec<T>> for Cow<'_, [T], U>
+where
+ T: Clone,
+ U: Capacity,
+{
+ #[inline]
+ fn from(v: Vec<T>) -> Self {
+ Cow::owned(v)
+ }
+}
+
+impl<T, U> Drop for Cow<'_, T, U>
+where
+ T: Beef + ?Sized,
+ U: Capacity,
+{
+ #[inline]
+ fn drop(&mut self) {
+ if let Some(capacity) = self.capacity() {
+ unsafe { T::owned_from_parts::<U>(self.ptr, self.fat, capacity) };
+ }
+ }
+}
+
+impl<'a, T, U> Clone for Cow<'a, T, U>
+where
+ T: Beef + ?Sized,
+ U: Capacity,
+{
+ #[inline]
+ fn clone(&self) -> Self {
+ match self.capacity() {
+ Some(_) => Cow::owned(self.borrow().to_owned()),
+ None => Cow { ..*self },
+ }
+ }
+}
+
+impl<T, U> core::ops::Deref for Cow<'_, T, U>
+where
+ T: Beef + ?Sized,
+ U: Capacity,
+{
+ type Target = T;
+
+ #[inline]
+ fn deref(&self) -> &T {
+ self.borrow()
+ }
+}
+
+impl<T, U> AsRef<T> for Cow<'_, T, U>
+where
+ T: Beef + ?Sized,
+ U: Capacity,
+{
+ #[inline]
+ fn as_ref(&self) -> &T {
+ self.borrow()
+ }
+}
+
+impl<T, U> Borrow<T> for Cow<'_, T, U>
+where
+ T: Beef + ?Sized,
+ U: Capacity,
+{
+ #[inline]
+ fn borrow(&self) -> &T {
+ self.borrow()
+ }
+}
+
+impl<'a, T, U> From<StdCow<'a, T>> for Cow<'a, T, U>
+where
+ T: Beef + ?Sized,
+ U: Capacity,
+{
+ #[inline]
+ fn from(stdcow: StdCow<'a, T>) -> Self {
+ match stdcow {
+ StdCow::Borrowed(v) => Self::borrowed(v),
+ StdCow::Owned(v) => Self::owned(v),
+ }
+ }
+}
+
+impl<'a, T, U> From<Cow<'a, T, U>> for StdCow<'a, T>
+where
+ T: Beef + ?Sized,
+ U: Capacity,
+{
+ #[inline]
+ fn from(cow: Cow<'a, T, U>) -> Self {
+ let cow = ManuallyDrop::new(cow);
+
+ match cow.capacity() {
+ Some(capacity) => {
+ StdCow::Owned(unsafe { T::owned_from_parts::<U>(cow.ptr, cow.fat, capacity) })
+ }
+ None => StdCow::Borrowed(unsafe { &*T::ref_from_parts::<U>(cow.ptr, cow.fat) }),
+ }
+ }
+}
+
+impl<A, B, U, V> PartialEq<Cow<'_, B, V>> for Cow<'_, A, U>
+where
+ A: Beef + ?Sized,
+ B: Beef + ?Sized,
+ U: Capacity,
+ V: Capacity,
+ A: PartialEq<B>,
+{
+ fn eq(&self, other: &Cow<B, V>) -> bool {
+ self.borrow() == other.borrow()
+ }
+}
+
+macro_rules! impl_eq {
+ ($($(@for< $bounds:tt >)? $ptr:ty => $([$($deref:tt)+])? <$with:ty>,)*) => {$(
+ impl<U $(, $bounds)*> PartialEq<$with> for Cow<'_, $ptr, U>
+ where
+ U: Capacity,
+ $( $bounds: Clone + PartialEq, )*
+ {
+ #[inline]
+ fn eq(&self, other: &$with) -> bool {
+ self.borrow() == $($($deref)*)* other
+ }
+ }
+
+ impl<U $(, $bounds)*> PartialEq<Cow<'_, $ptr, U>> for $with
+ where
+ U: Capacity,
+ $( $bounds: Clone + PartialEq, )*
+ {
+ #[inline]
+ fn eq(&self, other: &Cow<$ptr, U>) -> bool {
+ $($($deref)*)* self == other.borrow()
+ }
+ }
+ )*};
+}
+
+impl_eq! {
+ str => <str>,
+ str => [*]<&str>,
+ str => <String>,
+ @for<T> [T] => <[T]>,
+ @for<T> [T] => [*]<&[T]>,
+ @for<T> [T] => [&**]<Vec<T>>,
+}
+
+impl<T, U> fmt::Debug for Cow<'_, T, U>
+where
+ T: Beef + fmt::Debug + ?Sized,
+ U: Capacity,
+{
+ #[inline]
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ self.borrow().fmt(f)
+ }
+}
+
+impl<T, U> fmt::Display for Cow<'_, T, U>
+where
+ T: Beef + fmt::Display + ?Sized,
+ U: Capacity,
+{
+ #[inline]
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ self.borrow().fmt(f)
+ }
+}
+
+// Safety: Same bounds as `std::borrow::Cow`.
+unsafe impl<T, U> Sync for Cow<'_, T, U>
+where
+ U: Capacity,
+ T: Beef + Sync + ?Sized,
+ T::Owned: Sync,
+{
+}
+
+unsafe impl<T, U> Send for Cow<'_, T, U>
+where
+ U: Capacity,
+ T: Beef + Sync + ?Sized,
+ T::Owned: Send,
+{
+}
+
+impl<T, U> Unpin for Cow<'_, T, U>
+where
+ U: Capacity,
+ T: Beef + ?Sized,
+ T::Owned: Unpin,
+{
+}
diff --git a/vendor/beef/src/lean.rs b/vendor/beef/src/lean.rs
new file mode 100644
index 00000000..cb3c1943
--- /dev/null
+++ b/vendor/beef/src/lean.rs
@@ -0,0 +1,69 @@
+//! Namespace containing the 2-word `Cow` implementation.
+
+use crate::traits::Capacity;
+
+/// Faster, 2-word `Cow`. This version is available only on 64-bit architecture,
+/// and it puts both capacity and length together in a fat pointer. Both length and capacity
+/// is limited to 32 bits.
+///
+/// # Panics
+///
+/// [`Cow::owned`](../generic/struct.Cow.html#method.owned) will panic if capacity is larger than `u32::max_size()`. Use the
+/// top level `beef::Cow` if you wish to avoid this problem.
+pub type Cow<'a, T> = crate::generic::Cow<'a, T, Lean>;
+
+pub(crate) mod internal {
+ #[derive(Clone, Copy, PartialEq, Eq)]
+ pub struct Lean;
+}
+use internal::Lean;
+
+const MASK_LO: usize = u32::MAX as usize;
+const MASK_HI: usize = !MASK_LO;
+
+impl Lean {
+ #[inline]
+ pub const fn mask_len(len: usize) -> usize {
+ len & MASK_LO
+ }
+}
+
+impl Capacity for Lean {
+ type Field = Lean;
+ type NonZero = Lean;
+
+ #[inline]
+ fn len(fat: usize) -> usize {
+ fat & MASK_LO
+ }
+
+ #[inline]
+ fn empty(len: usize) -> (usize, Lean) {
+ (len & MASK_LO, Lean)
+ }
+
+ #[inline]
+ fn store(len: usize, capacity: usize) -> (usize, Lean) {
+ if capacity & MASK_HI != 0 {
+ panic!("beef::lean::Cow: Capacity out of bounds");
+ }
+
+ let fat = ((capacity & MASK_LO) << 32) | (len & MASK_LO);
+
+ (fat, Lean)
+ }
+
+ #[inline]
+ fn unpack(fat: usize, _: Lean) -> (usize, usize) {
+ (fat & MASK_LO, (fat & MASK_HI) >> 32)
+ }
+
+ #[inline]
+ fn maybe(fat: usize, _: Lean) -> Option<Lean> {
+ if fat & MASK_HI != 0 {
+ Some(Lean)
+ } else {
+ None
+ }
+ }
+}
diff --git a/vendor/beef/src/lib.rs b/vendor/beef/src/lib.rs
new file mode 100644
index 00000000..62a503a3
--- /dev/null
+++ b/vendor/beef/src/lib.rs
@@ -0,0 +1,285 @@
+//! Faster, more compact implementation of `Cow`.
+//!
+//! **[Changelog](https://github.com/maciejhirsz/beef/releases) -**
+//! **[Cargo](https://crates.io/crates/beef) -**
+//! **[Repository](https://github.com/maciejhirsz/beef)**
+//!
+//! ```rust
+//! use beef::Cow;
+//!
+//! let borrowed: Cow<str> = Cow::borrowed("Hello");
+//! let owned: Cow<str> = Cow::owned(String::from("World"));
+//!
+//! assert_eq!(
+//! format!("{} {}!", borrowed, owned),
+//! "Hello World!",
+//! );
+//! ```
+//!
+//! There are two versions of `Cow` exposed by this crate:
+//!
+//! + `beef::Cow` is 3 words wide: pointer, length, and capacity. It stores the ownership tag in capacity.
+//! + `beef::lean::Cow` is 2 words wide, storing length, capacity, and the ownership tag all in one word.
+//!
+//! Both versions are leaner than the `std::borrow::Cow`:
+//!
+//! ```rust
+//! use std::mem::size_of;
+//!
+//! const WORD: usize = size_of::<usize>();
+//!
+//! assert_eq!(size_of::<std::borrow::Cow<str>>(), 4 * WORD);
+//! assert_eq!(size_of::<beef::Cow<str>>(), 3 * WORD);
+//!
+//! // Lean variant is two words on 64-bit architecture
+//! #[cfg(target_pointer_width = "64")]
+//! assert_eq!(size_of::<beef::lean::Cow<str>>(), 2 * WORD);
+//! ```
+#![cfg_attr(feature = "const_fn", feature(const_fn_trait_bound))]
+#![warn(missing_docs)]
+#![cfg_attr(not(test), no_std)]
+extern crate alloc;
+
+mod traits;
+mod wide;
+
+#[cfg(feature = "impl_serde")]
+mod serde;
+
+pub mod generic;
+#[cfg(target_pointer_width = "64")]
+pub mod lean;
+
+#[cfg(not(target_pointer_width = "64"))]
+pub mod lean {
+ /// Re-exports 3-word Cow for non-64-bit targets
+ pub use super::wide::Cow;
+}
+
+pub use wide::Cow;
+
+#[rustfmt::skip]
+macro_rules! test { ($tmod:ident => $cow:path) => {
+ #[cfg(test)]
+ mod $tmod {
+ use $cow;
+
+ #[test]
+ fn borrowed_str() {
+ let s = "Hello World";
+ let c = Cow::borrowed(s);
+
+ assert_eq!(s, c);
+ assert_eq!(s, c.as_ref());
+ assert_eq!(s, &*c);
+ }
+
+ #[test]
+ fn owned_string() {
+ let s = String::from("Hello World");
+ let c: Cow<str> = Cow::owned(s.clone());
+
+ assert_eq!(s, c);
+ }
+
+ #[test]
+ fn into_owned() {
+ let hello = "Hello World";
+ let borrowed = Cow::borrowed(hello);
+ let owned: Cow<str> = Cow::owned(String::from(hello));
+
+ assert_eq!(borrowed.into_owned(), hello);
+ assert_eq!(owned.into_owned(), hello);
+ }
+
+ #[test]
+ fn borrowed_slice() {
+ let s: &[_] = &[1, 2, 42];
+ let c = Cow::borrowed(s);
+
+ assert_eq!(s, c);
+ assert_eq!(s, c.as_ref());
+ assert_eq!(s, &*c);
+ }
+
+ #[test]
+ fn owned_slice() {
+ let s = vec![1, 2, 42];
+ let c: Cow<[_]> = Cow::owned(s.clone());
+
+ assert_eq!(s, c);
+ }
+
+ #[test]
+ fn into_owned_vec() {
+ let hello: &[u8] = b"Hello World";
+ let borrowed = Cow::borrowed(hello);
+ let owned: Cow<[u8]> = Cow::owned(hello.to_vec());
+
+ assert_eq!(borrowed.into_owned(), hello);
+ assert_eq!(owned.into_owned(), hello);
+ }
+
+ #[test]
+ fn hash() {
+ use std::collections::hash_map::DefaultHasher;
+ use std::hash::{Hash, Hasher};
+
+ let slice = "Hello World!";
+ let borrowed = Cow::borrowed(slice);
+ let owned: Cow<str> = Cow::owned(slice.to_owned());
+
+ let hash1 = {
+ let mut hasher = DefaultHasher::default();
+
+ slice.hash(&mut hasher);
+
+ hasher.finish()
+ };
+
+ let hash2 = {
+ let mut hasher = DefaultHasher::default();
+
+ borrowed.hash(&mut hasher);
+
+ hasher.finish()
+ };
+
+ let hash3 = {
+ let mut hasher = DefaultHasher::default();
+
+ owned.hash(&mut hasher);
+
+ hasher.finish()
+ };
+
+ assert_eq!(hash1, hash2);
+ assert_eq!(hash1, hash3);
+ assert_eq!(hash2, hash3);
+ }
+
+ #[test]
+ fn ord_and_partial_ord() {
+ use std::cmp::Ordering;
+
+ macro_rules! generate_order_tests {
+ ( $f:tt => $order:expr => $left:expr, $right:expr ) => {
+ assert_eq!(
+ Cow::<str>::borrowed($left).$f(&Cow::<str>::borrowed($right)),
+ $order
+ );
+
+ assert_eq!(
+ Cow::<str>::owned($left.to_owned())
+ .$f(&Cow::<str>::borrowed($right)),
+ $order
+ );
+
+ assert_eq!(
+ Cow::<str>::borrowed($left)
+ .$f(&Cow::<str>::owned($right.to_owned())),
+ $order
+ );
+
+ assert_eq!(
+ Cow::<str>::owned($left.to_owned())
+ .$f(&Cow::<str>::owned($right.to_owned())),
+ $order
+ );
+ }
+ }
+
+ generate_order_tests!(partial_cmp => Some(Ordering::Equal) => "a", "a");
+ generate_order_tests!(partial_cmp => Some(Ordering::Less) => "a", "b");
+ generate_order_tests!(partial_cmp => Some(Ordering::Greater) => "b", "a");
+
+ generate_order_tests!(cmp => Ordering::Equal => "a", "a");
+ generate_order_tests!(cmp => Ordering::Less => "a", "b");
+ generate_order_tests!(cmp => Ordering::Greater => "b", "a");
+ }
+
+ #[test]
+ fn from_std_cow() {
+ let std = std::borrow::Cow::Borrowed("Hello World");
+ let beef = Cow::from(std.clone());
+
+ assert_eq!(&*std, &*beef);
+ }
+
+ #[test]
+ fn unwrap_borrowed() {
+ let borrowed = Cow::borrowed("Hello");
+
+ assert_eq!(borrowed.unwrap_borrowed(), "Hello");
+ }
+
+ #[test]
+ #[should_panic]
+ fn unwrap_owned() {
+ let borrowed: Cow<str> = Cow::owned("Hello".to_string());
+
+ borrowed.unwrap_borrowed();
+ }
+
+ #[test]
+ fn stress_test_owned() {
+ let mut expected = String::from("Hello... ");
+ let mut cow: Cow<str> = Cow::borrowed("Hello... ");
+
+ #[cfg(not(miri))]
+ let iterations = 1024;
+ #[cfg(miri)]
+ let iterations = 10;
+
+ for i in 0..iterations {
+ if i % 3 == 0 {
+ let old = cow;
+ cow = old.clone();
+
+ std::mem::drop(old);
+ }
+
+ let mut owned = cow.into_owned();
+
+ expected.push_str("Hello?.. ");
+ owned.push_str("Hello?.. ");
+
+ cow = owned.into();
+ }
+
+ assert_eq!(expected, cow.into_owned());
+ }
+
+ #[test]
+ fn const_fn_str() {
+ const HELLO: Cow<str> = Cow::const_str("Hello");
+
+ assert_eq!(&*HELLO, "Hello");
+ }
+
+ #[test]
+ #[cfg(feature = "const_fn")]
+ fn const_fn_slice() {
+ const FOO: Cow<[u8]> = Cow::const_slice(b"bar");
+
+ assert_eq!(&*FOO, b"bar");
+ }
+
+ #[test]
+ fn default_str() {
+ let empty: Cow<str> = Default::default();
+
+ assert_eq!(&*empty, "");
+ }
+
+ #[test]
+ fn default_slice() {
+ let empty: Cow<[u8]> = Default::default();
+
+ assert_eq!(&*empty, b"");
+ }
+ }
+} }
+
+test!(test_wide => crate::wide::Cow);
+test!(test_lean => crate::lean::Cow);
diff --git a/vendor/beef/src/serde.rs b/vendor/beef/src/serde.rs
new file mode 100644
index 00000000..a85fbc6f
--- /dev/null
+++ b/vendor/beef/src/serde.rs
@@ -0,0 +1,149 @@
+use alloc::{borrow::ToOwned, string::String};
+use core::{fmt, marker::PhantomData};
+
+use serde::de::{self, Deserialize, Deserializer, Visitor};
+use serde::ser::{Serialize, Serializer};
+
+use crate::generic::Cow;
+use crate::traits::internal::{Beef, Capacity};
+
+impl<T, U> Serialize for Cow<'_, T, U>
+where
+ T: Beef + Serialize + ?Sized,
+ U: Capacity,
+{
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ T::serialize(self.as_ref(), serializer)
+ }
+}
+
+struct CowVisitor<'de, 'a, T: Beef + ?Sized, U: Capacity>(
+ PhantomData<fn() -> (&'de T, Cow<'a, T, U>)>,
+);
+
+impl<'de, 'a, U> Visitor<'de> for CowVisitor<'de, 'a, str, U>
+where
+ 'de: 'a,
+ U: Capacity,
+{
+ type Value = Cow<'a, str, U>;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("a string")
+ }
+
+ fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ Ok(Cow::borrowed(value))
+ }
+
+ fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ Ok(Cow::owned(value.to_owned()))
+ }
+
+ fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ Ok(Cow::owned(value))
+ }
+}
+
+impl<'de, 'a, U> Deserialize<'de> for Cow<'a, str, U>
+where
+ 'de: 'a,
+ U: Capacity,
+{
+ #[inline]
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ deserializer.deserialize_str(CowVisitor::<'de, 'a, str, U>(PhantomData))
+ }
+}
+
+impl<'de, 'a, T, U> Deserialize<'de> for Cow<'a, [T], U>
+where
+ [T]: Beef,
+ U: Capacity,
+ <[T] as ToOwned>::Owned: Deserialize<'de>,
+{
+ #[inline]
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ <[T] as ToOwned>::Owned::deserialize(deserializer).map(Cow::owned)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_derive::{Deserialize, Serialize};
+
+ #[test]
+ fn wide_cow_de() {
+ use crate::Cow;
+
+ #[derive(Serialize, Deserialize)]
+ struct Test<'a> {
+ #[serde(borrow)]
+ foo: Cow<'a, str>,
+ bar: Cow<'a, str>,
+ }
+
+ let json = r#"{"foo":"Hello","bar":"\tWorld!"}"#;
+ let test: Test = serde_json::from_str(json).unwrap();
+
+ assert_eq!(test.foo, "Hello");
+ assert_eq!(test.bar, "\tWorld!");
+
+ assert!(test.foo.is_borrowed());
+ assert!(test.bar.is_owned());
+
+ let out = serde_json::to_string(&test).unwrap();
+
+ assert_eq!(json, out);
+ }
+
+ #[test]
+ fn wide_cow_direct() {
+ use crate::Cow;
+
+ let json = r#""foo""#;
+ let cow: Cow<str> = serde_json::from_str(json).unwrap();
+
+ assert_eq!(cow, "foo");
+
+ assert!(cow.is_borrowed());
+
+ let json = r#""\tfoo""#;
+ let cow: Cow<str> = serde_json::from_str(json).unwrap();
+
+ assert_eq!(cow, "\tfoo");
+
+ assert!(cow.is_owned());
+ }
+
+ #[test]
+ fn wide_cow_direct_bytes() {
+ use crate::Cow;
+
+ let json = r#"[102, 111, 111]"#;
+ let cow: Cow<[u8]> = serde_json::from_str(json).unwrap();
+
+ assert_eq!(cow, &b"foo"[..]);
+
+ // We need to stay generic over `[T]`, so no specialization for byte slices
+ assert!(cow.is_owned());
+ }
+}
diff --git a/vendor/beef/src/traits.rs b/vendor/beef/src/traits.rs
new file mode 100644
index 00000000..4be2d2d0
--- /dev/null
+++ b/vendor/beef/src/traits.rs
@@ -0,0 +1,175 @@
+pub(crate) use internal::Beef;
+pub(crate) use internal::Capacity;
+
+pub(crate) mod internal {
+ use alloc::borrow::ToOwned;
+ use alloc::string::String;
+ use alloc::vec::Vec;
+ use core::mem::ManuallyDrop;
+ use core::ptr::{slice_from_raw_parts, NonNull};
+
+ pub trait Capacity {
+ type Field: Copy;
+ type NonZero: Copy;
+
+ fn len(fat: usize) -> usize;
+
+ fn empty(len: usize) -> (usize, Self::Field);
+
+ fn store(len: usize, capacity: usize) -> (usize, Self::Field);
+
+ fn unpack(fat: usize, capacity: Self::NonZero) -> (usize, usize);
+
+ fn maybe(fat: usize, capacity: Self::Field) -> Option<Self::NonZero>;
+ }
+
+ /// Helper trait required by `Cow<T>` to extract capacity of owned
+ /// variant of `T`, and manage conversions.
+ ///
+ /// This can be only implemented on types that match requirements:
+ ///
+ /// + `T::Owned` has a `capacity`, which is an extra word that is absent in `T`.
+ /// + `T::Owned` with `capacity` of `0` does not allocate memory.
+ /// + `T::Owned` can be reconstructed from `*mut T` borrowed out of it, plus capacity.
+ pub unsafe trait Beef: ToOwned {
+ type PointerT;
+
+ fn ref_into_parts<U>(&self) -> (NonNull<Self::PointerT>, usize, U::Field)
+ where
+ U: Capacity;
+
+ unsafe fn ref_from_parts<U>(ptr: NonNull<Self::PointerT>, len: usize) -> *const Self
+ where
+ U: Capacity;
+
+ /// Convert `T::Owned` to `NonNull<T>` and capacity.
+ /// Return `None` for `0` capacity.
+ fn owned_into_parts<U>(owned: Self::Owned) -> (NonNull<Self::PointerT>, usize, U::Field)
+ where
+ U: Capacity;
+
+ /// Rebuild `T::Owned` from `NonNull<T>` and `capacity`. This can be done by the likes
+ /// of [`Vec::from_raw_parts`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.from_raw_parts).
+ unsafe fn owned_from_parts<U>(
+ ptr: NonNull<Self::PointerT>,
+ fat: usize,
+ capacity: U::NonZero,
+ ) -> Self::Owned
+ where
+ U: Capacity;
+ }
+
+ unsafe impl Beef for str {
+ type PointerT = u8;
+
+ #[inline]
+ fn ref_into_parts<U>(&self) -> (NonNull<u8>, usize, U::Field)
+ where
+ U: Capacity,
+ {
+ let (fat, cap) = U::empty(self.len());
+
+ // A note on soundness:
+ //
+ // We are casting *const T to *mut T, however for all borrowed values
+ // this raw pointer is only ever dereferenced back to &T.
+ (
+ unsafe { NonNull::new_unchecked(self.as_ptr() as *mut u8) },
+ fat,
+ cap,
+ )
+ }
+
+ #[inline]
+ unsafe fn ref_from_parts<U>(ptr: NonNull<u8>, fat: usize) -> *const str
+ where
+ U: Capacity,
+ {
+ slice_from_raw_parts(ptr.as_ptr(), U::len(fat)) as *const str
+ }
+
+ #[inline]
+ fn owned_into_parts<U>(owned: String) -> (NonNull<u8>, usize, U::Field)
+ where
+ U: Capacity,
+ {
+ // Convert to `String::into_raw_parts` once stabilized
+ // We need to go through Vec here to get provenance for the entire allocation
+ // instead of just the initialized parts.
+ let mut owned = ManuallyDrop::new(owned.into_bytes());
+ let (fat, cap) = U::store(owned.len(), owned.capacity());
+
+ (
+ unsafe { NonNull::new_unchecked(owned.as_mut_ptr()) },
+ fat,
+ cap,
+ )
+ }
+
+ #[inline]
+ unsafe fn owned_from_parts<U>(ptr: NonNull<u8>, fat: usize, capacity: U::NonZero) -> String
+ where
+ U: Capacity,
+ {
+ let (len, cap) = U::unpack(fat, capacity);
+
+ String::from_utf8_unchecked(Vec::from_raw_parts(ptr.as_ptr(), len, cap))
+ }
+ }
+
+ unsafe impl<T: Clone> Beef for [T] {
+ type PointerT = T;
+
+ #[inline]
+ fn ref_into_parts<U>(&self) -> (NonNull<T>, usize, U::Field)
+ where
+ U: Capacity,
+ {
+ let (fat, cap) = U::empty(self.len());
+
+ // A note on soundness:
+ //
+ // We are casting *const T to *mut T, however for all borrowed values
+ // this raw pointer is only ever dereferenced back to &T.
+ (
+ unsafe { NonNull::new_unchecked(self.as_ptr() as *mut T) },
+ fat,
+ cap,
+ )
+ }
+
+ #[inline]
+ unsafe fn ref_from_parts<U>(ptr: NonNull<T>, fat: usize) -> *const [T]
+ where
+ U: Capacity,
+ {
+ slice_from_raw_parts(ptr.as_ptr(), U::len(fat))
+ }
+
+ #[inline]
+ fn owned_into_parts<U>(owned: Vec<T>) -> (NonNull<T>, usize, U::Field)
+ where
+ U: Capacity,
+ {
+ // Convert to `Vec::into_raw_parts` once stabilized
+ let mut owned = ManuallyDrop::new(owned);
+ let (fat, cap) = U::store(owned.len(), owned.capacity());
+
+ (
+ unsafe { NonNull::new_unchecked(owned.as_mut_ptr()) },
+ fat,
+ cap,
+ )
+ }
+
+ #[inline]
+ unsafe fn owned_from_parts<U>(ptr: NonNull<T>, fat: usize, capacity: U::NonZero) -> Vec<T>
+ where
+ U: Capacity,
+ {
+ let (len, cap) = U::unpack(fat, capacity);
+
+ Vec::from_raw_parts(ptr.as_ptr(), len, cap)
+ }
+ }
+}
diff --git a/vendor/beef/src/wide.rs b/vendor/beef/src/wide.rs
new file mode 100644
index 00000000..466e594c
--- /dev/null
+++ b/vendor/beef/src/wide.rs
@@ -0,0 +1,42 @@
+use crate::traits::Capacity;
+use core::num::NonZeroUsize;
+
+/// Compact three word `Cow` that puts the ownership tag in capacity.
+/// This is a type alias, for documentation see [`beef::generic::Cow`](./generic/struct.Cow.html).
+pub type Cow<'a, T> = crate::generic::Cow<'a, T, Wide>;
+
+pub(crate) mod internal {
+ #[derive(Clone, Copy, PartialEq, Eq)]
+ pub struct Wide;
+}
+use internal::Wide;
+
+impl Capacity for Wide {
+ type Field = Option<NonZeroUsize>;
+ type NonZero = NonZeroUsize;
+
+ #[inline]
+ fn len(fat: usize) -> usize {
+ fat
+ }
+
+ #[inline]
+ fn empty(len: usize) -> (usize, Self::Field) {
+ (len, None)
+ }
+
+ #[inline]
+ fn store(len: usize, capacity: usize) -> (usize, Self::Field) {
+ (len, NonZeroUsize::new(capacity))
+ }
+
+ #[inline]
+ fn unpack(fat: usize, capacity: NonZeroUsize) -> (usize, usize) {
+ (fat, capacity.get())
+ }
+
+ #[inline]
+ fn maybe(_: usize, capacity: Option<NonZeroUsize>) -> Option<NonZeroUsize> {
+ capacity
+ }
+}