forked from m-rimestad/BinaryCoder
-
Notifications
You must be signed in to change notification settings - Fork 2
/
BinaryCodableExtensions.swift
68 lines (58 loc) · 1.94 KB
/
BinaryCodableExtensions.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
/// Implementations of BinaryCodable for built-in types.
import Foundation
extension Array: BinaryCodable where Element: Codable {
public func binaryEncode(to encoder: BinaryEncoder) throws {
try encoder.encode(self.count)
for element in self {
try (element).encode(to: encoder)
}
}
public init(fromBinary decoder: BinaryDecoder) throws {
let count = try decoder.decode(Int.self)
self.init()
self.reserveCapacity(count)
for _ in 0 ..< count {
let decoded = try Element.self.init(from: decoder)
self.append(decoded)
}
}
}
extension String: BinaryCodable {
public func binaryEncode(to encoder: BinaryEncoder) throws {
try Array(self.utf8).binaryEncode(to: encoder)
}
public init(fromBinary decoder: BinaryDecoder) throws {
let utf8: [UInt8] = try Array(fromBinary: decoder)
if let str = String(bytes: utf8, encoding: .utf8) {
self = str
} else {
throw BinaryDecoder.Error.invalidUTF8(utf8)
}
}
}
extension FixedWidthInteger where Self: BinaryEncodable {
public func binaryEncode(to encoder: BinaryEncoder) {
encoder.appendBytes(of: self.bigEndian)
}
}
extension FixedWidthInteger where Self: BinaryDecodable {
public init(fromBinary binaryDecoder: BinaryDecoder) throws {
var v = Self.init()
try binaryDecoder.read(into: &v)
self.init(bigEndian: v)
}
}
// for size in [8, 16, 32, 64] {
// for prefix in ["", "U"] {
// print("extension \(prefix)Int\(size): BinaryCodable {}")
// }
// }
// Copy the above snippet, then run: `pbpaste | swift`
extension Int8: BinaryCodable {}
extension UInt8: BinaryCodable {}
extension Int16: BinaryCodable {}
extension UInt16: BinaryCodable {}
extension Int32: BinaryCodable {}
extension UInt32: BinaryCodable {}
extension Int64: BinaryCodable {}
extension UInt64: BinaryCodable {}