1/* 2 * Copyright (C) 2014 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 */ 16package okio; 17 18import java.io.Closeable; 19import java.io.IOException; 20 21/** 22 * Receives a stream of bytes. Use this interface to write data wherever it's 23 * needed: to the network, storage, or a buffer in memory. Sinks may be layered 24 * to transform received data, such as to compress, encrypt, throttle, or add 25 * protocol framing. 26 * 27 * <p>Most application code shouldn't operate on a sink directly, but rather 28 * {@link BufferedSink} which is both more efficient and more convenient. Use 29 * {@link Okio#buffer(Sink)} to wrap any sink with a buffer. 30 * 31 * <p>Sinks are easy to test: just use an {@link OkBuffer} in your tests, and 32 * read from it to confirm it received the data that was expected. 33 * 34 * <h3>Comparison with OutputStream</h3> 35 * This interface is functionally equivalent to {@link java.io.OutputStream}. 36 * 37 * <p>{@code OutputStream} requires multiple layers when emitted data is 38 * heterogeneous: a {@code DataOutputStream} for primitive values, a {@code 39 * BufferedOutputStream} for buffering, and {@code OutputStreamWriter} for 40 * charset encoding. This class uses {@code BufferedSink} for all of the above. 41 * 42 * <p>Sink is also easier to layer: there is no {@link 43 * java.io.OutputStream#write(int) single-byte write} method that is awkward to 44 * implement efficiently. 45 * 46 * <h3>Interop with OutputStream</h3> 47 * Use {@link Okio#sink} to adapt an {@code OutputStream} to a sink. Use {@link 48 * BufferedSink#outputStream} to adapt a sink to an {@code OutputStream}. 49 */ 50public interface Sink extends Closeable { 51 /** Removes {@code byteCount} bytes from {@code source} and appends them to this. */ 52 void write(OkBuffer source, long byteCount) throws IOException; 53 54 /** Pushes all buffered bytes to their final destination. */ 55 void flush() throws IOException; 56 57 /** 58 * Sets the deadline for all operations on this sink. 59 * @return this sink. 60 */ 61 Sink deadline(Deadline deadline); 62 63 /** 64 * Pushes all buffered bytes to their final destination and releases the 65 * resources held by this sink. It is an error to write a closed sink. It is 66 * safe to close a sink more than once. 67 */ 68 @Override void close() throws IOException; 69} 70