I have a container Frame
, for example the following:
pub struct Frame<T: AsRef<[u8]>> {
inner: T,
}
and it has the following functions:
impl<T: AsRef<[u8]>> Frame<T> {
pub fn new_unchecked(frame: T) -> Self {
Frame { inner: frame }
}
pub fn payload(&self) -> &'_ [u8] {
self.inner.as_ref()
}
}
I also have a struct that is a more higher level representation of the Frame
:
pub struct Repr<'frame> {
payload: &'frame [u8],
}
The representation is created using the following function:
impl<'frame> Repr<'frame> {
pub fn parse<T: AsRef<[u8]>>(frame: &Frame<T>) -> Self {
let payload = frame.payload();
Repr {
payload
}
}
}
However this does not compile because an explicit lifetime is required for Frame
.
When I change the implementation of Frame
, for accessing the payload, to the following:
impl<'f, T: AsRef<[u8]> + ?Sized> Frame<&'f T> {
pub fn payload(&self) -> &'f [u8] {
self.inner.as_ref()
}
}
and define the parse
function of Repr
as:
impl<'frame> Repr<'frame> {
pub fn parse<T: AsRef<[u8]> + ?Sized>(frame: &Frame<&'frame T>) -> Repr<'frame> {
let payload = frame.payload();
Repr { payload }
}
}
then the compiler is happy!
However, now it is only possible to call parse with Frame
that is created using an immutable slice. There is no implementation for a mutable slice now. However, sometimes I need a frame that is created with a mutable slice, because I need to decrypt things in place.
I have totally no idea how to handle this. How do you create a parse
function that is still generic over T: AsRef<[u8]>
and can accept a mutable and immutable slice?
This is when the compiler is happy (however only accepts immutable slices etc.).
This is when the compiler is not happy.