Suppose I have two not entirely hypothetical traits Deserialize<'de>
and Deserializer<'de>
with the semantics that if T: Deserialize<'de>
and D: Deserializer<'de>
then I can use a deserializer of type D
to get out a value of type T
.
fn do_the_thing<'de, T, D>(deserializer: D) -> T
where
T: Deserialize<'de>,
D: Deserializer<'de>;
Seems like the sort of thing somebody could build a library around. In any case, here are some impls:
impl<'de: 'a, 'a> Deserialize<'de> for &'a str { /* ... */ }
impl<'de> Deserialize<'de> for String { /* ... */ }
struct JsonDeserializer<'de> { input: &'de [u8] }
impl<'de> Deserializer<'de> for JsonDeserializer<'de> { /* ... */ }
This is great. We can make a JsonDeserializer<'de>
and deserialize String
s from it regardless of 'de
, and deserialize &'a str
s from it as long as 'de
outlives 'a
.
But some deserializers only support deserializing types like String
and not types like &'a str
.
struct OtherDeserializer<R> { reader: R }
impl<R: io::Read> Deserializer<???> for OtherDeserializer<R> { /* ... */ }
There are basically two options for this impl.
impl<'de, R: io::Read> Deserializer<'de> for OtherDeserializer<R> { /* ... */ }
// or
impl<R: io::Read> Deserializer<'static> for OtherDeserializer<R> { /* ... */ }
They mean the same thing. In either case we can make an OtherDeserializer<R>
and deserialize String
s from it which is great, but also we can (try to) deserialize any &str
from it including &'static str
.
The 'static
in the last impl is the opposite of what we want. It means: assume this deserializer contains data that lives so long that it might as well live forever. The thing we want is: assume this deserializer contains data that lives so short that it never even exists in the first place.
impl<R: io::Read> Deserializer<'never> for OtherDeserializer<R> { /* ... */ }
I know about the postponed 'unsafe
lifetime RFC but my understanding is it is addressing something very different. cc @jpernst anyway in case this has any bearing on a future iteration of 'unsafe
.
I don’t plan to pursue this further but I figured it was worth writing down somewhere.