Skip to content

Commit b8c1948

Browse files
committed
Refactor RESPTranslator to mutate the passed ByteBuffer directly.
Motivation: During proposal review, it was pointed out that the code with a position index was redundant and error prone over relying on `ByteBuffer`'s `readerIndex`. Modifications: Refactored `RESPTranslator` to rely on `ByteBuffer.readerIndex` for position of current parsing cursor, and eliminated `ParsingResult` enum to instead return `RESPValue?`. The implementation for writing out `RESPValue` has been expanded to `RESPValueConvertible` and moved to an extension of `ByteBuffer`. Result: Parsing `RESPValue` into and out of `ByteBuffer` should be less error-prone and more straight forward. This contributes to issues #47 and #55
1 parent 44c2916 commit b8c1948

File tree

8 files changed

+716
-700
lines changed

8 files changed

+716
-700
lines changed

Sources/RedisNIO/ChannelHandlers/RedisByteDecoder.swift

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,18 +21,19 @@ import NIO
2121
public final class RedisByteDecoder: ByteToMessageDecoder {
2222
/// `ByteToMessageDecoder.InboundOut`
2323
public typealias InboundOut = RESPValue
24+
25+
private let parser: RESPTranslator
26+
27+
public init() {
28+
self.parser = RESPTranslator()
29+
}
2430

2531
/// See `ByteToMessageDecoder.decode(context:buffer:)`
2632
public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState {
27-
var position = 0
28-
29-
switch try RESPTranslator.parseBytes(&buffer, fromIndex: &position) {
30-
case .incomplete: return .needMoreData
31-
case let .parsed(value):
32-
context.fireChannelRead(wrapInboundOut(value))
33-
buffer.moveReaderIndex(forwardBy: position)
34-
return .continue
35-
}
33+
guard let value = try self.parser.parseBytes(from: &buffer) else { return .needMoreData }
34+
35+
context.fireChannelRead(wrapInboundOut(value))
36+
return .continue
3637
}
3738

3839
/// See `ByteToMessageDecoder.decodeLast(context:buffer:seenEOF)`

Sources/RedisNIO/ChannelHandlers/RedisMessageEncoder.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ public final class RedisMessageEncoder: MessageToByteEncoder {
3333
///
3434
/// See [https://redis.io/topics/protocol](https://redis.io/topics/protocol) and `RESPEncoder.encode(data:out:)`
3535
public func encode(data: RESPValue, out: inout ByteBuffer) throws {
36-
RESPTranslator.writeValue(data, into: &out)
36+
out.writeRESPValue(data)
3737

3838
logger.debug("Encoded \(data) to \(getPrintableString(for: &out))")
3939
}

0 commit comments

Comments
 (0)