-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathList.swift
More file actions
111 lines (94 loc) · 2.89 KB
/
Copy pathList.swift
File metadata and controls
111 lines (94 loc) · 2.89 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
import Foundation
/// List is a collection data type. Lists are ordered sequences and may contain any other valid
/// Haystack data types.
///
/// [Docs](https://project-haystack.org/doc/docHaystack/Kinds#list)
public struct List: Val {
public static var valType: ValType { .List }
public private(set) var elements: [any Val]
public init(_ elements: [any Val]) {
self.elements = elements
}
/// Converts to Zinc formatted string.
/// See [Zinc Literals](https://project-haystack.org/doc/docHaystack/Zinc#literals)
public func toZinc() -> String {
let zincElements = elements.map { $0.toZinc() }
return "[\(zincElements.joined(separator: ", "))]"
}
public func toSwiftArray() -> [any Val] {
return elements
}
}
// List + Codable
public extension List {
/// Read from decodable data
/// See [JSON format](https://project-haystack.org/doc/docHaystack/Json#list)
init(from decoder: Decoder) throws {
guard var container = try? decoder.unkeyedContainer() else {
throw DecodingError.typeMismatch(
Self.self,
.init(
codingPath: [],
debugDescription: "List representation must be an array"
)
)
}
var elements = [any Val]()
containerLoop: while !container.isAtEnd {
let val = try container.decode(AnyVal.self)
elements.append(val.val)
}
self.elements = elements
}
/// Write to encodable data
/// See [JSON format](https://project-haystack.org/doc/docHaystack/Json#list)
func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for element in elements {
try container.encode(element)
}
}
}
// List + Equatable
public extension List {
static func == (lhs: List, rhs: List) -> Bool {
guard lhs.elements.count == rhs.elements.count else {
return false
}
for (lhsElement, rhsElement) in zip(lhs.elements, rhs.elements) {
guard lhsElement.equals(rhsElement) else {
return false
}
}
return true
}
}
// List + Hashable
public extension List {
func hash(into hasher: inout Hasher) {
for element in elements {
hasher.combine(element)
}
}
}
// List + Collection
extension List: Collection {
public var startIndex: Int {
elements.startIndex
}
public var endIndex: Int {
elements.endIndex
}
public subscript(position: Int) -> any Val {
return elements[position]
}
public func index(after i: Int) -> Int {
return i + 1
}
}
extension List: ExpressibleByArrayLiteral {
/// Creates an instance initialized with the given elements.
public init(arrayLiteral: any Val...) {
elements = arrayLiteral
}
}