UPDATE: I put together a minimal example.
I want to write a no-std compatible MessagePack serializer/deserializer. So far I got most of the serialization working, but I am struggling with serializing structs, sequences and maps using serde.
I copied a lot from serde_json_core, but these parts don't seem to work.
This is my Serializer struct:
pub(crate) struct Serializer<'a> {
buf: &'a mut [u8],
pos: usize,
}
and my sequence serializer struct:
pub struct SerializeSeq<'a> { ser: &'a mut Serializer<'a> }
impl<'a> ser::SerializeSeq for SerializeSeq<'a> {
type Ok = ();
type Error = Error;
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<Self::Ok, Self::Error>
where T: ser::Serialize {
value.serialize(&mut *self.ser)?;
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(())
}
}
It's just like in serde_json_serde::ser::seq, but it fails to compile with this message:
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
--> src/lib.rs:23:25
|
23 | value.serialize(&mut *self.ser)?;
| ^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 18:5...
--> src/lib.rs:18:5
|
18 | / fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<Self::Ok, Self::Error>
19 | | where
20 | | T: ser::Serialize
21 | | {
... |
24 | | Ok(())
25 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:23:25
|
23 | value.serialize(&mut *self.ser)?;
| ^^^^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 14:6...
--> src/lib.rs:14:6
|
14 | impl<'a> ser::SerializeSeq for SerializeSeq<'a> {
| ^^
note: ...so that the types are compatible
--> src/lib.rs:23:15
|
23 | value.serialize(&mut *self.ser)?;
| ^^^^^^^^^
= note: expected `serde::Serializer`
found `serde::Serializer`
I also tried passing &mut self.ser
, mut *self.ser
and self.ser
, but they all fail to compile with different error messages. Obviously it has something to do with the lifetimes of the serializer and it's buffer, but I don't know how to solve this.
The serializer impl looks like this:
impl<'a> ser::Serializer for &'a mut Serializer<'a> {
type Ok = ();
type Error = Error;
type SerializeSeq = SerializeSeq<'a>;
type SerializeTuple = SerializeSeq<'a>;
// ...
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
Ok(SerializeSeq::new(self))
}
}