Skip to content

Commit

Permalink
Add generic message framing wrapper to DataChannel (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
koliyo authored Oct 20, 2023
1 parent f701f4e commit a61930e
Showing 1 changed file with 38 additions and 0 deletions.
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)
}
}

0 comments on commit a61930e

Please sign in to comment.