|
| 1 | +// |
| 2 | +// Heap.swift |
| 3 | +// Common |
| 4 | +// |
| 5 | +// Created by {{ cookiecutter.creator }} on {% now 'utc', '%d/%m/%Y' %}. |
| 6 | +// Copyright © {% now 'utc', '%Y' %} {{cookiecutter.company_name}}. All rights reserved. |
| 7 | +// |
| 8 | + |
| 9 | +private final class Reference<T: Equatable>: Equatable { |
| 10 | + var value: T |
| 11 | + init(_ value: T) { |
| 12 | + self.value = value |
| 13 | + } |
| 14 | + static func == (lhs: Reference<T>, rhs: Reference<T>) -> Bool { |
| 15 | + lhs.value == rhs.value |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +@propertyWrapper public struct Heap<T: Equatable>: Equatable { |
| 20 | + private var reference: Reference<T> |
| 21 | + |
| 22 | + public init(_ value: T) { |
| 23 | + reference = .init(value) |
| 24 | + } |
| 25 | + |
| 26 | + public var wrappedValue: T { |
| 27 | + get { reference.value } |
| 28 | + set { |
| 29 | + if !isKnownUniquelyReferenced(&reference) { |
| 30 | + reference = .init(newValue) |
| 31 | + return |
| 32 | + } |
| 33 | + reference.value = newValue |
| 34 | + } |
| 35 | + } |
| 36 | + public var projectedValue: Heap<T> { |
| 37 | + self |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +extension Heap: Hashable where T: Hashable { |
| 42 | + public func hash(into hasher: inout Hasher) { |
| 43 | + hasher.combine(wrappedValue) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +extension Heap: Decodable where T: Decodable { |
| 48 | + public init(from decoder: Decoder) throws { |
| 49 | + let container = try decoder.singleValueContainer() |
| 50 | + let value = try container.decode(T.self) |
| 51 | + self = Heap(value) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +extension Heap: Encodable where T: Encodable { |
| 56 | + public func encode(to encoder: Encoder) throws { |
| 57 | + var container = encoder.singleValueContainer() |
| 58 | + try container.encode(wrappedValue) |
| 59 | + } |
| 60 | +} |
0 commit comments