-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDict.swift
More file actions
236 lines (203 loc) · 6.9 KB
/
Copy pathDict.swift
File metadata and controls
236 lines (203 loc) · 6.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import Foundation
/// Dict (or dictionary) is the primary collection data type in Haystack. Dicts are an unordered collection of
/// name/value pairs that we call *tags*. The name keys of a dict are restricted to ASCII letters, digits and
/// underbar as discussed in the
/// [names](https://project-haystack.org/doc/docHaystack/Kinds#names)
/// section. The values may be be any other valid Haystack data type.
///
/// [Docs](https://project-haystack.org/doc/docHaystack/Kinds#dict)
public struct Dict: Val {
public static var valType: ValType { .Dict }
public static func empty() -> Dict {
return Dict([:])
}
public private(set) var elements: [String: any Val]
public init(_ elements: [String: any Val]) {
self.elements = elements
}
public func trap(_ name: String) throws -> any Val {
guard let fieldVal = elements[name], !(fieldVal is Null) else {
throw DictError.tagNotFound(name)
}
return fieldVal
}
public func trap<T: Val>(_ name: String, as _: T.Type) throws -> T {
guard let fieldVal = elements[name], !(fieldVal is Null) else {
throw DictError.tagNotFound(name)
}
return try fieldVal.coerce(to: T.self)
}
public func get(_ name: String) throws -> (any Val)? {
guard let fieldVal = elements[name], !(fieldVal is Null) else {
return nil
}
return fieldVal
}
public func get<T: Val>(_ name: String, as _: T.Type) throws -> T? {
guard let fieldVal = elements[name], !(fieldVal is Null) else {
return nil
}
return try fieldVal.coerce(to: T.self)
}
public func has(_ name: String) -> Bool {
return elements.keys.contains(name)
}
/// Converts to Zinc formatted string.
/// See [Zinc Literals](https://project-haystack.org/doc/docHaystack/Zinc#literals)
public func toZinc() -> String {
return toZinc(withBraces: true)
}
func toZinc(withBraces: Bool) -> String {
let zincElements = elements.keys.sorted().map { key in
"\(key):\(elements[key]!.toZinc())" // unwrap is safe due to immutability
}
let zinc = zincElements.joined(separator: " ")
if withBraces {
return "{\(zinc)}"
} else {
return zinc
}
}
}
// Dict + Codable
public extension Dict {
internal static let kindValue = "dateTime"
/// Read from decodable data
/// See [JSON format](https://project-haystack.org/doc/docHaystack/Json#dict)
init(from decoder: Decoder) throws {
guard let container = try? decoder.container(keyedBy: DictCodingKey.self) else {
throw DecodingError.typeMismatch(
Self.self,
.init(
codingPath: [],
debugDescription: "Dict representation must be an object"
)
)
}
var elements = [String: any Val]()
containerLoop: for key in container.allKeys {
if key.stringValue == "_kind" {
guard
let value = try? container.decode(String.self, forKey: key),
value == Self.kindValue
else {
throw DecodingError.typeMismatch(
Self.self,
.init(
codingPath: [key],
debugDescription: "Expected `_kind` to have value `\"\(Self.kindValue)\"`"
)
)
}
} else {
let val = try container.decode(AnyVal.self, forKey: key)
elements[key.stringValue] = val.val
}
}
self.elements = elements
}
/// Write to encodable data
/// See [JSON format](https://project-haystack.org/doc/docHaystack/Json#dict)
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: DictCodingKey.self)
for (key, value) in elements {
guard let codingKey = DictCodingKey(stringValue: key) else {
throw EncodingError.invalidValue(
self,
.init(
codingPath: [],
debugDescription: "CodingKey not found: \(key)"
)
)
}
try container.encode(value, forKey: codingKey)
}
}
private struct DictCodingKey: CodingKey {
let stringValue: String
let intValue: Int?
init?(stringValue: String) {
self.stringValue = stringValue
intValue = Int(stringValue)
}
init?(intValue: Int) {
stringValue = "\(intValue)"
self.intValue = intValue
}
}
}
// Dict + Equatable
public extension Dict {
static func == (lhs: Dict, rhs: Dict) -> Bool {
guard lhs.elements.count == rhs.elements.count else {
return false
}
guard lhs.elements.keys == rhs.elements.keys else {
return false
}
for key in lhs.elements.keys {
guard
let lhsValue = lhs.elements[key],
let rhsValue = rhs.elements[key]
else {
return false
}
guard lhsValue.equals(rhsValue) else {
return false
}
}
return true
}
}
// Dict + Hashable
public extension Dict {
func hash(into hasher: inout Hasher) {
for (key, value) in elements {
hasher.combine(key)
hasher.combine(value)
}
}
}
// Dict + Collection
extension Dict: Collection {
public var startIndex: Dictionary<String, any Val>.Index {
elements.keys.startIndex
}
public var endIndex: Dictionary<String, any Val>.Index {
elements.keys.endIndex
}
public subscript(position: Dictionary<String, any Val>.Index) -> (key: String, value: any Val) {
return elements[position]
}
public func index(after i: Dictionary<String, any Val>.Index) -> Dictionary<String, any Val>.Index {
return elements.index(after: i)
}
}
// Convenience string accessor
public extension Dict {
subscript(key: String) -> (any Val)? {
get {
let val = elements[key]
guard !(val is Null) else {
return nil
}
return val
}
set {
elements[key] = newValue
}
}
}
extension Dict: ExpressibleByDictionaryLiteral {
/// Creates an instance initialized with the given key-value pairs.
public init(dictionaryLiteral elementLiterals: (String, any Val)...) {
var elements = [String: any Val](minimumCapacity: elementLiterals.count)
for (key, value) in elementLiterals {
elements[key] = value
}
self.elements = elements
}
}
public enum DictError: Error {
case tagNotFound(String)
}