1 /* 2 * Copyright (C) 2010 The Android Open Source Project 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 17 package libcore.io; 18 19 import java.nio.ByteOrder; 20 import libcore.io.Memory; 21 22 /** 23 * Iterates over big- or little-endian bytes in a Java byte[]. 24 * 25 * @hide don't make this public without adding bounds checking. 26 */ 27 public final class HeapBufferIterator extends BufferIterator { 28 private final byte[] buffer; 29 private final int offset; 30 private final int byteCount; 31 private final ByteOrder order; 32 33 private int position; 34 35 HeapBufferIterator(byte[] buffer, int offset, int byteCount, ByteOrder order) { 36 this.buffer = buffer; 37 this.offset = offset; 38 this.byteCount = byteCount; 39 this.order = order; 40 } 41 42 public void seek(int offset) { 43 position = offset; 44 } 45 46 public void skip(int byteCount) { 47 position += byteCount; 48 } 49 50 public void readByteArray(byte[] dst, int dstOffset, int byteCount) { 51 System.arraycopy(buffer, offset + position, dst, dstOffset, byteCount); 52 position += byteCount; 53 } 54 55 public byte readByte() { 56 byte result = buffer[offset + position]; 57 ++position; 58 return result; 59 } 60 61 public int readInt() { 62 int result = Memory.peekInt(buffer, offset + position, order); 63 position += SizeOf.INT; 64 return result; 65 } 66 67 public void readIntArray(int[] dst, int dstOffset, int intCount) { 68 final int byteCount = intCount * SizeOf.INT; 69 Memory.unsafeBulkGet(dst, dstOffset, byteCount, buffer, offset + position, SizeOf.INT, order.needsSwap); 70 position += byteCount; 71 } 72 73 public short readShort() { 74 short result = Memory.peekShort(buffer, offset + position, order); 75 position += SizeOf.SHORT; 76 return result; 77 } 78 79 /** 80 * Returns a new iterator over {@code buffer}, starting at {@code offset} and continuing for 81 * {@code byteCount} bytes. Items larger than a byte are interpreted using the given byte order. 82 */ 83 public static BufferIterator iterator(byte[] buffer, int offset, int byteCount, ByteOrder order) { 84 return new HeapBufferIterator(buffer, offset, byteCount, order); 85 } 86 } 87