Created
December 28, 2021 06:09
-
-
Save tgnivekucn/7085e6009baa3217d636107c5a4b0e97 to your computer and use it in GitHub Desktop.
Use copy-on-write semantics for large values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class Ref<T> { | |
var val: T | |
init(_ v: T) {val = v} | |
} | |
struct Box<T> { | |
var ref: Ref<T> | |
init(_ x: T) { ref = Ref(x) } | |
var value: T { | |
get { return ref.val } | |
set { | |
if !isKnownUniquelyReferenced(&ref) { | |
ref = Ref(newValue) | |
return | |
} | |
ref.val = newValue | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment