How to (de)serialize `&'a Pin<Box<T>` with serde?

I have the following code:

use serde::*;

#[derive(Serialize, Deserialize)]
struct B {}

#[derive(Serialize, Deserialize)]
struct A<'a, T> {
    t: &'a Pin<Box<T>
}

impl<'a>  A<'a, B> {
    async fn handle(&'a self, context: Context, event: Event)               
           -> Result<&'a Self> {
          /// ...
         OK(self)
    }
}

fn main() {

     let b: Pin<Box<B> = Box::pin( B{} );
     let a = A::<'static, B> { t: &b };

     let id = some_actor_system
           .spawn()
           .with(a, Pin::<Box::<A<'static, B>>>handle).unwrap();
}

Compilation generates the following error:

error[E0277]: the trait bound `&std::pin::Pin<std::boxed::Box<B>>: std::default::Default` is not satisfied
  --> src/tests/hsm_03.rs:33:5
     |
33 | /     /// State processor.
34 | |     sm: &'a Pin<Box<SM>>,
     | |________________________^ the trait `std::default::Default` is not implemented for `&std::pin::Pin<std::boxed::Box<B>>`
   |
   = note: required by `std::default::Default::default`

The &'a Pin<Box<SM>> value is just a pinned reference to some space on the heap; it can't be that difficult to serialize it but I can't get it done... Help appreciated!

I don't think you can.

This is a reference to some pinned heap allocation, which is non-trivial to create. References are temporary views into another, already existing value. So you usually can't jut synthesize them whenever you want.

Any reason why this has to be a reference?

1 Like

The idea is to have an actor state '''B''' of unknown/variable size as field of actor struct '''A''' which is passed as self object to the '''async fn handle''' running (spawned) into a separate thread. The handle fn then updates state B arbitrarily every time it's called. In summary: how can I mutate a heap object from within a separate thread?

It sounds like you need a Mutex, or perhaps an Arc<Mutex<...>>?

That was it; thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.