BridgeBufferIterator.java revision c6fa65b9f29ae26ed3a2f4623cfa0286a1853a8b
1/*
2 * Copyright (C) 2014 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 com.android.layoutlib.bridge.libcore.io;
18
19import java.nio.MappedByteBuffer;
20
21import libcore.io.BufferIterator;
22
23/**
24 * Provides an implementation of {@link BufferIterator} over a {@link MappedByteBuffer}.
25 */
26public class BridgeBufferIterator extends BufferIterator {
27
28    private int mPosition;
29    private final long mSize;
30    private final MappedByteBuffer mMappedByteBuffer;
31
32    public BridgeBufferIterator(long size, MappedByteBuffer buffer) {
33        mSize = size;
34        mMappedByteBuffer = buffer;
35    }
36
37    @Override
38    public void seek(int offset) {
39        assert offset < mSize;
40       mPosition = offset;
41    }
42
43    @Override
44    public void skip(int byteCount) {
45        assert mPosition + byteCount <= mSize;
46        mPosition += byteCount;
47    }
48
49    @Override
50    public void readByteArray(byte[] dst, int dstOffset, int byteCount) {
51        assert dst.length >= dstOffset + byteCount;
52        mMappedByteBuffer.position(mPosition);
53        mMappedByteBuffer.get(dst, dstOffset, byteCount);
54        mPosition = mMappedByteBuffer.position();
55    }
56
57    @Override
58    public byte readByte() {
59        mMappedByteBuffer.position(mPosition);
60        byte b = mMappedByteBuffer.get();
61        mPosition = mMappedByteBuffer.position();
62        return b;
63    }
64
65    @Override
66    public int readInt() {
67        mMappedByteBuffer.position(mPosition);
68        int i = mMappedByteBuffer.getInt();
69        mPosition = mMappedByteBuffer.position();
70        return i;
71    }
72
73    @Override
74    public void readIntArray(int[] dst, int dstOffset, int intCount) {
75        mMappedByteBuffer.position(mPosition);
76        while (--intCount >= 0) {
77            dst[dstOffset++] = mMappedByteBuffer.getInt();
78        }
79        mPosition = mMappedByteBuffer.position();
80    }
81
82    @Override
83    public short readShort() {
84        mMappedByteBuffer.position(mPosition);
85        short s = mMappedByteBuffer.getShort();
86        mPosition = mMappedByteBuffer.position();
87        return s;
88    }
89}
90