-
-
Notifications
You must be signed in to change notification settings - Fork 791
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
#[serde(borrow)] does not work with Option<Cow<'a, str>> #2016
Comments
Please note that fixing this bug may be a breaking change unfortunately, because people may have written data structs such as the above with the assumption that they worked with borrowed data, but then used those structs in a situation where DeserializeOwned is required. |
As a workaround I wonder if it's possible for users to write a custom |
I proposed a fix for this bug in #2072 but the fix was declined. |
It is possible to use use serde_with::{serde_as, BorrowCow};
use std::borrow::Cow;
#[serde_as]
#[derive(Deserialize, Serialize)]
struct Data<'a> {
#[serde_as(as = "Option<[BorrowCow; 1]>")]
nested: Option<[Cow<'a, str>; 1]>,
}
let mut d: Data<'static> = serde_json::from_str(r#"{"nested": ["foobar"]}"#)?;
let [cow] = d.nested.take().unwrap();
match cow {
Cow::Borrowed(_) => println!("borrowed"),
Cow::Owned(_) => println!("owned"),
};
// => Prints borrowed |
If this is closed as "won't fix", I'd like to suggest that at least serde(borrow) should complain if it tags something it doesn't know how to borrow. The problem of getting the desired functionality is one thing, but the footgun of thinking you're borrowing when you're actually not is much worse. |
As @robertbastian found in unicode-org/icu4x#1556, Do you think we should reopen this issue to focus on that aspect? |
I think that it's… kind of ridiculous to have to wrap things in Sorry for being kinda salty about this, but I don't think that retaining compatibility with broken behaviour is a reason to not implement correct behaviour in any capacity. |
Minimal repro:
Expected behavior: the test should pass, because the string in the Cow should be borrowed from the Bincode buffer.
Actual behavior: the test fails on the
assert!(matches!(...))
line, and passes if I changeCow::Borrowed
toCow::Owned
.I believe it is desired to pass the lifetime down through the Option, since Serde does this with raw string references, according to #1029.
Related: #723, #1497
CC @Manishearth
The text was updated successfully, but these errors were encountered: