Skip to content

Commit cd277e2

Browse files
author
Sandin
committed
added canonical cbor map key sorting
1 parent 0209a2d commit cd277e2

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

Sources/SwiftCBOR/CBOREncoder.swift

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,24 @@ extension CBOR {
125125
res.append(contentsOf: arr.flatMap{ return $0.encode() })
126126
return res
127127
}
128+
129+
// MARK: sortHelper
130+
131+
public static func keyOrder(a: [UInt8], b: [UInt8]) -> Bool {
132+
if a.count == b.count {
133+
for (index, byteA) in a.enumerated() {
134+
let byteB = b[index]
135+
if byteA == byteB {
136+
continue
137+
} else {
138+
return byteA < byteB
139+
}
140+
}
141+
return false
142+
} else {
143+
return a.count < b.count
144+
}
145+
}
128146

129147
// MARK: - major 5: a map of pairs of data items
130148

@@ -133,10 +151,16 @@ extension CBOR {
133151
res.reserveCapacity(1 + map.count * (MemoryLayout<A>.size + MemoryLayout<B>.size + 2))
134152
res = map.count.encode()
135153
res[0] = res[0] | 0b101_00000
136-
for (k, v) in map {
137-
res.append(contentsOf: k.encode())
138-
res.append(contentsOf: v.encode())
154+
155+
let sortedEntries = map
156+
.map { k, v in (k.encode(), v.encode()) }
157+
.sorted { a, b in keyOrder(a: a.0, b: b.0) }
158+
159+
for (k, v) in sortedEntries {
160+
res.append(contentsOf: k)
161+
res.append(contentsOf: v)
139162
}
163+
140164
return res
141165
}
142166

0 commit comments

Comments
 (0)