Can you transmute lifetimes like this?

⚓ rust    📅 2025-05-28    👤 surdeus    👁️ 4      

surdeus

Warning

This post was published 31 days ago. The information described in this article may have changed.

I have a following struct:

pub struct Deserializer<'de> {
    tape: Vec<&'de str>,
}

It's meant to store zero copy strings. In theory at least.

To parse I have the following function and traits:

impl<'de> Deserializer<'de> {
    fn parse_to_vec<'s, S, B>(input: S, mut buffer: B) -> Self
    where
        S: Source<'s>,
        B: Buffer<'de>
    {
        Deserializer {
            tape: vec![buffer.append(input.to_source())],
        }
    }
}

pub trait Source<'s> {
    fn to_source(&self) -> &'s str;
}

pub trait Buffer<'b> {
    fn append<'src>(&mut self, src: &'src str) -> &'b str;
}

I have Source and Buffer as traits because I want to abstract over sources and Buffers. For example if I have a borrowed string, I don't need a buffer, so I can easily say:


impl<'b> Buffer<'b> for () {
    fn append<'src>(&mut self, src: &'src str) -> &'b str {
        // THING I'm worried about
        unsafe {transmute(src)}
    }
}

impl<'s> Source<'s> for &'s str {
    fn to_source(&self) -> &'s str {
        self
    }
}

pub fn main() {
    let Deserializer { tape } = Deserializer::parse_to_vec("Hello, world!", ());
    println!("{}",tape[0]); // prints: Hello, world!
}

However, is it OK to implement like this? is the transmute gimmick sound, if I implement it like this?

5 posts - 2 participants

Read full topic

🏷️ rust_feed