forked from CoreOffice/XMLCoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
XMLEncoderImplementation.swift
288 lines (247 loc) · 9.43 KB
/
XMLEncoderImplementation.swift
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
//
// XMLEncoder.swift
// XMLCoder
//
// Created by Shawn Moore on 11/22/17.
// Copyright © 2017 Shawn Moore. All rights reserved.
//
import Foundation
class XMLEncoderImplementation: Encoder {
// MARK: Properties
/// The encoder's storage.
var storage: XMLEncodingStorage
/// Options set on the top-level encoder.
let options: XMLEncoder.Options
/// The path to the current point in encoding.
public var codingPath: [CodingKey]
public var nodeEncodings: [(CodingKey) -> XMLEncoder.NodeEncoding]
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey: Any] {
return options.userInfo
}
// MARK: - Initialization
/// Initializes `self` with the given top-level encoder options.
init(
options: XMLEncoder.Options,
nodeEncodings: [(CodingKey) -> XMLEncoder.NodeEncoding],
codingPath: [CodingKey] = []
) {
self.options = options
storage = XMLEncodingStorage()
self.codingPath = codingPath
self.nodeEncodings = nodeEncodings
}
/// Returns whether a new element can be encoded at this coding path.
///
/// `true` if an element has not yet been encoded at this coding path; `false` otherwise.
var canEncodeNewValue: Bool {
// Every time a new value gets encoded, the key it's encoded for is
// pushed onto the coding path (even if it's a nil key from an unkeyed container).
// At the same time, every time a container is requested, a new value
// gets pushed onto the storage stack.
// If there are more values on the storage stack than on the coding path,
// it means the value is requesting more than one container, which
// violates the precondition.
//
// This means that anytime something that can request a new container
// goes onto the stack, we MUST push a key onto the coding path.
// Things which will not request containers do not need to have the
// coding path extended for them (but it doesn't matter if it is,
// because they will not reach here).
return storage.count == codingPath.count
}
// MARK: - Encoder Methods
public func container<Key>(keyedBy _: Key.Type) -> KeyedEncodingContainer<Key> {
guard canEncodeNewValue else {
return mergeWithExistingKeyedContainer(keyedBy: Key.self)
}
if Key.self is XMLChoiceCodingKey.Type {
return choiceContainer(keyedBy: Key.self)
} else {
return keyedContainer(keyedBy: Key.self)
}
}
public func unkeyedContainer() -> UnkeyedEncodingContainer {
// If an existing unkeyed container was already requested, return that one.
let topContainer: SharedBox<UnkeyedBox>
if canEncodeNewValue {
// We haven't yet pushed a container at this level; do so here.
topContainer = storage.pushUnkeyedContainer()
} else {
guard let container = storage.lastContainer as? SharedBox<UnkeyedBox> else {
preconditionFailure(
"""
Attempt to push new unkeyed encoding container when already previously encoded \
at this path.
"""
)
}
topContainer = container
}
return XMLUnkeyedEncodingContainer(referencing: self, codingPath: codingPath, wrapping: topContainer)
}
public func singleValueContainer() -> SingleValueEncodingContainer {
return self
}
private func keyedContainer<Key>(keyedBy _: Key.Type) -> KeyedEncodingContainer<Key> {
let container = XMLKeyedEncodingContainer<Key>(
referencing: self,
codingPath: codingPath,
wrapping: storage.pushKeyedContainer()
)
return KeyedEncodingContainer(container)
}
private func choiceContainer<Key>(keyedBy _: Key.Type) -> KeyedEncodingContainer<Key> {
let container = XMLChoiceEncodingContainer<Key>(
referencing: self,
codingPath: codingPath,
wrapping: storage.pushChoiceContainer()
)
return KeyedEncodingContainer(container)
}
private func mergeWithExistingKeyedContainer<Key>(keyedBy _: Key.Type) -> KeyedEncodingContainer<Key> {
switch storage.lastContainer {
case let keyed as SharedBox<KeyedBox>:
let container = XMLKeyedEncodingContainer<Key>(
referencing: self,
codingPath: codingPath,
wrapping: keyed
)
return KeyedEncodingContainer(container)
case let choice as SharedBox<ChoiceBox>:
_ = storage.popContainer()
let keyed = KeyedBox(
elements: KeyedBox.Elements([choice.withShared { ($0.key, $0.element) }]),
attributes: []
)
let container = XMLKeyedEncodingContainer<Key>(
referencing: self,
codingPath: codingPath,
wrapping: storage.pushKeyedContainer(keyed)
)
return KeyedEncodingContainer(container)
default:
preconditionFailure(
"""
No existing keyed encoding container to merge with.
"""
)
}
}
}
extension XMLEncoderImplementation {
/// Returns the given value boxed in a container appropriate for pushing onto the container stack.
func box() -> SimpleBox {
return NullBox()
}
func box(_ value: Bool) -> SimpleBox {
return BoolBox(value)
}
func box(_ value: Decimal) -> SimpleBox {
return DecimalBox(value)
}
func box<T: BinaryInteger & SignedInteger & Encodable>(_ value: T) -> SimpleBox {
return IntBox(value)
}
func box<T: BinaryInteger & UnsignedInteger & Encodable>(_ value: T) -> SimpleBox {
return UIntBox(value)
}
func box(_ value: Float) throws -> SimpleBox {
return try box(value, FloatBox.self)
}
func box(_ value: Double) throws -> SimpleBox {
return try box(value, DoubleBox.self)
}
func box<T: BinaryFloatingPoint & Encodable, B: ValueBox>(
_ value: T,
_: B.Type
) throws -> SimpleBox where B.Unboxed == T {
guard value.isInfinite || value.isNaN else {
return B(value)
}
guard case let .convertToString(
positiveInfinity: posInfString,
negativeInfinity: negInfString,
nan: nanString
) = options.nonConformingFloatEncodingStrategy else {
throw EncodingError._invalidFloatingPointValue(value, at: codingPath)
}
if value == T.infinity {
return StringBox(posInfString)
} else if value == -T.infinity {
return StringBox(negInfString)
} else {
return StringBox(nanString)
}
}
func box(_ value: String) -> SimpleBox {
return StringBox(value)
}
func box(_ value: Date) throws -> Box {
switch options.dateEncodingStrategy {
case .deferredToDate:
try value.encode(to: self)
return storage.popContainer()
case .secondsSince1970:
return DateBox(value, format: .secondsSince1970)
case .millisecondsSince1970:
return DateBox(value, format: .millisecondsSince1970)
case .iso8601:
return DateBox(value, format: .iso8601)
case let .formatted(formatter):
return DateBox(value, format: .formatter(formatter))
case let .custom(closure):
let depth = storage.count
try closure(value, self)
guard storage.count > depth else {
return KeyedBox()
}
return storage.popContainer()
}
}
func box(_ value: Data) throws -> Box {
switch options.dataEncodingStrategy {
case .deferredToData:
try value.encode(to: self)
return storage.popContainer()
case .base64:
return DataBox(value, format: .base64)
case let .custom(closure):
let depth = storage.count
try closure(value, self)
guard storage.count > depth else {
return KeyedBox()
}
return storage.popContainer()
}
}
func box(_ value: URL) -> SimpleBox {
return URLBox(value)
}
func box<T: Encodable>(_ value: T) throws -> Box {
if T.self == Date.self || T.self == NSDate.self,
let value = value as? Date {
return try box(value)
} else if T.self == Data.self || T.self == NSData.self,
let value = value as? Data {
return try box(value)
} else if T.self == URL.self || T.self == NSURL.self,
let value = value as? URL {
return box(value)
} else if T.self == Decimal.self || T.self == NSDecimalNumber.self,
let value = value as? Decimal {
return box(value)
}
let depth = storage.count
try value.encode(to: self)
// The top container should be a new container.
guard storage.count > depth else {
return KeyedBox()
}
let lastContainer = storage.popContainer()
guard let sharedBox = lastContainer as? TypeErasedSharedBoxProtocol else {
return lastContainer
}
return sharedBox.typeErasedUnbox()
}
}