Skip to content

Commit 30733de

Browse files
committed
Merge branch 'fix-data-conversion' into 'master'
Fix `Data` Conversion to `RESPValue` See merge request Mordil/swift-redis-nio-client!50
2 parents 788f69d + 34647e1 commit 30733de

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

Sources/RedisNIO/RESP/RESPValue.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,15 @@ extension String {
2424
}
2525
}
2626

27+
extension Data {
28+
@inline(__always)
29+
var byteBuffer: ByteBuffer {
30+
var buffer = RESPValue.allocator.buffer(capacity: self.count)
31+
buffer.writeBytes(self)
32+
return buffer
33+
}
34+
}
35+
2736
/// A representation of a Redis Serialization Protocol (RESP) primitive value.
2837
///
2938
/// See: [https://redis.io/topics/protocol](https://redis.io/topics/protocol)

Sources/RedisNIO/RESP/RESPValueConvertible.swift

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,3 +152,16 @@ extension Optional: RESPValueConvertible where Wrapped: RESPValueConvertible {
152152
}
153153
}
154154
}
155+
156+
import struct Foundation.Data
157+
158+
extension Data: RESPValueConvertible {
159+
public init?(_ value: RESPValue) {
160+
guard let data = value.data else { return nil }
161+
self = data
162+
}
163+
164+
public func convertedToRESPValue() -> RESPValue {
165+
return .bulkString(self.byteBuffer)
166+
}
167+
}

Tests/RedisNIOTests/RESP/RESPTranslatorWritingTests.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,12 @@ final class RESPTranslatorWritingTests: XCTestCase {
6464
XCTAssertTrue(testPass(input: .null, expected: "$-1\r\n"))
6565
}
6666

67+
func testDataEncoding() throws {
68+
let name = #function
69+
let data = Data(name.bytes).convertedToRESPValue()
70+
XCTAssertTrue(testPass(input: data, expected: "$\(name.count)\r\n\(name)\r\n"))
71+
}
72+
6773
private func testPass(input: RESPValue, expected: [UInt8]) -> Bool {
6874
let allocator = ByteBufferAllocator()
6975

@@ -97,5 +103,6 @@ extension RESPTranslatorWritingTests {
97103
("testArrays", testArrays),
98104
("testError", testError),
99105
("testNull", testNull),
106+
("testDataEncoding", testDataEncoding),
100107
]
101108
}

0 commit comments

Comments
 (0)