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

Is there a way to borrow when serialize and own when deserialize? #40

Open
seekstar opened this issue Jun 24, 2023 · 1 comment
Open

Comments

@seekstar
Copy link

Cow is handled in this way in serde. But serde-bytes deserializes Cow by borrowing. As a result, this compiles:

#[derive(Serialize, Deserialize)]
struct A<'a> {
    a: Cow<'a, [u8]>,
}

But this does not compile:

#[derive(Serialize, Deserialize)]
struct A<'a> {
    #[serde(with = "serde_bytes")]
    a: Cow<'a, [u8]>,
}

The error message generated by compiler:

error: lifetime may not live long enough
 --> src/main.rs:4:21
  |
4 | #[derive(Serialize, Deserialize)]
  |                     ^^^^^^^^^^^
  |                     |
  |                     lifetime `'de` defined here
  |                     associated function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'de`
5 | struct A<'a> {
  |          -- lifetime `'a` defined here
  |
  = help: consider adding the following bound: `'de: 'a`
  = note: this error originates in the derive macro `Deserialize` (in Nightly builds, run with -Z macro-backtrace for more info)

Isn't it more reasonable to handle Cow in a way similar to serde so that deserializing Cow does not borrow?

@seekstar
Copy link
Author

I wrote crate CowBytes to solve this problem: https://github.com/seekstar/CowBytes. It seems that it works fine. I would like to submit a PR if the maintainer of serde_bytes consents.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant