|
| 1 | +/* |
| 2 | + * Copyright (C) 2024 Square, 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 | + * http://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 | +package okio.samples |
| 17 | + |
| 18 | +import okio.Buffer |
| 19 | +import okio.FileSystem |
| 20 | +import okio.Path.Companion.toPath |
| 21 | +import okio.Sink |
| 22 | +import okio.Timeout |
| 23 | +import okio.buffer |
| 24 | +import okio.sink |
| 25 | + |
| 26 | +/** |
| 27 | + * A sink that writes all input to both [sinkA] and [sinkB]. |
| 28 | + */ |
| 29 | +class TeeSink( |
| 30 | + private val sinkA: Sink, |
| 31 | + private val sinkB: Sink, |
| 32 | +) : Sink { |
| 33 | + private val timeout = Timeout() |
| 34 | + |
| 35 | + override fun write(source: Buffer, byteCount: Long) { |
| 36 | + // Writing to sink mutates source. Work around that. |
| 37 | + sinkA.timeout().intersectWith(timeout) { |
| 38 | + val buffer = Buffer() |
| 39 | + source.copyTo(buffer, byteCount = byteCount) |
| 40 | + sinkA.write(buffer, byteCount) |
| 41 | + } |
| 42 | + |
| 43 | + sinkB.timeout().intersectWith(timeout) { |
| 44 | + sinkB.write(source, byteCount) |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + override fun flush() { |
| 49 | + sinkA.flush() |
| 50 | + sinkB.flush() |
| 51 | + } |
| 52 | + |
| 53 | + override fun close() { |
| 54 | + try { |
| 55 | + sinkA.close() |
| 56 | + } catch (tA: Throwable) { |
| 57 | + try { |
| 58 | + sinkB.close() |
| 59 | + } catch (tB: Throwable) { |
| 60 | + tA.addSuppressed(tB) |
| 61 | + } |
| 62 | + throw tA |
| 63 | + } |
| 64 | + |
| 65 | + sinkB.close() |
| 66 | + } |
| 67 | + |
| 68 | + override fun timeout() = sinkA.timeout() |
| 69 | +} |
| 70 | + |
| 71 | +fun main() { |
| 72 | + val a = System.out.sink() |
| 73 | + val b = FileSystem.SYSTEM.sink("tee.txt".toPath()) |
| 74 | + |
| 75 | + TeeSink(a, b).buffer().use { teeSink -> |
| 76 | + teeSink.writeUtf8("hello\n") |
| 77 | + teeSink.flush() |
| 78 | + teeSink.writeUtf8("world!") |
| 79 | + } |
| 80 | +} |
0 commit comments