Skip to content

Confusing error message for lifetime mismatch #132749

@Kushagra-0801

Description

Code

use bytes::Bytes;

#[allow(unused)]
struct SimpleString(Bytes);

fn deserialize_simple_string(buf: &[u8]) -> Result<(SimpleString, &[u8]), &'static str> {
    let Some((s, rest)) = split_on_crlf(buf) else {
        return Err("No CRLF found");
    };
    Ok((SimpleString(Bytes::from(s)), rest))
}


fn split_on_crlf(buf: &[u8]) -> Option<(&[u8], &[u8])> {
    let pos = buf.windows(2).position(|win| win == b"\r\n")?;
    let part = &buf[..pos];
    let rest = &buf[pos + 2..];
    Some((part, rest))
}

fn main() {
    let x = Vec::from(b"non-static user data\r\n");
    let _ = deserialize_simple_string(&x).unwrap();
}

Current output

error[E0521]: borrowed data escapes outside of function
 --> src/main.rs:7:27
  |
6 | fn deserialize_simple_string(buf: &[u8]) -> Result<(SimpleString, &[u8]), &'static str> {
  |                              ---  - let's call the lifetime of this reference `'1`
  |                              |
  |                              `buf` is a reference that is only valid in the function body
7 |     let Some((s, rest)) = split_on_crlf(buf) else {
  |                           ^^^^^^^^^^^^^^^^^^
  |                           |
  |                           `buf` escapes the function body here
  |                           argument requires that `'1` must outlive `'static`

Desired output

main.rs:23

In main()

`x` does not live for `'static` but `deserialize_simple_string` expects the argument to outlive `'static`.

Rationale and extra context

The real problem is that the Bytes::from implementation is only for &'static [u8]. Whatever the output is, it shouldn't be pointing to split_on_crlf as the culprit. I also don't see how it could be leaking the reference at all.

Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=631eaea4377ffad8120532ea9e356233

Other cases

No response

Rust Version

Its the stable channel, debug build, 2021 edition on playground. Version 1.82.0

Anything else?

No response

Activity

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

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsD-confusingDiagnostics: Confusing error or lint that should be reworked.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions