@@ -10,9 +10,13 @@ public import Init.System.Promise
1010public import Init.Data.Queue
1111public import Std.Sync.Mutex
1212public import Std.Internal.Async.Select
13+ public import Std.Internal.Async.IO
1314
1415public section
1516
17+ open Std.Internal.Async.IO
18+ open Std.Internal.IO.Async
19+
1620/-!
1721This module contains the implementation of `Std.Channel`. `Std.Channel` is a multi-producer
1822multi-consumer FIFO channel that offers both bounded and unbounded buffering as well as synchronous
@@ -24,7 +28,6 @@ for cleaner code.
2428-/
2529
2630namespace Std
27-
2831namespace CloseableChannel
2932
3033/--
@@ -753,6 +756,17 @@ partial def forAsync (f : α → BaseIO Unit) (ch : CloseableChannel α)
753756 | none => return .pure ()
754757 | some v => do f v; ch.forAsync f prio
755758
759+ instance [Inhabited α] : AsyncStream (CloseableChannel α) (Option α) where
760+ next channel := channel.recvSelector
761+
762+ instance [Inhabited α] : AsyncRead (CloseableChannel α) (Option α) where
763+ read receiver := Internal.IO.Async.Async.ofIOTask receiver.recv
764+
765+ instance [Inhabited α] : AsyncWrite (CloseableChannel α) α where
766+ write receiver x := do
767+ let task ← receiver.send x
768+ Async.ofAsyncTask <| task.map (Except.mapError (IO.userError ∘ toString))
769+
756770/--
757771This function is a no-op and just a convenient way to expose the synchronous API of the channel.
758772-/
@@ -804,7 +818,6 @@ instance [MonadLiftT BaseIO m] : ForIn m (Sync α) α where
804818 forIn ch b f := private ch.forIn f b
805819
806820end Sync
807-
808821end CloseableChannel
809822
810823/--
@@ -893,6 +906,17 @@ partial def forAsync [Inhabited α] (f : α → BaseIO Unit) (ch : Channel α)
893906 (prio : Task.Priority := .default) : BaseIO (Task Unit) := do
894907 BaseIO.bindTask (prio := prio) (← ch.recv) fun v => do f v; ch.forAsync f prio
895908
909+ instance [Inhabited α] : AsyncStream (Channel α) α where
910+ next channel := channel.recvSelector
911+
912+ instance [Inhabited α] : AsyncRead (Channel α) α where
913+ read receiver := Internal.IO.Async.Async.ofIOTask receiver.recv
914+
915+ instance [Inhabited α] : AsyncWrite (Channel α) α where
916+ write receiver x := do
917+ let task ← receiver.send x
918+ Async.ofTask task
919+
896920@[inherit_doc CloseableChannel.sync, inline]
897921def sync (ch : Channel α) : Channel.Sync α := ch
898922
0 commit comments