Serializing TypeId

Can std::any::TypeId be safely serialized/deserialized (as a byte array) under the specific limited condition that the only program that will deserialize the TypeId will be the one that serialized it, and that it will be assumed that TypeId can change if the program is recompiled?

1 Like

From the TypeId page:

While TypeId implements Hash, PartialOrd, and Ord, it is worth noting that the hashes and ordering will vary between Rust releases. Beware of relying on them inside of your code!

So yes, according to this, what you have described above would work, but you probably shouldn’t, and should instead use an Enum. You probably shouldn’t use this to load dynamic types from a file though, as that would be some really weird UB territory.

1 Like

Not planning to load dynamic types from a file. The specific thing I’m building is a “Session Types” crate for a parallel communications library that otherwise does not guarantee type safety. One quick, cheap sanity check that all processes are using the same session type would be to exchange the TypeId for the session type and check that they match across processes (which should all be running the same executable).

That was my interpretation of that text, too - I just wanted to make sure I was interpreting it correctly. Thanks!

Oh, then that makes more sense, but I’d advise using something else other than the TypeId for validating the version of the executable, as it may change through rust version, and not specifically executable version. I’d instead figure out a way to get the cargo project version and use that.

It’s actually not a stand in for the executable version - it’s supposed to verify that all processes in the parallel run are using the same session type for the communication. It’s possible that a single executable would have many session types, so you need to verify that one of the processes isn’t going rogue and instantiating the communication with a different session type than the rest of the processes in the parallel execution.

The “same process version” rule would just be enforced by convention.

1 Like

Depending on what you mean by “going rogue,” a rogue process could also send a deliberately incorrect typeid…

For sure - this isn’t to enforce security, it’s to check correctness.

i.e. essentially guarding against/detecting cases like this where one rank in the parallel run inadvertently uses the wrong session type:

// This condition is probably more obscure
if rank == 7 {
    let session = BadSessionType::new(comm);
    // use comm
} else {
    let session = GoodSessionType::new(comm);
    // use comm

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