Sergey Mashkov | 25b2bc5 | 2017-08-24 21:24:47 +0300 | [diff] [blame] | 1 | package kotlinx.coroutines.experimental.io |
| 2 | |
Roman Elizarov | 2adf8bc | 2018-01-24 20:09:57 +0300 | [diff] [blame] | 3 | import kotlinx.coroutines.experimental.* |
| 4 | import kotlin.coroutines.experimental.* |
Sergey Mashkov | 25b2bc5 | 2017-08-24 21:24:47 +0300 | [diff] [blame] | 5 | |
| 6 | /** |
| 7 | * A coroutine job that is writing to a byte channel |
| 8 | */ |
| 9 | interface WriterJob : Job { |
| 10 | /** |
| 11 | * A reference to the channel that this coroutine is writing to |
| 12 | */ |
| 13 | val channel: ByteReadChannel |
| 14 | } |
| 15 | |
| 16 | interface WriterScope : CoroutineScope { |
| 17 | val channel: ByteWriteChannel |
| 18 | } |
| 19 | |
| 20 | fun writer(coroutineContext: CoroutineContext, |
| 21 | channel: ByteChannel, |
Sergey Mashkov | 15639fa | 2017-12-05 15:49:56 +0300 | [diff] [blame] | 22 | parent: Job? = null, |
Sergey Mashkov | ea3a418 | 2017-09-11 13:06:54 +0300 | [diff] [blame] | 23 | block: suspend WriterScope.() -> Unit): WriterJob { |
Sergey Mashkov | 15639fa | 2017-12-05 15:49:56 +0300 | [diff] [blame] | 24 | val newContext = newCoroutineContext(coroutineContext, parent) |
Roman Elizarov | e8f694e | 2017-11-28 10:12:00 +0300 | [diff] [blame] | 25 | val coroutine = WriterCoroutine(newContext, channel) |
Roman Elizarov | 2adf8bc | 2018-01-24 20:09:57 +0300 | [diff] [blame] | 26 | coroutine.start(CoroutineStart.DEFAULT, coroutine, block) |
Sergey Mashkov | 25b2bc5 | 2017-08-24 21:24:47 +0300 | [diff] [blame] | 27 | return coroutine |
| 28 | } |
| 29 | |
| 30 | fun writer(coroutineContext: CoroutineContext, |
| 31 | autoFlush: Boolean = false, |
Sergey Mashkov | 15639fa | 2017-12-05 15:49:56 +0300 | [diff] [blame] | 32 | parent: Job? = null, |
Sergey Mashkov | a26b790 | 2017-12-05 16:06:03 +0300 | [diff] [blame] | 33 | 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 Mashkov | 25b2bc5 | 2017-08-24 21:24:47 +0300 | [diff] [blame] | 39 | |
| 40 | private class WriterCoroutine(ctx: CoroutineContext, channel: ByteChannel) |
| 41 | : ByteChannelCoroutine(ctx, channel), WriterScope, WriterJob |
| 42 | |