示例工程 18-value-semantics-cow

18-value-semantics-cow/Sources/Ch18Kit/COWStack.swift

swift · 1.4 KB

/// 手写写时复制栈:赋值共享存储,首次修改才复制,并记录复制次数。
public struct COWStack<Element> {
    private var storage: Storage<Element>
    /// 这个实例触发过几次存储复制;跟着结构体一起复制。
    public private(set) var copyCount: Int
 
    public init(_ elements: [Element] = []) {
        storage = Storage(elements)
        copyCount = 0
    }
 
    public var count: Int {
        storage.values.count
    }
 
    public var elements: [Element] {
        storage.values
    }
 
    /// 只有引用唯一时才为 true;共享存储时为 false。
    /// 读取需要 `inout self`,因此是 `mutating get`,只能在 `var` 实例上调用。
    public var isUnique: Bool {
        mutating get { isKnownUniquelyReferenced(&storage) }
    }
 
    public mutating func push(_ element: Element) {
        ensureUnique()
        storage.values.append(element)
    }
 
    public mutating func pop() -> Element? {
        guard !storage.values.isEmpty else { return nil }
        ensureUnique()
        return storage.values.popLast()
    }
 
    private mutating func ensureUnique() {
        guard !isKnownUniquelyReferenced(&storage) else { return }
        storage = Storage(storage.values)
        copyCount += 1
    }
}
 
private final class Storage<Element> {
    var values: [Element]
 
    init(_ values: [Element]) {
        self.values = values
    }
}