Sergey Mashkov | 4cd0014 | 2017-09-05 19:25:32 +0300 | [diff] [blame] | 1 | package kotlinx.coroutines.experimental.io |
| 2 | |
| 3 | interface LookAheadSession { |
| 4 | /** |
| 5 | * Marks [n] bytes as consumed so the corresponding range becomes available for writing |
| 6 | */ |
| 7 | fun consumed(n: Int) |
| 8 | |
| 9 | /** |
| 10 | * Request byte buffer range skipping [skip] bytes and [atLeast] bytes length |
| 11 | * @return byte buffer for the requested range or null if it is impossible to provide such a buffer |
| 12 | * |
| 13 | * There are the following reasons for this function to return `null`: |
| 14 | * - not enough bytes available yet (should be at least `skip + atLeast` bytes available) |
| 15 | * - due to buffer fragmentation is is impossible to represent the requested range as a single byte buffer |
| 16 | * - end of stream encountered and all bytes were consumed |
| 17 | * - channel has been closed with an exception so buffer has been recycled |
| 18 | */ |
| 19 | fun request(skip: Int, atLeast: Int): ByteBuffer? |
| 20 | } |
| 21 | |
| 22 | interface LookAheadSuspendSession : LookAheadSession { |
| 23 | /** |
| 24 | * Suspend until [n] bytes become available or end of stream encountered (possibly due to exceptional close) |
| 25 | */ |
Sergey Mashkov | 09b621e | 2017-12-22 20:42:18 +0300 | [diff] [blame] | 26 | suspend fun awaitAtLeast(n: Int): Boolean |
Sergey Mashkov | 4cd0014 | 2017-09-05 19:25:32 +0300 | [diff] [blame] | 27 | } |
| 28 | |
| 29 | inline fun LookAheadSession.consumeEachRemaining(visitor: (ByteBuffer) -> Boolean) { |
| 30 | do { |
| 31 | val cont = request(0, 1)?.let { |
| 32 | val s = it.remaining() |
| 33 | val rc = visitor(it) |
| 34 | consumed(s) |
| 35 | rc |
| 36 | } ?: false |
| 37 | |
| 38 | if (!cont) break |
| 39 | } while (true) |
| 40 | } |
| 41 | |