    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.imaging.common.bytesource;
    018
    019import java.io.ByteArrayInputStream;
    020import java.io.IOException;
    021import java.io.InputStream;
    022
    023public class ByteSourceArray extends ByteSource {
    024    private final byte[] bytes;
    025
    026    public ByteSourceArray(final String fileName, final byte[] bytes) {
    027        super(fileName);
    028        this.bytes = bytes;
    029    }
    030
    031    public ByteSourceArray(final byte[] bytes) {
    032        this(null, bytes);
    033    }
    034
    035    @Override
    036    public InputStream getInputStream() {
    037        return new ByteArrayInputStream(bytes);
    038    }
    039
    040    @Override
    041    public byte[] getBlock(final long startLong, final int length) throws IOException {
    042        final int start = (int) startLong;
    043        // We include a separate check for int overflow.
    044        if ((start < 0) || (length < 0) || (start + length < 0)
    045                || (start + length > bytes.length)) {
    046            throw new IOException("Could not read block (block start: " + start
    047                    + ", block length: " + length + ", data length: "
    048                    + bytes.length + ").");
    049        }
    050
    051        final byte[] result = new byte[length];
    052        System.arraycopy(bytes, start, result, 0, length);
    053        return result;
    054    }
    055
    056    @Override
    057    public long getLength() {
    058        return bytes.length;
    059    }
    060
    061    @Override
    062    public byte[] getAll() throws IOException {
    063        return bytes;
    064    }
    065
    066    @Override
    067    public String getDescription() {
    068        return bytes.length + " byte array";
    069    }
    070
    071}