Search code examples
rustserde

Associate unique identifier with rust function definitions


I have a struct that I would like to serialize to disk as part of a JSON save file format. The (simplified) structure of the struct is like this:

pub struct Effect {
  pub source: Source,
  pub duration: Duration,
  pub implementation: fn(&mut GameState, Source) -> Result<()>
}

I would like to serialize this structure via serde. Serializing function pointers is not possible, of course, so what I want to do is annotate each function I use as an implementation with a unique ID, write that ID as part of the saved JSON, and then use the ID to look up the function pointer to use when deserializing the structure, probably by building up a big map of functionId->functionPointer as a fist step. Is there a nice way for me to tag function definitions with this kind of metadata?

(note: I'm aware that I could convert Effect to a trait, but I really want to use function pointers here for a bunch of reasons -- ergonomics, performance, lots of existing code depending on this structure, etc)


Solution

  • Function pointers point directly to machine code. There is no way to attach additional metadata to them. You cannot compare the function pointers, either: you may experience both false negatives (functions which happened to be compiled twice) and false positives (functions whose machine code was deduplicated with another function that happens to have identical code).

    The only way you can possibly get reliable information about a function pointer is to call it and see what it does. But at that point, you might as well use a trait object instead, rather than getting fancy with the function signature. The trait object can have a method for doing the operation and a method for asking for its ID in the serialization table.