forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNIOUtils.swift
60 lines (53 loc) · 1.95 KB
/
NIOUtils.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
import Foundation
import NIOCore
internal extension ByteBuffer {
mutating func readInteger<E>(endianness: Endianness = .big, as rawRepresentable: E.Type) -> E? where E: RawRepresentable, E.RawValue: FixedWidthInteger {
guard let rawValue = readInteger(endianness: endianness, as: E.RawValue.self) else {
return nil
}
return E.init(rawValue: rawValue)
}
mutating func readNullableBytes() -> ByteBuffer? {
guard let count: Int = readInteger(as: Int32.self).flatMap(numericCast) else {
return nil
}
switch count {
case -1:
// As a special case, -1 indicates a NULL parameter value. No value bytes follow in the NULL case.
return nil
default: return readSlice(length: count)
}
}
mutating func write<T>(array: [T], closure: (inout ByteBuffer, T) -> ()) {
self.writeInteger(numericCast(array.count), as: Int16.self)
for el in array {
closure(&self, el)
}
}
mutating func write<T>(array: [T]) where T: FixedWidthInteger {
self.write(array: array) { buffer, el in
buffer.writeInteger(el)
}
}
mutating func write<T>(array: [T]) where T: RawRepresentable, T.RawValue: FixedWidthInteger {
self.write(array: array) { buffer, el in
buffer.writeInteger(el.rawValue)
}
}
mutating func read<T>(array type: T.Type, _ closure: (inout ByteBuffer) throws -> (T)) rethrows -> [T]? {
guard let count: Int = readInteger(as: Int16.self).flatMap(numericCast) else {
return nil
}
var array: [T] = []
array.reserveCapacity(count)
for _ in 0..<count {
try array.append(closure(&self))
}
return array
}
}
internal extension Sequence where Element == UInt8 {
func hexdigest() -> String {
return reduce("") { $0 + String(format: "%02x", $1) }
}
}