redjack/libcork — pull request #52 by dcreager (2013-04-22 19:33:50+00:00)
Title: More efficient slices

This two patches add some efficiency to the slice interface. You can now make "light" copies of a slice, which means that you (as the caller) are guaranteeing that the new copy cannot possibly outlive the source slice. Some slice implementations are able to make light copies more efficiently than the previous "normal" or "heavy" copies.

In particular, the new "copy-once" slice is used to wrap an existing buffer. This is only valid if the caller guarantees that the buffer will outlive the slice. If you make a light copy of this kind of slice, the guarantee extends to the light copy: since the buffer outlives the original slice, and the original slice outlives the light copy, then the buffer outlives the light copy. So for light copies of a copy-once slice, we can use the same pointer, and not have to make a real copy of the data.

For a heavy copy of a copy-once slice, however, we can't make any guarantees about how the original data buffer relates to the copied slice. So for those, we have to actually copy the underlying buffer. We actually a managed buffer, which lets us bump refcounts for any further copies. Hence the name "copy-once" — with a copy-once slice, we'll make at most one copy of the underlying wrapped buffer, and only do that when needed.