Cow 1.0.0

Cow 1.0.0

TestsTested
LangLanguage SwiftSwift
License BSD
ReleasedLast Release Feb 2015
SPMSupports SPM

Maintained by Vincent Esche.



Cow 1.0.0

  • By
  • Vincent Esche

Cow

Cow

Cow aims to provide a simple and easy to integrate copy-on-write layer for your own Swift data structures.

Cow works on both iOS (8.0 or later) and OS X (10.9 or later).

Installation

Just copy the files in "Cow/Classes/..." into your project.

Alternatively you can install Cow into your project with CocoaPods.
Just add it to your Podfile: pod 'Cow'

Usage

(See CowTests.swift for sample use of Cow<…>)

Add a CoW wrapping your internal expensive data object as a member to your class:

class Container {
    typealias CoW = Cow<SomeExpensiveInternalObject>
    private(set) var cow: CoW
    // ...
}

Initialize your class like this:

init() {
    let initialValue = Value()
    self.cow = CoW(initialValue) {
        Value($0) // used for copying on write
    }
    // ...
}

Provide a copy initializer like this:

init(_ other: Container) {
    self.cow = CoW.attachTo(other.cow)
    // ...
}

Add a deinitializer like this:

deinit {
    self.cow.detach()
}

And last but not least wrap all mutating logic like this:

mutate(&self.cow) { value in
    // mutate or even re-assign `value` (it's an inout parameter)
    return
}

Non-mutating logic can just be forwarded to self.cow.value.

How it works

Instances of Cow<…> keep track of how many owners are attached to it and detach copies of itself when appropriate.

The mutate function checks if the provided cow is shared amongst multiple owners and create a copy of the cow (along with its value), overwrite the provided cow with it and then pass it to the closure for performing the actual mutating logic.

Limitations

If Swift structs provided a means of hooking into its runtime-defined copying and deinitialization routines for structs (which unfortunately is not the case), one could use Cow to wrap complex class-based data structures (such as lists, trees, graphs, e.g.) with a light-weight struct, turning them into value types with optimal copy performance (O(1)) and minimal memory consumption. It doesn’t though.

As such Cow mostly remains a proof of concept and a fun coding excercise.

Unit Tests

Cow contains unit tests.

Dependencies

None.

Creator

Vincent Esche (@regexident)

License

Cow is available under a modified BSD-3 clause license with the additional requirement of attribution. See the LICENSE file for more info.