Reads MAT-file header.

Modifies <code>buf</code> position.

@param buf
<code>ByteBuffer</code>
@throws IOException
if reading from buffer fails or if this is not a valid
MAT-file
344480
private void readHeader(ByteBuffer buf) throws IOException
    {
        //header values
        String description;
        int version;
        byte[] endianIndicator = new byte[2];

        // This part of the header is missing if the file isn't a regular mat file.  So ignore.
        if (matType == MatFileType.Regular) {
            //descriptive text 116 bytes
            byte[] descriptionBuffer = new byte[116];
            buf.get(descriptionBuffer);

            description = zeroEndByteArrayToString(descriptionBuffer);

            if (!description.matches("MATLAB 5.0 MAT-file.*")) {
                throw new MatlabIOException("This is not a valid MATLAB 5.0 MAT-file.");
            }

            //subsyst data offset 8 bytes
            buf.position(buf.position() + 8);
        } else {
            description = "Simulink generated MATLAB 5.0 MAT-file"; // Default simulink description.
        }
        
        byte[] bversion = new byte[2];
        //version 2 bytes
        buf.get(bversion);
        
        //endian indicator 2 bytes
        buf.get(endianIndicator);
        
        //program reading the MAT-file must perform byte swapping to interpret the data
        //in the MAT-file correctly
        if ( (char)endianIndicator[0] == 'I' && (char)endianIndicator[1] == 'M')
        {
            byteOrder = ByteOrder.LITTLE_ENDIAN;
            version = bversion[1] & 0xff | bversion[0] << 8;
        }
        else
        {
            byteOrder = ByteOrder.BIG_ENDIAN;
            version = bversion[0] & 0xff | bversion[1] << 8;
        }
        
        buf.order( byteOrder );
        
        matFileHeader = new MatFileHeader(description, version, endianIndicator, byteOrder);

        // After the header, the next read must be aligned.  Thus force the alignment.  Only matters with reduced header data,
        // but apply it regardless for safety.
        buf.position((buf.position() + 7) & 0xfffffff8);
    }
499466
private void fillBuf() throws IOException {
		int result = in.read(buf, 0, buf.length);
		if (result == -1) {
			throw new EOFException();
		}
		pos = 0;
		end = result;
	}
1282077
private void writeHeader(WritableByteChannel channel) throws IOException
    {
        //write descriptive text
        MatFileHeader header = MatFileHeader.createHeader();
        char[] dest = new char[116];
        char[] src = header.getDescription().toCharArray();
        System.arraycopy(src, 0, dest, 0, src.length);

        byte[] endianIndicator = header.getEndianIndicator();

        ByteBuffer buf = ByteBuffer.allocateDirect(dest.length * 2 /* Char size */ + 2 + endianIndicator.length);

        for ( int i = 0; i < dest.length; i++ )
        {
            buf.put( (byte)dest[i] );
        }
        //write subsyst data offset
        buf.position( buf.position() + 8);

        //write version
        int version = header.getVersion();
        buf.put( (byte)(version >> 8) );
        buf.put( (byte)version );

        buf.put( endianIndicator );

        buf.flip();
        channel.write(buf);
    }
400616
public synchronized long readFromEnd(final long datalen, final ByteBuffer buf) {
		if (!validState) {
			throw new InvalidStateException();
		}
		final long size = size();
		final long offset = (size - HEADER_LEN - datalen - FOOTER_LEN);
		return read(offset, buf);
	}
1345030
public int read(CharBuffer buf, int length) throws IOException
  {
    int len = buf.length();

    buf.length(len + length);
    
    int readLength = read(buf.buffer(), len, length);
    
    if (readLength < 0) {
      buf.length(len);
    }
    else if (readLength < length) {
      buf.length(len + readLength);
    }

    return length;
  }
142026
public int read(char []buf, int offset, int length)
    throws IOException
  {
    for (int i = 0; i < length; i++) {
      int ch = _is.read();

      if (ch < 0)
        return i > 0 ? i : -1;
      else {
        buf[offset + i] = (char) ch;
      }
    }
      
    return length;
  }
1322090
private void readHeader() throws IOException {
    headerBuffer.rewind();

    final int flgRead = in.read();
    if (flgRead < 0) {
      throw new IOException(PREMATURE_EOS);
    }
    final int bdRead = in.read();
    if (bdRead < 0) {
      throw new IOException(PREMATURE_EOS);
    }

    final byte flgByte = (byte)(flgRead & 0xFF);
    final LZ4FrameOutputStream.FLG flg = LZ4FrameOutputStream.FLG.fromByte(flgByte);
    headerBuffer.put(flgByte);
    final byte bdByte = (byte)(bdRead & 0xFF);
    final LZ4FrameOutputStream.BD bd = LZ4FrameOutputStream.BD.fromByte(bdByte);
    headerBuffer.put(bdByte);

    this.frameInfo = new LZ4FrameOutputStream.FrameInfo(flg, bd);

    if (flg.isEnabled(LZ4FrameOutputStream.FLG.Bits.CONTENT_SIZE)) {
      expectedContentSize = readLong(in);
      headerBuffer.putLong(expectedContentSize);
    }
    totalContentSize = 0L;

    // check stream descriptor hash
    final byte hash = (byte) ((checksum.hash(headerArray, 0, headerBuffer.position(), 0) >> 8) & 0xFF);
    final int expectedHash = in.read();
    if (expectedHash < 0) {
      throw new IOException(PREMATURE_EOS);
    }

    if (hash != (byte)(expectedHash & 0xFF)) {
      throw new IOException(DESCRIPTOR_HASH_MISMATCH);
    }

    maxBlockSize = frameInfo.getBD().getBlockMaximumSize();
    compressedBuffer = new byte[maxBlockSize]; // Reused during different compressions
    rawBuffer = new byte[maxBlockSize];
    buffer = ByteBuffer.wrap(rawBuffer);
    buffer.limit(0);
  }
682328
public static byte[] getBytes(ByteBuffer buf) {
    int savedPos = buf.position();
    byte [] newBytes = new byte[buf.remaining()];
    buf.get(newBytes);
    buf.position(savedPos);
    return newBytes;
  }
1229282
private void readHeaderFromBuffer(final ByteBuffer buffer) {
    int toRead = MIN_RECV_PACKET - headerOffset;
    int available = buffer.remaining();
    toRead = Math.min(toRead, available);
    getLogger().debug("Reading %d header bytes", toRead);
    buffer.get(header, headerOffset, toRead);
    headerOffset += toRead;
  }
143054
public static ByteBuffer copyBuffer(final ByteBuffer buf) {
        if(buf == null)
            return null;
        int offset=buf.hasArray()? buf.arrayOffset() + buf.position() : buf.position(), len=buf.remaining();
        byte[] tmp=new byte[len];
        if(!buf.isDirect())
            System.arraycopy(buf.array(), offset, tmp, 0, len);
        else {
         //   buf.get(tmp, 0, len);
            for(int i=0; i < len; i++)
                tmp[i]=buf.get(i+offset);
        }
        return ByteBuffer.wrap(tmp);
    }
1170873
def _read_bytes(fp, buf):
    

    # Do the first read without resizing the input buffer
    offset = 0
    remaining = len(buf)
    while remaining > 0:
        l = fp.readinto((ctypes.c_char * remaining).from_buffer(buf, offset))
        if l is None or l == 0:
            return offset
        offset += l
        remaining -= l
    return offset
206176
@Override
    public ImageHeader readHeader(InputStream input) throws IOException
    {
        final long toSkip = 8L;
        final boolean bigEndian = 'M' == input.read();
        checkSkippedError(input.skip(HEADER_SIZE - 1L), HEADER_SIZE - 1);
        final int ifd = readInt(input, 4, bigEndian);
        input.skip(ifd - toSkip);
        // checkSkippedError(skipped, ifd - toSkip); fail when reading from JAR, not needed
        final int entries = readInt(input, 2, bigEndian);

        int width = -1;
        int height = -1;
        for (int i = 1; i <= entries; i++)
        {
            final int tag = readInt(input, 2, bigEndian);
            final int fieldType = readInt(input, 2, bigEndian);
            readInt(input, VAL_OFFSET_BYTES, bigEndian);
            final int valOffset;
            if (VAL_OFFSET_FIELD_1 == fieldType || VAL_OFFSET_FIELD_2 == fieldType)
            {
                valOffset = readInt(input, 2, bigEndian);
                final long skipped = input.skip(2);
                checkSkippedError(skipped, 2);
            }
            else
            {
                valOffset = readInt(input, VAL_OFFSET_BYTES, bigEndian);
            }
            if (TAG_WIDTH == tag)
            {
                width = valOffset;
            }
            else if (TAG_HEIGHT == tag)
            {
                height = valOffset;
            }
            if (-1 != width && -1 != height)
            {
                return new ImageHeaderModel(width, height, ImageFormat.TIFF);
            }
        }
        throw new IOException(ERROR_TIFF);
    }
1074202
@SuppressWarnings("cast")
    @Override
    public int read(char[] cbuf, int start, int len) throws IOException
    {
        // Let's first ensure there's enough room...
        if (start < 0 || (start+len) > cbuf.length) {
            reportBounds(cbuf, start, len);
        }
        // Already EOF?
        if (mByteBuffer == null) {
            return -1;
        }
        if (len < 1) { // dummy call?
            return 0;
        }

        len += start;
        int outPtr = start;

        // Ok, first; do we have a surrogate from last round?
        if (mSurrogate != NULL_CHAR) {
            cbuf[outPtr++] = mSurrogate;
            mSurrogate = NULL_CHAR;
            // No need to load more, already got one char
        } else {
            /* To prevent unnecessary blocking (esp. with network streams),
             * we'll only require decoding of a single char
             */
            int left = (mByteBufferEnd - mBytePtr);

            /* So; only need to load more if we can't provide at least
             * one more character. We need not do thorough check here,
             * but let's check the common cases here: either completely
             * empty buffer (left == 0), or one with less than max. byte
             * count for a single char, and starting of a multi-byte
             * encoding (this leaves possibility of a 2/3-byte char
             * that is still fully accessible... but that can be checked
             * by the load method)
             */

            if (left < 4) {
                // Need to load more?
                if (left < 1 || mByteBuffer[mBytePtr] < 0) {
                    if (!loadMore(left)) { // (legal) EOF?
                        return -1;
                    }
                }
            }
        }

        /* This may look silly, but using a local var is indeed faster
         * (if and when HotSpot properly gets things running) than
         * member variable...
         */
        byte[] buf = mByteBuffer;
        int inPtr = mBytePtr;
        int inBufLen = mByteBufferEnd;

        main_loop:
        while (outPtr < len) {
            // At this point we have at least one byte available
            int c = (int) buf[inPtr++];

            /* Let's first do the quickie loop for common case; 7-bit
             * ascii:
             */
            if (c >= 0) { // ascii? can probably loop, then
                if (c == 0x7F && mXml11) { // DEL illegal in xml1.1
                    int bytePos = mByteCount + inPtr - 1;
                    int charPos = mCharCount + (outPtr-start);
                    reportInvalidXml11(c, bytePos, charPos);
                }
                cbuf[outPtr++] = (char) c; // ok since MSB is never on

                /* Ok, how many such chars could we safely process
                 * without overruns? (will combine 2 in-loop comparisons
                 * into just one)
                 */
                int outMax = (len - outPtr); // max output
                int inMax = (inBufLen - inPtr); // max input
                int inEnd = inPtr + ((inMax < outMax) ? inMax : outMax);

                ascii_loop:
                while (true) {
                    if (inPtr >= inEnd) {
                        break main_loop;
                    }
                    c = ((int) buf[inPtr++]) & 0xFF;
                    if (c >= 0x7F) { // DEL, or multi-byte
                        break ascii_loop;
                    }
                    cbuf[outPtr++] = (char) c;
                }
                if (c == 0x7F) { 
                    if (mXml11) { // DEL illegal in xml1.1
                        int bytePos = mByteCount + inPtr - 1;
                        int charPos = mCharCount + (outPtr-start);
                        reportInvalidXml11(c, bytePos, charPos);
                    } // but not in xml 1.0
                    cbuf[outPtr++] = (char) c;
                    if(inPtr >= inEnd){
                    	break main_loop;
                    }
                    continue main_loop;
                }
            }

            int needed;

            // Ok; if we end here, we got multi-byte combination
            if ((c & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF)
                c = (c & 0x1F);
                needed = 1;
            } else if ((c & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF)
                c = (c & 0x0F);
                needed = 2;
            } else if ((c & 0xF8) == 0xF0) {
                // 4 bytes; double-char BS, with surrogates and all...
                c = (c & 0x0F);
                needed = 3;
            } else {
                reportInvalidInitial(c & 0xFF, outPtr-start);
                // never gets here...
                needed = 1;
            }
            /* Do we have enough bytes? If not, let's just push back the
             * byte and leave, since we have already gotten at least one
             * char decoded. This way we will only block (with read from
             * input stream) when absolutely necessary.
             */
            if ((inBufLen - inPtr) < needed) {
                --inPtr;
                break main_loop;
            }

            int d = (int) buf[inPtr++];
            if ((d & 0xC0) != 0x080) {
                reportInvalidOther(d & 0xFF, outPtr-start);
            }
            c = (c << 6) | (d & 0x3F);

            if (needed > 1) { // needed == 1 means 2 bytes total
                d = buf[inPtr++]; // 3rd byte
                if ((d & 0xC0) != 0x080) {
                    reportInvalidOther(d & 0xFF, outPtr-start);
                }
                c = (c << 6) | (d & 0x3F);
                if (needed > 2) { // 4 bytes? (need surrogates)
                    d = buf[inPtr++];
                    if ((d & 0xC0) != 0x080) {
                        reportInvalidOther(d & 0xFF, outPtr-start);
                    }
                    c = (c << 6) | (d & 0x3F);
                    if (c > XmlConsts.MAX_UNICODE_CHAR) {
                        reportInvalid(c, outPtr-start,
                                      "(above "+Integer.toHexString(XmlConsts.MAX_UNICODE_CHAR)+") ");
                    }
                    /* Ugh. Need to mess with surrogates. Ok; let's inline them
                     * there, then, if there's room: if only room for one,
                     * need to save the surrogate for the rainy day...
                     */
                    c -= 0x10000; // to normalize it starting with 0x0
                    cbuf[outPtr++] = (char) (0xD800 + (c >> 10));
                    // hmmh. can this ever be 0? (not legal, at least?)
                    c = (0xDC00 | (c & 0x03FF));

                    // Room for second part?
                    if (outPtr >= len) { // nope
                        mSurrogate = (char) c;
                        break main_loop;
                    }
                    // sure, let's fall back to normal processing:
                } else {
                    /* Otherwise, need to check that 3-byte chars are
                     * legal ones (should not expand to surrogates;
                     * 0xFFFE and 0xFFFF are illegal)
                     */
                    if (c >= 0xD800) {
                        // But first, let's check max chars:
                        if (c < 0xE000) {
                            reportInvalid(c, outPtr-start, "(a surrogate character) ");
                        } else if (c >= 0xFFFE) {
                            reportInvalid(c, outPtr-start, "");
                        }
                    } else if (mXml11 && c == 0x2028) { // LSEP?
                        /* 10-May-2006, TSa: Since LSEP is "non-associative",
                         *    it needs additional handling. One way to do
                         *    this is to convert preceding \r to \n. This
                         *    should be implemented better when integrating
                         *    decoder and tokenizer.
                         */
                        if (outPtr > start && cbuf[outPtr-1] == '\r') {
                            cbuf[outPtr-1] = '\n';
                        }
                        c = CONVERT_LSEP_TO;
                    }
                }
            } else { // (needed == 1)
                if (mXml11) { // high-order ctrl char detection...
                    if (c <= 0x9F) {
                        if (c == 0x85) { // NEL, let's convert?
                            c = CONVERT_NEL_TO;
                        } else if (c >= 0x7F) { // DEL, ctrl chars
                            int bytePos = mByteCount + inPtr - 1;
                            int charPos = mCharCount + (outPtr-start);
                            reportInvalidXml11(c, bytePos, charPos);
                        }
                    }
                }
            }
            cbuf[outPtr++] = (char) c;
            if (inPtr >= inBufLen) {
                break main_loop;
            }
        }

        mBytePtr = inPtr;
        len = outPtr - start;
        mCharCount += len;
        return len;
    }
965434
public static ByteBuffer toByteBuffer(File file) {
        ByteBuffer buffer = ByteBuffer.allocateDirect((int) file.length());
        try {
            buffer.put(toByteArray(new FileInputStream(file)));
        } catch (IOException e) {
            logger.error("Failed to write file to byte array: " + e.getMessage());
        }
        buffer.flip();
        return buffer;
    }
28218
public void read(ByteBuffer buffer) {
        Persistables.persistable(streamableNoBuffers()).read(buffer);

        final int n = getNumDataBuffers();
        int lengthsPosition = buffer.position();
        buffer.position(buffer.position() + 2 * n); // skip positions
        for (int i = 0; i < n; i++) {
            final int size = buffer.getShort(lengthsPosition) & 0xFFFF; // big-endian
            lengthsPosition += 2;

            final ByteBuffer b1 = Persistables.slice(buffer, size);
            setDataBuffer(i, b1);
        }
    }
805839
public void serialize(final ByteBuffer buf) {

		checkInvariants();

		if (!sizeIsSticky)
			trimToSize();

		buf.putInt(wordsInUse);
		for (int i = 0; i < wordsInUse; i++) {
			buf.putLong(words[i]);
		}
	}
1304797
public boolean readLine(Appendable buf) throws IOException {
    boolean success = false;
    while(true) {
      // Process buffer:
      while(pos < end) {
        success = true;
        final char c = buffer[pos++];
        if(c == '\n') {
          return success;
        }
        if(c == '\r') {
          continue;
        }
        buf.append(c);
      }
      // Refill buffer:
      assert (pos >= end) : "Buffer wasn't empty when refilling!";
      end = in.read(buffer, 0, buffer.length);
      pos = 0;
      if(end < 0) { // End of stream.
        return success;
      }
    }
  }