forked from vapor/postgres-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtilities.swift
79 lines (67 loc) · 2.11 KB
/
Utilities.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
import Bits
import Foundation
extension Data {
public var hexDebug: String {
return "0x" + map { String(format: "%02X", $0) }.joined(separator: " ")
}
}
extension UnsafeBufferPointer {
public var unsafeBaseAddress: UnsafePointer<Element> {
guard let baseAddress = self.baseAddress else {
fatalError("Unexpected nil baseAddress for \(self)")
}
return baseAddress
}
}
extension UnsafeRawBufferPointer {
public var unsafeBaseAddress: UnsafeRawPointer {
guard let baseAddress = self.baseAddress else {
fatalError("Unexpected nil baseAddress for \(self)")
}
return baseAddress
}
}
extension Data {
internal mutating func unsafePopFirst() -> Byte {
guard let byte = popFirst() else {
fatalError("Unexpected end of data")
}
return byte
}
internal mutating func skip(_ n: Int) {
guard n < count else {
self = Data()
return
}
for _ in 0..<n {
assert(popFirst() != nil)
}
}
internal mutating func skip<T>(sizeOf: T.Type) {
skip(MemoryLayout<T>.size)
}
/// Casts data to a supplied type.
internal mutating func extract<T>(_ type: T.Type = T.self) -> T {
assert(MemoryLayout<T>.size <= count, "Insufficient data to exctract: \(T.self)")
defer { skip(sizeOf: T.self) }
return withUnsafeBytes { (pointer: UnsafePointer<T>) -> T in
return pointer.pointee
}
}
internal mutating func extract(count: Int) -> Data {
assert(self.count >= count, "Insufficient data to extract bytes.")
defer { skip(count) }
return withUnsafeBytes({ (pointer: UnsafePointer<UInt8>) -> Data in
let buffer = UnsafeBufferPointer(start: pointer, count: count)
return Data(buffer)
})
}
}
extension Data {
/// Casts data to a supplied type.
internal func unsafeCast<T>(to type: T.Type = T.self) -> T {
return withUnsafeBytes { (pointer: UnsafePointer<T>) -> T in
return pointer.pointee
}
}
}