-
-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add generic message framing wrapper to DataChannel (#12)
- Loading branch information
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
38 changes: 38 additions & 0 deletions
38
Sources/LanguageServerProtocol/Additions/DataChannel+MessageFraming.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) | ||
} | ||
} |