Unsafe formatting

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"),
        }
    }
}

However, this method does not compile since the returned format_args! contains references to local variables such as b.

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?

You could have a type that can only be unsafely constructed which implements Display:

enum Value {
    Bool(bool),
    Object(*mut ()), // omitting the pointee type for representation
}

struct Valid<'a>(&'a Value);

impl Value {
    unsafe fn assume_valid(&self)->Valid<'_> { Valid(self) }
}

impl Display for Valid<'_> {
    /* ... */
}
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.