blob: f4a64adb0a0c0a746feda844af93fba2774d6831 [file] [log] [blame]
Sergey Mashkov25b2bc52017-08-24 21:24:47 +03001package kotlinx.coroutines.experimental.io
2
Roman Elizarov2adf8bc2018-01-24 20:09:57 +03003import kotlinx.coroutines.experimental.*
4import kotlin.coroutines.experimental.*
Sergey Mashkov25b2bc52017-08-24 21:24:47 +03005
6/**
7 * A coroutine job that is writing to a byte channel
8 */
9interface WriterJob : Job {
10 /**
11 * A reference to the channel that this coroutine is writing to
12 */
13 val channel: ByteReadChannel
14}
15
16interface WriterScope : CoroutineScope {
17 val channel: ByteWriteChannel
18}
19
20fun writer(coroutineContext: CoroutineContext,
21 channel: ByteChannel,
Sergey Mashkov15639fa2017-12-05 15:49:56 +030022 parent: Job? = null,
Sergey Mashkovea3a4182017-09-11 13:06:54 +030023 block: suspend WriterScope.() -> Unit): WriterJob {
Sergey Mashkov15639fa2017-12-05 15:49:56 +030024 val newContext = newCoroutineContext(coroutineContext, parent)
Roman Elizarove8f694e2017-11-28 10:12:00 +030025 val coroutine = WriterCoroutine(newContext, channel)
Roman Elizarov2adf8bc2018-01-24 20:09:57 +030026 coroutine.start(CoroutineStart.DEFAULT, coroutine, block)
Sergey Mashkov25b2bc52017-08-24 21:24:47 +030027 return coroutine
28}
29
30fun writer(coroutineContext: CoroutineContext,
31 autoFlush: Boolean = false,
Sergey Mashkov15639fa2017-12-05 15:49:56 +030032 parent: Job? = null,
Sergey Mashkova26b7902017-12-05 16:06:03 +030033 block: suspend WriterScope.() -> Unit): WriterJob {
34 val channel = ByteChannel(autoFlush) as ByteBufferChannel
35 val job = writer(coroutineContext, channel, parent, block)
36 channel.attachJob(job)
37 return job
38}
Sergey Mashkov25b2bc52017-08-24 21:24:47 +030039
40private class WriterCoroutine(ctx: CoroutineContext, channel: ByteChannel)
41 : ByteChannelCoroutine(ctx, channel), WriterScope, WriterJob
42