serde-rs / serde-rs/bytes

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

Open
#40 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
384
Forks
40
PR merge metrics
No merged PRs in 30d

Description

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?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the two Rust examples and comparing serde-bytes' Cow behavior with serde's handling. Investigate the serde-bytes implementation and determine whether the example can serialize by borrowing while deserializing into owned data; done means the second example compiles with that behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.