Package okio

Class Buffer

  • All Implemented Interfaces:
    Closeable, Flushable, AutoCloseable, Cloneable, BufferedSink, BufferedSource, Sink, Source

    public final class Buffer
    extends Object
    implements BufferedSource, BufferedSink, Cloneable
    A collection of bytes in memory.

    Moving data from one buffer to another is fast. Instead of copying bytes from one place in memory to another, this class just changes ownership of the underlying byte arrays.

    This buffer grows with your data. Just like ArrayList, each buffer starts small. It consumes only the memory it needs to.

    This buffer pools its byte arrays. When you allocate a byte array in Java, the runtime must zero-fill the requested array before returning it to you. Even if you're going to write over that space anyway. This class avoids zero-fill and GC churn by pooling byte arrays.

    • Constructor Summary

      Constructors 
      Constructor Description
      Buffer()  
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      Buffer buffer()
      Returns this source's internal buffer.
      void clear()
      Discards all bytes in this buffer.
      Buffer clone()
      Returns a deep copy of this buffer.
      void close()
      Closes this source and releases the resources held by this source.
      long completeSegmentByteCount()
      Returns the number of bytes in segments that are not writable.
      Buffer copyTo​(OutputStream out)
      Copy the contents of this to out.
      Buffer copyTo​(OutputStream out, long offset, long byteCount)
      Copy byteCount bytes from this, starting at offset, to out.
      Buffer copyTo​(Buffer out, long offset, long byteCount)
      Copy byteCount bytes from this, starting at offset, to out.
      BufferedSink emit()
      Writes all buffered data to the underlying sink, if one exists.
      Buffer emitCompleteSegments()
      Writes complete segments to the underlying sink, if one exists.
      boolean equals​(Object o)
      Compares this instance with the specified object and indicates if they are equal.
      boolean exhausted()
      Returns true if there are no more bytes in this source.
      void flush()
      Pushes all buffered bytes to their final destination.
      byte getByte​(long pos)
      Returns the byte at pos.
      int hashCode()
      Returns an integer hash code for this object.
      long indexOf​(byte b)
      Returns the index of the first b in the buffer.
      long indexOf​(byte b, long fromIndex)
      Returns the index of b in this at or beyond fromIndex, or -1 if this buffer does not contain b in that range.
      long indexOf​(ByteString bytes)
      Returns the index of the first match for bytes in the buffer.
      long indexOf​(ByteString bytes, long fromIndex)
      Returns the index of the first match for bytes in the buffer at or after fromIndex.
      long indexOfElement​(ByteString targetBytes)
      Returns the index of the first byte in targetBytes in the buffer.
      long indexOfElement​(ByteString targetBytes, long fromIndex)
      Returns the index of the first byte in targetBytes in the buffer at or after fromIndex.
      InputStream inputStream()
      Returns an input stream that reads from this source.
      OutputStream outputStream()
      Returns an output stream that writes to this sink.
      int read​(byte[] sink)
      Removes up to sink.length bytes from this and copies them into sink.
      int read​(byte[] sink, int offset, int byteCount)
      Removes up to byteCount bytes from this and copies them into sink at offset.
      long read​(Buffer sink, long byteCount)
      Removes at least 1, and up to byteCount bytes from this and appends them to sink.
      long readAll​(Sink sink)
      Removes all bytes from this and appends them to sink.
      byte readByte()
      Removes a byte from this source and returns it.
      byte[] readByteArray()
      Removes all bytes from this and returns them as a byte array.
      byte[] readByteArray​(long byteCount)
      Removes byteCount bytes from this and returns them as a byte array.
      ByteString readByteString()
      Removes all bytes bytes from this and returns them as a byte string.
      ByteString readByteString​(long byteCount)
      Removes byteCount bytes from this and returns them as a byte string.
      long readDecimalLong()
      Reads a long from this source in signed decimal form (i.e., as a string in base 10 with optional leading '-').
      Buffer readFrom​(InputStream in)
      Read and exhaust bytes from in to this.
      Buffer readFrom​(InputStream in, long byteCount)
      Read byteCount bytes from in to this.
      void readFully​(byte[] sink)
      Removes exactly sink.length bytes from this and copies them into sink.
      void readFully​(Buffer sink, long byteCount)
      Removes exactly byteCount bytes from this and appends them to sink.
      long readHexadecimalUnsignedLong()
      Reads a long form this source in hexadecimal form (i.e., as a string in base 16).
      int readInt()
      Removes four bytes from this source and returns a big-endian int.
      int readIntLe()
      Removes four bytes from this source and returns a little-endian int.
      long readLong()
      Removes eight bytes from this source and returns a big-endian long.
      long readLongLe()
      Removes eight bytes from this source and returns a little-endian long.
      short readShort()
      Removes two bytes from this source and returns a big-endian short.
      short readShortLe()
      Removes two bytes from this source and returns a little-endian short.
      String readString​(long byteCount, Charset charset)
      Removes byteCount bytes from this, decodes them as charset, and returns the string.
      String readString​(Charset charset)
      Removes all bytes from this, decodes them as charset, and returns the string.
      String readUtf8()
      Removes all bytes from this, decodes them as UTF-8, and returns the string.
      String readUtf8​(long byteCount)
      Removes byteCount bytes from this, decodes them as UTF-8, and returns the string.
      int readUtf8CodePoint()
      Removes and returns a single UTF-8 code point, reading between 1 and 4 bytes as necessary.
      String readUtf8Line()
      Removes and returns characters up to but not including the next line break.
      String readUtf8LineStrict()
      Removes and returns characters up to but not including the next line break.
      boolean request​(long byteCount)
      Returns true when the buffer contains at least byteCount bytes, expanding it as necessary.
      void require​(long byteCount)
      Returns when the buffer contains at least byteCount bytes.
      long size()
      Returns the number of bytes currently in this buffer.
      void skip​(long byteCount)
      Discards byteCount bytes from the head of this buffer.
      ByteString snapshot()
      Returns an immutable copy of this buffer as a byte string.
      ByteString snapshot​(int byteCount)
      Returns an immutable copy of the first byteCount bytes of this buffer as a byte string.
      Timeout timeout()
      Returns the timeout for this source.
      String toString()
      Returns a string containing a concise, human-readable description of this object.
      Buffer write​(byte[] source)
      Like OutputStream.write(byte[]), this writes a complete byte array to this sink.
      Buffer write​(byte[] source, int offset, int byteCount)
      Like OutputStream.write(byte[], int, int), this writes byteCount bytes of source, starting at offset.
      void write​(Buffer source, long byteCount)
      Removes byteCount bytes from source and appends them to this.
      Buffer write​(ByteString byteString)  
      BufferedSink write​(Source source, long byteCount)
      Removes byteCount bytes from source and appends them to this sink.
      long writeAll​(Source source)
      Removes all bytes from source and appends them to this sink.
      Buffer writeByte​(int b)
      Writes a byte to this sink.
      Buffer writeDecimalLong​(long v)
      Writes a long to this sink in signed decimal form (i.e., as a string in base 10).
      Buffer writeHexadecimalUnsignedLong​(long v)
      Writes a long to this sink in hexadecimal form (i.e., as a string in base 16).
      Buffer writeInt​(int i)
      Writes a big-endian int to this sink using four bytes.
      Buffer writeIntLe​(int i)
      Writes a little-endian int to this sink using four bytes.
      Buffer writeLong​(long v)
      Writes a big-endian long to this sink using eight bytes.
      Buffer writeLongLe​(long v)
      Writes a little-endian long to this sink using eight bytes.
      Buffer writeShort​(int s)
      Writes a big-endian short to this sink using two bytes.
      Buffer writeShortLe​(int s)
      Writes a little-endian short to this sink using two bytes.
      Buffer writeString​(String string, int beginIndex, int endIndex, Charset charset)
      Encodes the characters at beginIndex up to endIndex from string in charset and writes it to this sink.
      Buffer writeString​(String string, Charset charset)
      Encodes string in charset and writes it to this sink.
      Buffer writeTo​(OutputStream out)
      Write the contents of this to out.
      Buffer writeTo​(OutputStream out, long byteCount)
      Write byteCount bytes from this to out.
      Buffer writeUtf8​(String string)
      Encodes string in UTF-8 and writes it to this sink.
      Buffer writeUtf8​(String string, int beginIndex, int endIndex)
      Encodes the characters at beginIndex up to endIndex from string in UTF-8 and writes it to this sink.
      Buffer writeUtf8CodePoint​(int codePoint)
      Encodes codePoint in UTF-8 and writes it to this sink.
    • Constructor Detail

      • Buffer

        public Buffer()
    • Method Detail

      • size

        public long size()
        Returns the number of bytes currently in this buffer.
      • emitCompleteSegments

        public Buffer emitCompleteSegments()
        Description copied from interface: BufferedSink
        Writes complete segments to the underlying sink, if one exists. Like Sink.flush(), but weaker. Use this to limit the memory held in the buffer to a single segment.
        Specified by:
        emitCompleteSegments in interface BufferedSink
      • emit

        public BufferedSink emit()
        Description copied from interface: BufferedSink
        Writes all buffered data to the underlying sink, if one exists. Like Sink.flush(), but weaker. Call this before this buffered sink goes out of scope so that its data can reach its destination.
        Specified by:
        emit in interface BufferedSink
      • exhausted

        public boolean exhausted()
        Description copied from interface: BufferedSource
        Returns true if there are no more bytes in this source. This will block until there are bytes to read or the source is definitely exhausted.
        Specified by:
        exhausted in interface BufferedSource
      • request

        public boolean request​(long byteCount)
        Description copied from interface: BufferedSource
        Returns true when the buffer contains at least byteCount bytes, expanding it as necessary. Returns false if the source is exhausted before the requested bytes can be read.
        Specified by:
        request in interface BufferedSource
      • copyTo

        public Buffer copyTo​(Buffer out,
                             long offset,
                             long byteCount)
        Copy byteCount bytes from this, starting at offset, to out.
      • completeSegmentByteCount

        public long completeSegmentByteCount()
        Returns the number of bytes in segments that are not writable. This is the number of bytes that can be flushed immediately to an underlying sink without harming throughput.
      • readByte

        public byte readByte()
        Description copied from interface: BufferedSource
        Removes a byte from this source and returns it.
        Specified by:
        readByte in interface BufferedSource
      • getByte

        public byte getByte​(long pos)
        Returns the byte at pos.
      • readShort

        public short readShort()
        Description copied from interface: BufferedSource
        Removes two bytes from this source and returns a big-endian short.
        Specified by:
        readShort in interface BufferedSource
      • readInt

        public int readInt()
        Description copied from interface: BufferedSource
        Removes four bytes from this source and returns a big-endian int.
        Specified by:
        readInt in interface BufferedSource
      • readLong

        public long readLong()
        Description copied from interface: BufferedSource
        Removes eight bytes from this source and returns a big-endian long.
        Specified by:
        readLong in interface BufferedSource
      • readShortLe

        public short readShortLe()
        Description copied from interface: BufferedSource
        Removes two bytes from this source and returns a little-endian short.
        Specified by:
        readShortLe in interface BufferedSource
      • readIntLe

        public int readIntLe()
        Description copied from interface: BufferedSource
        Removes four bytes from this source and returns a little-endian int.
        Specified by:
        readIntLe in interface BufferedSource
      • readLongLe

        public long readLongLe()
        Description copied from interface: BufferedSource
        Removes eight bytes from this source and returns a little-endian long.
        Specified by:
        readLongLe in interface BufferedSource
      • readDecimalLong

        public long readDecimalLong()
        Description copied from interface: BufferedSource
        Reads a long from this source in signed decimal form (i.e., as a string in base 10 with optional leading '-'). This will iterate until a non-digit character is found.
        Specified by:
        readDecimalLong in interface BufferedSource
      • readHexadecimalUnsignedLong

        public long readHexadecimalUnsignedLong()
        Description copied from interface: BufferedSource
        Reads a long form this source in hexadecimal form (i.e., as a string in base 16). This will iterate until a non-hexadecimal character is found.
        Specified by:
        readHexadecimalUnsignedLong in interface BufferedSource
      • readAll

        public long readAll​(Sink sink)
                     throws IOException
        Description copied from interface: BufferedSource
        Removes all bytes from this and appends them to sink. Returns the total number of bytes written to sink which will be 0 if this is exhausted.
        Specified by:
        readAll in interface BufferedSource
        Throws:
        IOException
      • readUtf8

        public String readUtf8()
        Description copied from interface: BufferedSource
        Removes all bytes from this, decodes them as UTF-8, and returns the string.
        Specified by:
        readUtf8 in interface BufferedSource
      • readUtf8Line

        public String readUtf8Line()
                            throws EOFException
        Description copied from interface: BufferedSource
        Removes and returns characters up to but not including the next line break. A line break is either "\n" or "\r\n"; these characters are not included in the result.

        On the end of the stream this method returns null, just like BufferedReader. If the source doesn't end with a line break then an implicit line break is assumed. Null is returned once the source is exhausted. Use this for human-generated data, where a trailing line break is optional.

        Specified by:
        readUtf8Line in interface BufferedSource
        Throws:
        EOFException
      • readUtf8LineStrict

        public String readUtf8LineStrict()
                                  throws EOFException
        Description copied from interface: BufferedSource
        Removes and returns characters up to but not including the next line break. A line break is either "\n" or "\r\n"; these characters are not included in the result.

        On the end of the stream this method throws. Every call must consume either '\r\n' or '\n'. If these characters are absent in the stream, an EOFException is thrown. Use this for machine-generated data where a missing line break implies truncated input.

        Specified by:
        readUtf8LineStrict in interface BufferedSource
        Throws:
        EOFException
      • readUtf8CodePoint

        public int readUtf8CodePoint()
                              throws EOFException
        Description copied from interface: BufferedSource
        Removes and returns a single UTF-8 code point, reading between 1 and 4 bytes as necessary.

        If this source is exhausted before a complete code point can be read, this throws an EOFException and consumes no input.

        If this source doesn't start with a properly-encoded UTF-8 code point, this method will remove 1 or more non-UTF-8 bytes and return the replacement character (U+FFFD). This covers encoding problems (the input is not properly-encoded UTF-8), characters out of range (beyond the 0x10ffff limit of Unicode), code points for UTF-16 surrogates (U+d800..U+dfff) and overlong encodings (such as 0xc080 for the NUL character in modified UTF-8).

        Specified by:
        readUtf8CodePoint in interface BufferedSource
        Throws:
        EOFException
      • readByteArray

        public byte[] readByteArray()
        Description copied from interface: BufferedSource
        Removes all bytes from this and returns them as a byte array.
        Specified by:
        readByteArray in interface BufferedSource
      • read

        public int read​(byte[] sink)
        Description copied from interface: BufferedSource
        Removes up to sink.length bytes from this and copies them into sink. Returns the number of bytes read, or -1 if this source is exhausted.
        Specified by:
        read in interface BufferedSource
      • read

        public int read​(byte[] sink,
                        int offset,
                        int byteCount)
        Description copied from interface: BufferedSource
        Removes up to byteCount bytes from this and copies them into sink at offset. Returns the number of bytes read, or -1 if this source is exhausted.
        Specified by:
        read in interface BufferedSource
      • clear

        public void clear()
        Discards all bytes in this buffer. Calling this method when you're done with a buffer will return its segments to the pool.
      • writeUtf8

        public Buffer writeUtf8​(String string,
                                int beginIndex,
                                int endIndex)
        Description copied from interface: BufferedSink
        Encodes the characters at beginIndex up to endIndex from string in UTF-8 and writes it to this sink.
        Specified by:
        writeUtf8 in interface BufferedSink
      • writeString

        public Buffer writeString​(String string,
                                  int beginIndex,
                                  int endIndex,
                                  Charset charset)
        Description copied from interface: BufferedSink
        Encodes the characters at beginIndex up to endIndex from string in charset and writes it to this sink.
        Specified by:
        writeString in interface BufferedSink
      • writeAll

        public long writeAll​(Source source)
                      throws IOException
        Description copied from interface: BufferedSink
        Removes all bytes from source and appends them to this sink. Returns the number of bytes read which will be 0 if source is exhausted.
        Specified by:
        writeAll in interface BufferedSink
        Throws:
        IOException
      • writeShort

        public Buffer writeShort​(int s)
        Description copied from interface: BufferedSink
        Writes a big-endian short to this sink using two bytes.
        Specified by:
        writeShort in interface BufferedSink
      • writeShortLe

        public Buffer writeShortLe​(int s)
        Description copied from interface: BufferedSink
        Writes a little-endian short to this sink using two bytes.
        Specified by:
        writeShortLe in interface BufferedSink
      • writeInt

        public Buffer writeInt​(int i)
        Description copied from interface: BufferedSink
        Writes a big-endian int to this sink using four bytes.
        Specified by:
        writeInt in interface BufferedSink
      • writeIntLe

        public Buffer writeIntLe​(int i)
        Description copied from interface: BufferedSink
        Writes a little-endian int to this sink using four bytes.
        Specified by:
        writeIntLe in interface BufferedSink
      • writeLong

        public Buffer writeLong​(long v)
        Description copied from interface: BufferedSink
        Writes a big-endian long to this sink using eight bytes.
        Specified by:
        writeLong in interface BufferedSink
      • writeLongLe

        public Buffer writeLongLe​(long v)
        Description copied from interface: BufferedSink
        Writes a little-endian long to this sink using eight bytes.
        Specified by:
        writeLongLe in interface BufferedSink
      • writeDecimalLong

        public Buffer writeDecimalLong​(long v)
        Description copied from interface: BufferedSink
        Writes a long to this sink in signed decimal form (i.e., as a string in base 10).
        Specified by:
        writeDecimalLong in interface BufferedSink
      • write

        public void write​(Buffer source,
                          long byteCount)
        Description copied from interface: Sink
        Removes byteCount bytes from source and appends them to this.
        Specified by:
        write in interface Sink
      • read

        public long read​(Buffer sink,
                         long byteCount)
        Description copied from interface: Source
        Removes at least 1, and up to byteCount bytes from this and appends them to sink. Returns the number of bytes read, or -1 if this source is exhausted.
        Specified by:
        read in interface Source
      • indexOf

        public long indexOf​(byte b)
        Description copied from interface: BufferedSource
        Returns the index of the first b in the buffer. This expands the buffer as necessary until b is found. This reads an unbounded number of bytes into the buffer. Returns -1 if the stream is exhausted before the requested byte is found.
        Specified by:
        indexOf in interface BufferedSource
      • indexOf

        public long indexOf​(byte b,
                            long fromIndex)
        Returns the index of b in this at or beyond fromIndex, or -1 if this buffer does not contain b in that range.
        Specified by:
        indexOf in interface BufferedSource
      • indexOf

        public long indexOf​(ByteString bytes)
                     throws IOException
        Description copied from interface: BufferedSource
        Returns the index of the first match for bytes in the buffer. This expands the buffer as necessary until bytes is found. This reads an unbounded number of bytes into the buffer. Returns -1 if the stream is exhausted before the requested bytes are found.
        Specified by:
        indexOf in interface BufferedSource
        Throws:
        IOException
      • indexOf

        public long indexOf​(ByteString bytes,
                            long fromIndex)
                     throws IOException
        Description copied from interface: BufferedSource
        Returns the index of the first match for bytes in the buffer at or after fromIndex. This expands the buffer as necessary until bytes is found. This reads an unbounded number of bytes into the buffer. Returns -1 if the stream is exhausted before the requested bytes are found.
        Specified by:
        indexOf in interface BufferedSource
        Throws:
        IOException
      • indexOfElement

        public long indexOfElement​(ByteString targetBytes)
        Description copied from interface: BufferedSource
        Returns the index of the first byte in targetBytes in the buffer. This expands the buffer as necessary until a target byte is found. This reads an unbounded number of bytes into the buffer. Returns -1 if the stream is exhausted before the requested byte is found.
        Specified by:
        indexOfElement in interface BufferedSource
      • indexOfElement

        public long indexOfElement​(ByteString targetBytes,
                                   long fromIndex)
        Description copied from interface: BufferedSource
        Returns the index of the first byte in targetBytes in the buffer at or after fromIndex. This expands the buffer as necessary until a target byte is found. This reads an unbounded number of bytes into the buffer. Returns -1 if the stream is exhausted before the requested byte is found.
        Specified by:
        indexOfElement in interface BufferedSource
      • flush

        public void flush()
        Description copied from interface: Sink
        Pushes all buffered bytes to their final destination.
        Specified by:
        flush in interface Flushable
        Specified by:
        flush in interface Sink
      • close

        public void close()
        Description copied from interface: Source
        Closes this source and releases the resources held by this source. It is an error to read a closed source. It is safe to close a source more than once.
        Specified by:
        close in interface AutoCloseable
        Specified by:
        close in interface Closeable
        Specified by:
        close in interface Sink
        Specified by:
        close in interface Source
      • timeout

        public Timeout timeout()
        Description copied from interface: Source
        Returns the timeout for this source.
        Specified by:
        timeout in interface Sink
        Specified by:
        timeout in interface Source
      • equals

        public boolean equals​(Object o)
        Description copied from class: Object
        Compares this instance with the specified object and indicates if they are equal. In order to be equal, o must represent the same object as this instance using a class-specific comparison. The general contract is that this comparison should be reflexive, symmetric, and transitive. Also, no object reference other than null is equal to null.

        The default implementation returns true only if this == o. See Writing a correct equals method if you intend implementing your own equals method.

        The general contract for the equals and Object.hashCode() methods is that if equals returns true for any two objects, then hashCode() must return the same value for these objects. This means that subclasses of Object usually override either both methods or neither of them.

        Overrides:
        equals in class Object
        Parameters:
        o - the object to compare this instance with.
        Returns:
        true if the specified object is equal to this Object; false otherwise.
        See Also:
        Object.hashCode()
      • hashCode

        public int hashCode()
        Description copied from class: Object
        Returns an integer hash code for this object. By contract, any two objects for which Object.equals(java.lang.Object) returns true must return the same hash code value. This means that subclasses of Object usually override both methods or neither method.

        Note that hash values must not change over time unless information used in equals comparisons also changes.

        See Writing a correct hashCode method if you intend implementing your own hashCode method.

        Overrides:
        hashCode in class Object
        Returns:
        this object's hash code.
        See Also:
        Object.equals(java.lang.Object)
      • toString

        public String toString()
        Description copied from class: Object
        Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:
           getClass().getName() + '@' + Integer.toHexString(hashCode())

        See Writing a useful toString method if you intend implementing your own toString method.

        Overrides:
        toString in class Object
        Returns:
        a printable representation of this object.
      • clone

        public Buffer clone()
        Returns a deep copy of this buffer.
        Overrides:
        clone in class Object
        Returns:
        a copy of this object.
      • snapshot

        public ByteString snapshot()
        Returns an immutable copy of this buffer as a byte string.
      • snapshot

        public ByteString snapshot​(int byteCount)
        Returns an immutable copy of the first byteCount bytes of this buffer as a byte string.