1 /* 2 * Copyright 2017 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * https://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package trebuchet.io 18 19 import java.util.concurrent.ArrayBlockingQueue 20 21 interface Producer<in T> { addnull22 fun add(data: T) 23 fun close() 24 } 25 26 interface Consumer<out T> { 27 fun next(): T? 28 } 29 30 class Pipe<T>(capacity: Int = 4) : Producer<T>, Consumer<T> { 31 private class Packet<out T>(val data: T?) 32 33 private val queue = ArrayBlockingQueue<Packet<T>>(capacity) 34 private var producerClosed = false 35 private var consumerClosed = false 36 addnull37 override fun add(data: T) { 38 if (data == null) throw IllegalStateException("Unable to send null") 39 40 if (producerClosed) throw IllegalStateException("Already closed") 41 queue.put(Packet(data)) 42 } 43 closenull44 override fun close() { 45 if (!producerClosed) { 46 producerClosed = true 47 queue.put(Packet(null)) 48 } 49 } 50 nextnull51 override fun next(): T? { 52 if (consumerClosed) return null 53 val packet = queue.take() 54 if (packet.data == null) { 55 consumerClosed = true 56 } 57 return packet.data 58 } 59 }