forked from apple/swift-nio-extras
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LineBasedFrameDecoder.swift
98 lines (90 loc) · 3.85 KB
/
LineBasedFrameDecoder.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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
/// A decoder that splits incoming `ByteBuffer`s around line end
/// character(s) (`'\n'` or `'\r\n'`).
///
/// Let's, for example, consider the following received buffer:
///
/// +----+-------+------------+
/// | AB | C\nDE | F\r\nGHI\n |
/// +----+-------+------------+
///
/// A instance of ``LineBasedFrameDecoder`` will split this buffer
/// as follows:
///
/// +-----+-----+-----+
/// | ABC | DEF | GHI |
/// +-----+-----+-----+
///
public class LineBasedFrameDecoder: ByteToMessageDecoder {
/// `ByteBuffer` is the expected type passed in.
public typealias InboundIn = ByteBuffer
/// `ByteBuffer`s will be passed to the next stage.
public typealias InboundOut = ByteBuffer
@available(*, deprecated, message: "No longer used")
public var cumulationBuffer: ByteBuffer?
// keep track of the last scan offset from the buffer's reader index (if we didn't find the delimiter)
private var lastScanOffset = 0
public init() { }
/// Decode data in the supplied buffer.
/// - Parameters:
/// - context: Calling cotext
/// - buffer: Buffer containing data to decode.
/// - Returns: State describing if more data is required.
public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState {
if let frame = try self.findNextFrame(buffer: &buffer) {
context.fireChannelRead(wrapInboundOut(frame))
return .continue
} else {
return .needMoreData
}
}
/// Decode all remaining data.
/// If it is not possible to consume all the data then ``NIOExtrasErrors/LeftOverBytesError`` is reported via `context.fireErrorCaught`
/// - Parameters:
/// - context: Calling context.
/// - buffer: Buffer containing the data to decode.
/// - seenEOF: Has end of file been seen.
/// - Returns: Always .needMoreData as all data will be consumed.
public func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState {
while try self.decode(context: context, buffer: &buffer) == .continue {}
if buffer.readableBytes > 0 {
context.fireErrorCaught(NIOExtrasErrors.LeftOverBytesError(leftOverBytes: buffer))
}
return .needMoreData
}
private func findNextFrame(buffer: inout ByteBuffer) throws -> ByteBuffer? {
let view = buffer.readableBytesView.dropFirst(self.lastScanOffset)
// look for the delimiter
if let delimiterIndex = view.firstIndex(of: 0x0A) { // '\n'
let length = delimiterIndex - buffer.readerIndex
let dropCarriageReturn = delimiterIndex > buffer.readableBytesView.startIndex &&
buffer.readableBytesView[delimiterIndex - 1] == 0x0D // '\r'
let buff = buffer.readSlice(length: dropCarriageReturn ? length - 1 : length)
// drop the delimiter (and trailing carriage return if appicable)
buffer.moveReaderIndex(forwardBy: dropCarriageReturn ? 2 : 1)
// reset the last scan start index since we found a line
self.lastScanOffset = 0
return buff
}
// next scan we start where we stopped
self.lastScanOffset = buffer.readableBytes
return nil
}
}
#if swift(>=5.6)
@available(*, unavailable)
extension LineBasedFrameDecoder: Sendable {}
#endif