mozilla/rust — pull request #9786 by bill-myers (2013-10-09 22:04:59+00:00)
Title: add copy-on-write mutable borrowing to Rc and Arc

This patch adds a copy-on-write mechanism to Rc and Arc of Clonable types that allows to mutably borrow the contents.

In the simplest case, if the reference count is 1, we can just give out a mutable reference since we are obviously the only user.

If the reference count is more than 1, we clone the contents, and we are back to the previous case.

With this change, Rc and Arc can be used as a variant of unique pointers with the advantage of O(1) time and space copy (as long as the contents are not mutated) but the disadvantage of requiring an extra machine branch and a bunch of machine code on every mutation.

This can be used for things like persistent functional data structures and in general data that starts being the same as parent data, but sometimes gets changed.