Repository navigation
Add Cow conversions for Bytes - #859
RanaPriyansh wants to merge 3 commits into
Conversation
This comment was marked as spam.
This comment was marked as spam.
| } | ||
| } | ||
| } | ||
|
|
There was a problem hiding this comment.
I'm not a maintainer (or even a contributor. yet? 😅), but this looks good to me! Thanks for picking up the str variant too!
Only thing I can think of is, I wonder if there's a way to generalize this, so that it automatically picks up all Cow<'static, T> where both the borrowed and owned types already implement Into<Bytes>?
There was a problem hiding this comment.
Thanks for taking a look! I tried the generic version locally:
impl<T> From<Cow<'static, T>> for Bytes
where
T: ToOwned + ?Sized + 'static,
&'static T: Into<Bytes>,
T::Owned: Into<Bytes>,
{
fn from(cow: Cow<'static, T>) -> Bytes {
match cow {
Cow::Borrowed(borrowed) => borrowed.into(),
Cow::Owned(owned) => owned.into(),
}
}
}It compiles in place of the two impls, and the existing test suite plus the new Cow tests pass unchanged on Rust 1.94.1. Today it covers exactly the same types, [u8] and str, because those are the only T with From<&'static T> for Bytes. Its main gain is for downstream crates: a type that implements From<&'static T> and From<T::Owned> for Bytes would get Cow support automatically.
I kept the concrete impls because the blanket impl is a broader API commitment. It shows up in the docs as a where-clause rather than two concrete conversions. Any future From<&'static X> for Bytes would also extend Cow support to X. Starting with concrete impls leaves room to switch to the generic form later. Removing a blanket impl would be a breaking change. I haven't checked the generic version against the 1.57 MSRV.
I'm happy to switch if the maintainers prefer the generic form.
Codex used.
Closes #712.
Closes #861.
Implement
From<Cow<'static, [u8]>>andFrom<Cow<'static, str>>forBytes. Borrowed values use static storage. Owned values use the existingVec<u8>andStringconversions.Tests cover UTF-8 content, borrowed pointers, cloning and slicing, empty inputs, and owned pointer/capacity round-trips. The string fixture fails on baseline for the missing conversion and passes with the implementation. The tests use explicit Cow types where the two conversions make inference ambiguous.
Local validation: formatting,
git diff --check,RUSTFLAGS=-Dwarnings bash ci/test-stable.sh test, andcargo hack check --feature-powerset --optional-deps --rust-versionwith Rust 1.57.0.Pointer and capacity checks establish payload storage reuse for the tested cases. They do not establish zero total allocation. Nightly, Miri, sanitizers, cross-platform checks, and hosted CI remain separate.
Codex used.