BufferIterator.java revision d6b9f2e0e9640ff9c896b394716cf5e7eee6e257
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
17package libcore.io;
18
19import org.apache.harmony.luni.platform.OSMemory;
20
21/**
22 * Iterates over big- or little-endian bytes. See {@link MemoryMappedFile#bigEndianIterator} and
23 * {@link MemoryMappedFile#littleEndianIterator}.
24 *
25 * @hide don't make this public without adding bounds checking.
26 */
27public final class BufferIterator {
28    private final int address;
29    private final int size;
30    private final boolean swap;
31
32    private int position;
33
34    BufferIterator(int address, int size, boolean swap) {
35        this.address = address;
36        this.size = size;
37        this.swap = swap;
38    }
39
40    /**
41     * Skips forwards or backwards {@code byteCount} bytes from the current position.
42     */
43    public void skip(int byteCount) {
44        position += byteCount;
45    }
46
47    /**
48     * Copies {@code byteCount} bytes from the current position into {@code dst}, starting at
49     * {@code dstOffset}, and advances the current position {@code byteCount} bytes.
50     */
51    public void readByteArray(byte[] dst, int dstOffset, int byteCount) {
52        OSMemory.peekByteArray(address + position, dst, dstOffset, byteCount);
53        position += byteCount;
54    }
55
56    /**
57     * Returns the byte at the current position, and advances the current position one byte.
58     */
59    public byte readByte() {
60        byte result = OSMemory.peekByte(address + position);
61        ++position;
62        return result;
63    }
64
65    /**
66     * Returns the 32-bit int at the current position, and advances the current position four bytes.
67     */
68    public int readInt() {
69        int result = OSMemory.peekInt(address + position, swap);
70        position += 4;
71        return result;
72    }
73
74    /**
75     * Copies {@code intCount} 32-bit ints from the current position into {@code dst}, starting at
76     * {@code dstOffset}, and advances the current position {@code 4 * intCount} bytes.
77     */
78    public void readIntArray(int[] dst, int dstOffset, int intCount) {
79        OSMemory.peekIntArray(address + position, dst, dstOffset, intCount, swap);
80        position += 4 * intCount;
81    }
82}
83