HarfBuzz is a great example of memory managmenet done right (in C)

I'm currently reading through the HarfBuzz library, and I think it's a great example of what is required to be memory-safe in C (and what the rust compiler does automatically for us).

Take the hb_blob_t. This data type is roughly equivalent to an Arc<[u8]> in Rust - it looks after an array of bytes and provides reference counting services. Let's look at the constructor.

hb_blob_t *
hb_blob_create (const char *data,
    unsigned int length,
    hb_memory_mode_t mode,
    void *user_data,
    hb_destroy_func_t destroy);

Firstly we need a pointer to the data and its length. In rust we would pass a &[u8] which contains both these pieces of information, known as a "fat pointer". The next parameter is interesting - hb_memory_mode_t. Its signature is

enum hb_memory_mode_t {
    // internals ommitted...

Here the HarfBuzz library is helping us manage mutability at run-time (what std::borrow::Cow does for us in Rust). We can give HarfBuzz data and continue to hold an immutable reference to it in Rust if we use HB_MEMORY_MODE_READONLY, whereas if we pass the WRITABLE variant then HarfBuzz does not guarantee that it will leave our data alone. The final 2 parameters show how to handle memory management over an FFI boundary: HarfBuzz will call destroy(user_data) when it knows it doesn't need the data any more. C code using this library might simply pass data and free here, but in Rust we might want to do something more compilcated (like decrement the reference count on an Arc).

hb_blob_t also implements copy-on-write semantics (like std::borrow::Cow), so you can give HarfBuzz an immutable data source, and then ask to make it mutable (with a memcpy of the data if necessary).

Anyway end of my random musings. I just thought it was a good exposition of how complex memory management is in C, and also how much it is the user's responsibility! It also shows how memory management would need to work in a complex C FFI interface to a rust crate.


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.