From a61930edd078182165278132ec8c89b64db2cb08 Mon Sep 17 00:00:00 2001 From: Nils Hjelte Date: Fri, 20 Oct 2023 15:30:05 +0200 Subject: [PATCH] Add generic message framing wrapper to DataChannel (#12) --- .../DataChannel+MessageFraming.swift | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Sources/LanguageServerProtocol/Additions/DataChannel+MessageFraming.swift diff --git a/Sources/LanguageServerProtocol/Additions/DataChannel+MessageFraming.swift b/Sources/LanguageServerProtocol/Additions/DataChannel+MessageFraming.swift new file mode 100644 index 0000000..6debe6c --- /dev/null +++ b/Sources/LanguageServerProtocol/Additions/DataChannel+MessageFraming.swift @@ -0,0 +1,38 @@ +import Foundation +import JSONRPC + +extension DataChannel { + /// Wrap http message framing on an existing data channel + public func withMessageFraming( + ) -> DataChannel { + + let writeHandler: DataChannel.WriteHandler = { data in + let data = MessageFraming.frame(data) + + try await self.writeHandler(data) + } + +#if compiler(>=5.9) + let (stream, continuation) = DataSequence.makeStream() +#else + var escapedContinuation: DataSequence.Continuation? + + let stream = DataSequence { escapedContinuation = $0 } + let continuation = escapedContinuation! +#endif + + Task { + let byteStream = AsyncByteSequence(base: dataSequence) + let framedData = AsyncMessageFramingSequence(base: byteStream) + + for try await data in framedData { + continuation.yield(data) + } + + continuation.finish() + } + + return DataChannel(writeHandler: writeHandler, + dataSequence: stream) + } +}