/
Buffer.swift
203 lines (177 loc) · 5.42 KB
/
Buffer.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
//
// Buffer.swift
// Macro
//
// Created by Helge Hess.
// Copyright © 2020 ZeeZide GmbH. All rights reserved.
//
import Foundation
import NIOFoundationCompat
import struct NIO.ByteBuffer
import struct NIO.ByteBufferAllocator
/**
* A lightweight wrapper around the NIO ByteBuffer.
*
* Node Buffer API:
* https://nodejs.org/api/buffer.html
*/
public struct Buffer {
public var byteBuffer : ByteBuffer
@inlinable public init(_ byteBuffer: ByteBuffer) {
self.byteBuffer = byteBuffer
}
@inlinable public init(_ buffer: Buffer) {
byteBuffer = buffer.byteBuffer
}
@inlinable
public init(capacity : Int = 1024,
allocator : ByteBufferAllocator = MacroCore.shared.allocator)
{
byteBuffer = allocator.buffer(capacity: capacity)
}
@inlinable public var isEmpty : Bool { return byteBuffer.readableBytes < 1 }
@inlinable public var count : Int { return byteBuffer.readableBytes }
@inlinable public mutating func append(_ buffer: Buffer) {
byteBuffer.writeBytes(buffer.byteBuffer.readableBytesView)
}
@inlinable public mutating func consumeFirst(_ k: Int) -> Buffer {
guard k > 0 else { return MacroCore.shared.emptyBuffer }
if k >= count {
let swap = byteBuffer
byteBuffer = MacroCore.shared.emptyByteBuffer
return Buffer(swap)
}
let readBuffer = byteBuffer.readSlice(length: k)!
return Buffer(readBuffer)
}
}
public extension Buffer {
@inlinable init(_ data: Data) {
self.init(capacity: data.count)
byteBuffer.writeBytes(data)
}
@inlinable init(_ string: String) {
guard let data = string.data(using: .utf8) else {
fatalError("failed to encode string in UTF-8")
}
self.init(data)
}
@inlinable init<S: StringProtocol>(_ string: S) {
guard let data = string.data(using: .utf8) else {
fatalError("failed to encode string in UTF-8")
}
self.init(data)
}
@inlinable var data : Data {
return byteBuffer.getData(at : byteBuffer.readerIndex,
length : byteBuffer.readableBytes) ?? Data()
}
}
public extension Buffer {
@inlinable
static func from(_ string: String, encoding: String.Encoding = .utf8)
throws -> Buffer
{
guard let data = string.data(using: encoding) else {
throw CharsetConversionError.failedToConverData(encoding: encoding)
}
return Buffer(data)
}
@inlinable
static func from<S: StringProtocol>(_ string: S,
encoding: String.Encoding = .utf8)
throws -> Buffer
{
guard let data = string.data(using: encoding) else {
throw CharsetConversionError.failedToConverData(encoding: encoding)
}
return Buffer(data)
}
@inlinable
static func from<S: StringProtocol>(_ string: S, encoding: String) throws
-> Buffer
{
switch encoding {
case "hex":
var buffer = Buffer(capacity: string.utf16.count / 2)
guard buffer.writeHexString(string) else {
throw DataDecodingError.failedToDecodeHexString
}
return buffer
case "base64":
guard let data = Data(base64Encoded: String(string)) else {
throw DataDecodingError.failedToDecodeBase64
}
return Buffer(data)
default:
return try from(string, encoding: .encodingWithName(encoding))
}
}
@inlinable
static func isEncoding(_ encoding: String) -> Bool {
switch encoding {
case "hex", "base64": return true
default: return String.Encoding.isEncoding(encoding)
}
}
@inlinable
func toString(_ encoding: String.Encoding = .utf8) throws -> String {
guard let string = String(data: data, encoding: encoding) else {
throw CharsetConversionError.failedToConvertString(encoding: encoding)
}
return string
}
@inlinable
func toString(_ encoding: String) throws -> String {
switch encoding {
case "hex" : return hexEncodedString()
case "base64" : return data.base64EncodedString()
default: return try toString(.encodingWithName(encoding))
}
}
}
public enum DataDecodingError: Swift.Error {
case failedToDecodeHexString
case failedToDecodeBase64
}
public enum DataEncodingError: Swift.Error {
case failedToReadData
}
@usableFromInline
internal let hexAlphabet = "0123456789abcdef".unicodeScalars.map { $0 }
extension Buffer {
public func hexEncodedString() -> String {
// https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex
return String(byteBuffer.readableBytesView.reduce(into: "".unicodeScalars, {
( result, value ) in
result.append(hexAlphabet[Int(value / 16)])
result.append(hexAlphabet[Int(value % 16)])
}))
}
@inlinable
mutating func writeHexString<S: StringProtocol>(_ hexString: S) -> Bool {
// https://stackoverflow.com/questions/41485494/convert-hex-encoded-string
func decodeNibble(u: UInt16) -> UInt8? {
switch(u) {
case 0x30 ... 0x39: return UInt8(u - 0x30)
case 0x41 ... 0x46: return UInt8(u - 0x41 + 10)
case 0x61 ... 0x66: return UInt8(u - 0x61 + 10)
default: return nil
}
}
var even = true
var byte : UInt8 = 0
for c in hexString.utf16 {
guard let val = decodeNibble(u: c) else { return false }
if even {
byte = val << 4
}
else {
byte += val
byteBuffer.writeInteger(byte)
}
even = !even
}
return even
}
}