-
Notifications
You must be signed in to change notification settings - Fork 104
/
KeyedBox.swift
115 lines (92 loc) · 2.54 KB
/
KeyedBox.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
//
// KeyedBox.swift
// XMLCoderPackageDescription
//
// Created by Vincent Esche on 11/19/18.
//
import Foundation
struct KeyedStorage<Key: Hashable & Comparable, Value> {
typealias Buffer = [Key: Value]
fileprivate var buffer: Buffer = [:]
var count: Int {
return buffer.count
}
var keys: Buffer.Keys {
return buffer.keys
}
init(_ buffer: Buffer) {
self.buffer = buffer
}
subscript(key: Key) -> Value? {
get {
return buffer[key]
}
set {
buffer[key] = newValue
}
}
func map<T>(_ transform: (Key, Value) throws -> T) rethrows -> [T] {
return try buffer.map(transform)
}
func compactMap<T>(_ transform: ((Key, Value)) throws -> T?) rethrows -> [T] {
return try buffer.compactMap(transform)
}
}
extension KeyedStorage: Sequence {
typealias Iterator = Buffer.Iterator
func makeIterator() -> Iterator {
return buffer.makeIterator()
}
}
extension KeyedStorage: ExpressibleByDictionaryLiteral {
init(dictionaryLiteral elements: (Key, Value)...) {
self.init(Dictionary(uniqueKeysWithValues: elements))
}
}
extension KeyedStorage: CustomStringConvertible
where Key: Comparable {
var description: String {
return "[\(buffer)]"
}
}
class KeyedBox {
typealias Key = String
typealias Attribute = SimpleBox
typealias Element = Box
typealias Attributes = KeyedStorage<Key, Attribute>
typealias Elements = KeyedStorage<Key, Element>
var attributes: Attributes = [:]
var elements: Elements = [:]
init() {
attributes = [:]
elements = [:]
}
init<E, A>(elements: E, attributes: A)
where E: Sequence, E.Element == (Key, Element), A: Sequence, A.Element == (Key, Attribute) {
self.elements = Elements(Dictionary(uniqueKeysWithValues: elements))
self.attributes = Attributes(Dictionary(uniqueKeysWithValues: attributes))
}
init(elements: [Key: Element], attributes: [Key: Attribute]) {
self.elements = Elements(elements)
self.attributes = Attributes(attributes)
}
func unbox() -> (elements: Elements, attributes: Attributes) {
return (
elements: elements,
attributes: attributes
)
}
}
extension KeyedBox: Box {
var isNull: Bool {
return false
}
func xmlString() -> String? {
return nil
}
}
extension KeyedBox: CustomStringConvertible {
var description: String {
return "\(elements)"
}
}