-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDataRepresentable.swift
83 lines (70 loc) · 2.24 KB
/
DataRepresentable.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
import Foundation
public protocol DataRepresentable {
var dataRepresentation: Data { get }
init?(dataRepresentation: Data)
}
extension DataRepresentable {
public static func converting(_ representable: DataRepresentable) -> Self? {
return .init(dataRepresentation: representable.dataRepresentation)
}
}
extension Data: DataRepresentable {
public var dataRepresentation: Data { self }
public init(dataRepresentation data: Data) {
self = data
}
}
extension String: DataRepresentable {
public var dataRepresentation: Data { data(using: .utf8)! }
public init?(dataRepresentation data: Data) {
self.init(data: data, encoding: .utf8)
}
}
extension Bool: DataRepresentable {
public var dataRepresentation: Data {
var value = self
return Data(bytes: &value, count: MemoryLayout<Self>.size)
}
public init?(dataRepresentation: Data) {
let size = MemoryLayout<Self>.size
guard dataRepresentation.count == size else { return nil }
var value: Bool = false
let actualSize = withUnsafeMutableBytes(of: &value, {
dataRepresentation.copyBytes(to: $0)
})
assert(actualSize == MemoryLayout.size(ofValue: value))
self = value
}
}
extension Numeric {
public var dataRepresentation: Data {
var value = self
return Data(bytes: &value, count: MemoryLayout<Self>.size)
}
public init?(dataRepresentation: Data) {
let size = MemoryLayout<Self>.size
guard dataRepresentation.count == size else { return nil }
var value: Self = .zero
let actualSize = withUnsafeMutableBytes(of: &value, {
dataRepresentation.copyBytes(to: $0)
})
assert(actualSize == MemoryLayout.size(ofValue: value))
self = value
}
}
extension Int: DataRepresentable {}
extension Int8: DataRepresentable {}
extension Int16: DataRepresentable {}
extension Int32: DataRepresentable {}
extension Int64: DataRepresentable {}
extension UInt: DataRepresentable {}
extension UInt8: DataRepresentable {}
extension UInt16: DataRepresentable {}
extension UInt32: DataRepresentable {}
extension UInt64: DataRepresentable {}
extension Double: DataRepresentable {}
extension Float: DataRepresentable {}
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import CoreGraphics
extension CGFloat: DataRepresentable {}
#endif