Subrc: a pointer to a descendant member of a reference counted pointer (`Rc`)

60 points hillin

I had this interesting use case: there is a huge struct, it's a config object consists of hundreds of fields, organized in a deeply nested structure. Since we don't want to make copies of such a huge object, its sole instance is wrapped in a reference counted pointer Rc to be passed around and stored in the components.

However, most components only care about part of the configuration tree, or a "subregion" of the huge config object; but since the object is behind a Rc, I found there is no built-in way to store a reference to that subregion only. For some reason it is also not desirable to split the config up and let each component to keep a copy of only the part it's interested in. To make every component storing the whole config tree just feels so wrong, so I created this little crate: subrc. It does one simple job: expose a subregion - member / member of member etc. - of a Rc object, as a pointer. The reference counts on the Rc object, but you get to only access that subregion.

A very simple example:

struct Foo {
    value: i32,
}

let rc = Rc::new(Foo { value: 42 });
let subrc = Subrc::new(rc.clone(), |foo| &foo.value);
// or 
let subrc = subrc!(rc.value);

// subrc derefs to 42
assert_eq!(*subrc, 42);
// subrc points to rc.value
assert!(std::ptr::eq(&*subrc, &rc.value));

Let me know your thoughts on it!