Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

optimization - How can I make a container with copy-on-write semantics? (Swift)

I have a very large structure, which I want to ensure is not copied needlessly. How can I make a copy-on-write container for it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A copy-on-write is usually a struct wrapper over some backing object.

public final class MutableHeapStore<T>: NonObjectiveCBase
{
    public typealias Storage = T

    public private(set) var storage: Storage

    public init(storage: Storage)
    {
        self.storage = storage
    }
}

public struct COW<T>
{
    public typealias Storage = MutableHeapStore<T>
    public typealias Value = T

    public var storage: Storage

    public init(storage: Storage)
    {
        self.storage = storage
    }

    public var value: Value
    {
        get
        {
            return storage.storage
        }

        set
        {
            if isUniquelyReferenced(&storage)
            {
                storage.storage = newValue
            }

            else
            {
                storage = Storage(storage: newValue)
            }
        }
    }

    public init(_ value: Value)
    {
        self.init(storage: Storage(storage: value))
    }
}

extension COW: CustomStringConvertible
{
    public var description: String
    {
        return String(value)
    }
}

The trick lies in asserting isUniquelyReferenced every time the boxed value is mutated. If the underlying storage object is singly referenced, nothing is to be done. However if another reference exists, one must create a new storage.

Is this code thread-safe? It is exactly as safe as any other value type, e.g. Int or Bool.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...