Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign updeserialize Cow should be decoding into slices #224
Comments
|
|
|
Oh nice. Why isn't it a default for non-owned deserialization though? |
|
The deserialize impl is: impl<'de, 'a, T: ?Sized> Deserialize<'de> for Cow<'a, T>The borrow attribute effectively gives you: impl<'de, T: ?Sized> Deserialize<'de> for Cow<'de, T>In my experience the first one is usually what people want for the ways that Cow is commonly used. For example it lets you serialize and deserialize a struct containing Cow where the data is always borrowed on the way out and owned on the way in without needing to hold on to the serialized data. The second one is relatively uncommonly used. |
|
It's just a bit surprising that we have two deserialization entry points, one that assumes holding onto the entire input (and so can decode &str, &[u8] etc.) and another that can't assume that as it operates on streams and so can produce only owned values. Yet both entry points produce owned values for Cow by default, even though its contents are subject to exactly same assumptions about having the actual data blob stored elsewhere. Wouldn't it be possible / make sense to specialize Cow to parse references by default when entire data is available and only owned values otherwise, just like it does for "regular" data types? If my struct consists of various fields some of which are pure references and some are Cows, it's already bound to the input data because of the former, and so could as well deserialize references in the latter case. |
|
This issue would need to be raised with the serde repo itself since it controls how Cow is deserialized. |
Currently if I encode, for example,
Cow<String>, and deserialize it back usingdeserialize(that is, passing a complete slice of bytes and not just a stream), I get aCow::Ownedback even though I own the entire buffer, and so could have a cheap allocation-free decoding intoCow::Borrowed.Note that when decoding into explicit
&str, this produces a reference as expected.