mirror of
https://github.com/apple/swift-nio
synced 2026-11-25 04:47:49 +00:00
Issue-2748 - Add ByteBuffer Hex init & write (#2837)
Add ability for below two functions
`ByteBuffer(hexEncodedBytes: "68 65 6c 6c 6f 20 77 6f 72 6c 64 0a")`
` buffer.writeHexEncodedBytes("68656c6c6f20776f726c640a")`
### Motivation:
https://github.com/apple/swift-nio/issues/2748
---------
Co-authored-by: Ali Ali <ali.ali@qantas.com.au>
Co-authored-by: Cory Benfield <lukasa@apple.com>
This commit is contained in:
4 files changed
+168
-1
No files matched your search
@@ -91,6 +91,30 @@ extension ByteBuffer {
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: Hex encoded string APIs
|
||||
/// Write ASCII hexadecimal `string` into this `ByteBuffer` as raw bytes, decoding the hexadecimal & moving the writer index forward appropriately.
|
||||
/// This method will throw if the string input is not of the "plain" hex encoded format.
|
||||
/// - parameters:
|
||||
/// - plainHexEncodedBytes: The hex encoded string to write. Plain hex dump format is hex bytes optionally separated by spaces, i.e. `48 65 6c 6c 6f` or `48656c6c6f` for `Hello`.
|
||||
/// This format is compatible with `xxd` CLI utility.
|
||||
/// - returns: The number of bytes written.
|
||||
@discardableResult
|
||||
@inlinable
|
||||
public mutating func writePlainHexEncodedBytes(_ plainHexEncodedBytes: String) throws -> Int {
|
||||
var slice = plainHexEncodedBytes.utf8[...]
|
||||
let initialWriterIndex = self.writerIndex
|
||||
|
||||
do {
|
||||
while let nextByte = try slice.popNextHexByte() {
|
||||
self.writeInteger(nextByte)
|
||||
}
|
||||
return self.writerIndex - initialWriterIndex
|
||||
} catch {
|
||||
self.moveWriterIndex(to: initialWriterIndex)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: String APIs
|
||||
/// Write `string` into this `ByteBuffer` using UTF-8 encoding, moving the writer index forward appropriately.
|
||||
///
|
||||
@@ -763,6 +787,18 @@ extension ByteBufferAllocator {
|
||||
return buffer
|
||||
}
|
||||
|
||||
/// Create a fresh `ByteBuffer` containing the `bytes` decoded from the ASCII `plainHexEncodedBytes` string .
|
||||
///
|
||||
/// This will allocate a new `ByteBuffer` with enough space to fit `bytes` and potentially some extra space.
|
||||
///
|
||||
/// - returns: The `ByteBuffer` containing the written bytes.
|
||||
@inlinable
|
||||
public func buffer(plainHexEncodedBytes string: String) throws -> ByteBuffer {
|
||||
var buffer = self.buffer(capacity: string.utf8.count / 2)
|
||||
try buffer.writePlainHexEncodedBytes(string)
|
||||
return buffer
|
||||
}
|
||||
|
||||
/// Create a fresh `ByteBuffer` containing the bytes of the byte representation in the given `endianness` of
|
||||
/// `integer`.
|
||||
///
|
||||
|
||||
@@ -42,7 +42,7 @@ extension String {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - radix: radix base to use for conversion.
|
||||
/// - padding: the desired lenght of the resulting string.
|
||||
/// - padding: the desired length of the resulting string.
|
||||
@inlinable
|
||||
internal init<Value>(_ value: Value, radix: Int, padding: Int) where Value: BinaryInteger {
|
||||
let formatted = String(value, radix: radix)
|
||||
|
||||
@@ -14,6 +14,20 @@
|
||||
|
||||
extension ByteBuffer {
|
||||
|
||||
/// Create a fresh `ByteBuffer` containing the `bytes` decoded from the string representation of `plainHexEncodedBytes`.
|
||||
///
|
||||
/// This will allocate a new `ByteBuffer` with enough space to fit the hex decoded `bytes` and potentially some extra space
|
||||
/// using the default allocator.
|
||||
///
|
||||
/// - info: If you have access to a `Channel`, `ChannelHandlerContext`, or `ByteBufferAllocator` we
|
||||
/// recommend using `channel.allocator.buffer(integer:)`. Or if you want to write multiple items into the
|
||||
/// buffer use `channel.allocator.buffer(capacity: ...)` to allocate a `ByteBuffer` of the right
|
||||
/// size followed by a `writeHexEncodedBytes` instead of using this method. This allows SwiftNIO to do
|
||||
/// accounting and optimisations of resources acquired for operations on a given `Channel` in the future.
|
||||
public init(plainHexEncodedBytes string: String) throws {
|
||||
self = try ByteBufferAllocator().buffer(plainHexEncodedBytes: string)
|
||||
}
|
||||
|
||||
/// Describes a ByteBuffer hexDump format.
|
||||
/// Can be either xxd output compatible, or hexdump compatible.
|
||||
public struct HexDumpFormat: Hashable, Sendable {
|
||||
@@ -340,4 +354,61 @@ extension ByteBuffer {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An error that is thrown when an invalid hex encoded string was attempted to be written to a ByteBuffer.
|
||||
public struct HexDecodingError: Error, Equatable {
|
||||
private let kind: HexDecodingErrorKind
|
||||
|
||||
private enum HexDecodingErrorKind {
|
||||
/// The hex encoded string was not of the expected even length.
|
||||
case invalidHexLength
|
||||
/// An invalid hex character was found in the hex encoded string.
|
||||
case invalidCharacter
|
||||
}
|
||||
|
||||
public static let invalidHexLength = HexDecodingError(kind: .invalidHexLength)
|
||||
public static let invalidCharacter = HexDecodingError(kind: .invalidCharacter)
|
||||
}
|
||||
}
|
||||
|
||||
extension UInt8 {
|
||||
fileprivate var isASCIIWhitespace: Bool {
|
||||
[UInt8(ascii: "\n"), UInt8(ascii: "\t"), UInt8(ascii: "\r"), UInt8(ascii: " ")].contains(
|
||||
self
|
||||
)
|
||||
}
|
||||
|
||||
fileprivate var asciiHexNibble: UInt8 {
|
||||
get throws {
|
||||
switch self {
|
||||
case UInt8(ascii: "0")...UInt8(ascii: "9"):
|
||||
return self - UInt8(ascii: "0")
|
||||
case UInt8(ascii: "a")...UInt8(ascii: "f"):
|
||||
return self - UInt8(ascii: "a") + 10
|
||||
case UInt8(ascii: "A")...UInt8(ascii: "F"):
|
||||
return self - UInt8(ascii: "A") + 10
|
||||
default:
|
||||
throw ByteBuffer.HexDecodingError.invalidCharacter
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Substring.UTF8View {
|
||||
@usableFromInline
|
||||
mutating func popNextHexByte() throws -> UInt8? {
|
||||
while let nextByte = self.first, nextByte.isASCIIWhitespace {
|
||||
self = self.dropFirst()
|
||||
}
|
||||
|
||||
guard let firstHex = try self.popFirst()?.asciiHexNibble else {
|
||||
return nil // No next byte to pop
|
||||
}
|
||||
|
||||
guard let secondHex = try self.popFirst()?.asciiHexNibble else {
|
||||
throw ByteBuffer.HexDecodingError.invalidHexLength
|
||||
}
|
||||
|
||||
return (firstHex << 4) | secondHex
|
||||
}
|
||||
}
|
||||
@@ -1069,6 +1069,17 @@ class ByteBufferTest: XCTestCase {
|
||||
XCTAssertNil(self.buf.getString(at: 0, length: capacity + 1))
|
||||
}
|
||||
|
||||
func testWriteEmptyByteArray() throws {
|
||||
var buffer = ByteBufferAllocator().buffer(capacity: 32)
|
||||
buffer.moveWriterIndex(to: 16)
|
||||
buffer.moveReaderIndex(to: 16)
|
||||
XCTAssertEqual(buffer.setBytes([], at: 16), 0)
|
||||
XCTAssertEqual(buffer.readableBytes, 0)
|
||||
XCTAssertEqual(buffer.writableBytes, 16)
|
||||
XCTAssertEqual(buffer.writerIndex, 16)
|
||||
XCTAssertEqual(buffer.readerIndex, 16)
|
||||
}
|
||||
|
||||
func testSetGetBytesAllFine() throws {
|
||||
self.buf.moveReaderIndex(to: 0)
|
||||
self.buf.setBytes([1, 2, 3, 4], at: 0)
|
||||
@@ -1934,6 +1945,55 @@ class ByteBufferTest: XCTestCase {
|
||||
XCTAssertEqual(expected, actual)
|
||||
}
|
||||
|
||||
func testWriteHexEncodedBytes() throws {
|
||||
var buffer = try ByteBuffer(plainHexEncodedBytes: "68 65 6c 6c 6f 20 77 6f 72 6c 64 0a")
|
||||
XCTAssertEqual(try buffer.writePlainHexEncodedBytes("68656c6c6f20776f726c64"), 11)
|
||||
XCTAssertEqual(try buffer.writePlainHexEncodedBytes(" 0a "), 1)
|
||||
XCTAssertEqual(try buffer.writePlainHexEncodedBytes(""), 0)
|
||||
XCTAssertEqual(try buffer.writePlainHexEncodedBytes(" "), 0)
|
||||
XCTAssertEqual(ByteBuffer(string: "hello world\nhello world\n"), buffer)
|
||||
}
|
||||
|
||||
func testWriteHexEncodedBytesFails() throws {
|
||||
var buffer = ByteBuffer()
|
||||
XCTAssertThrowsError(try buffer.writePlainHexEncodedBytes(" 1 ")) { error in
|
||||
XCTAssertTrue((error as? ByteBuffer.HexDecodingError) == ByteBuffer.HexDecodingError.invalidCharacter)
|
||||
}
|
||||
XCTAssertThrowsError(try buffer.writePlainHexEncodedBytes(" 1")) { error in
|
||||
XCTAssertTrue((error as? ByteBuffer.HexDecodingError) == ByteBuffer.HexDecodingError.invalidHexLength)
|
||||
}
|
||||
XCTAssertThrowsError(try buffer.writePlainHexEncodedBytes("1 ")) { error in
|
||||
XCTAssertTrue((error as? ByteBuffer.HexDecodingError) == ByteBuffer.HexDecodingError.invalidCharacter)
|
||||
}
|
||||
XCTAssertThrowsError(try buffer.writePlainHexEncodedBytes("🤓")) { error in
|
||||
XCTAssertTrue((error as? ByteBuffer.HexDecodingError) == ByteBuffer.HexDecodingError.invalidCharacter)
|
||||
}
|
||||
XCTAssertThrowsError(try buffer.writePlainHexEncodedBytes("1 1")) { error in
|
||||
XCTAssertTrue((error as? ByteBuffer.HexDecodingError) == ByteBuffer.HexDecodingError.invalidCharacter)
|
||||
}
|
||||
|
||||
// The first byte (68 = "h") is valid, the method throws and the valid byte IS NOT written to the ByteBuffer
|
||||
XCTAssertThrowsError(try buffer.writePlainHexEncodedBytes("68 1")) { error in
|
||||
XCTAssertTrue((error as? ByteBuffer.HexDecodingError) == ByteBuffer.HexDecodingError.invalidHexLength)
|
||||
}
|
||||
XCTAssertTrue(buffer.readableBytesView.isEmpty)
|
||||
}
|
||||
|
||||
func testHexInitialiser() throws {
|
||||
var allBytes = ByteBufferAllocator().buffer(capacity: Int(UInt8.max))
|
||||
for x in UInt8.min...UInt8.max {
|
||||
allBytes.writeInteger(x)
|
||||
}
|
||||
|
||||
let allBytesHex = allBytes.hexDump(format: .plain)
|
||||
let allBytesDecoded = try ByteBuffer(plainHexEncodedBytes: allBytesHex)
|
||||
XCTAssertEqual(allBytes, allBytesDecoded)
|
||||
|
||||
// Edge cases
|
||||
XCTAssertEqual(try ByteBuffer(plainHexEncodedBytes: " "), ByteBufferAllocator.zeroCapacityWithDefaultAllocator)
|
||||
XCTAssertThrowsError(try ByteBuffer(plainHexEncodedBytes: " 1 "))
|
||||
}
|
||||
|
||||
func testHexDumpPlain() {
|
||||
let buf = ByteBuffer(string: "Hello")
|
||||
XCTAssertEqual("48 65 6c 6c 6f", buf.hexDump(format: .plain))
|
||||
|
||||
Reference in new issue
Block a user