Skip to content

Implement Into<&'a [u8]> for BorrowedBytes<'a> #659

@sxyazi

Description

@sxyazi

Currently, to get the underlying &[u8] represented by BorrowedBytes you need to go through Deref, Borrow<[u8]> or AsRef<[u8]>, but they all take a &self rather than self, which causes the returned &[u8] to be tied to a temporary &BorrowedBytes instead of to the lifetime 'a of BorrowedBytes<'a>, which is a reference to &'a mlua::String.

This makes:

fn as_bytes<'a>(s: &'a mlua::String) -> &'a [u8] {
  s.as_bytes().as_ref()
}

fail to compile:

cannot return value referencing temporary value
returns a value referencing data owned by the current function rustc (E0515)

By implementing Into<&'a [u8]>:

impl<'a> From<BorrowedBytes<'a>> for &'a [u8] {
  fn from(value: BorrowedBytes<'a>) -> Self { value.buf }
}

I can convert BorrowedBytes<'a> into &'a [u8]:

fn as_bytes<'a>(s: &'a mlua::String) -> &'a [u8] {
  s.as_bytes().into()
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions