Hi! I'm writing a language VM in Rust, and I'd like to implement the formatting of run-time values for debugging/tracing.
The value is defined like this:
enum Value {
Bool(bool),
Object(*mut ()), // omitting the pointee type for representation
}
Since a Value
can represent an invalid object, the formatting function must be unsafe
. So I cannot implement Display
for Value
.
What I came up with next is to implement an unsafe method that returns format_args!
as follows:
impl Value {
pub unsafe fn format_args<'s>(&'s self) -> fmt::Arguments<'s> {
match self {
Value::Bool(b) => format_args!("{}", b),
// inspect the object, and returns an appropriate fmt::Arguments
Value::Object(_) => format_args!("blabla"),
}
}
}
Therefore, the only way I'm left with is to call format!
to generate a String
and return it, which I'd like to avoid because it involves an allocation.
Do you have any idea for implementing unsafe formatting?