001/*
002 * Copyright 2012-2013 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.boot.loader.data;
018
019import java.io.ByteArrayInputStream;
020import java.io.InputStream;
021
022/**
023 * {@link RandomAccessData} implementation backed by a byte array.
024 *
025 * @author Phillip Webb
026 */
027public class ByteArrayRandomAccessData implements RandomAccessData {
028
029        private final byte[] bytes;
030
031        private final long offset;
032
033        private final long length;
034
035        public ByteArrayRandomAccessData(byte[] bytes) {
036                this(bytes, 0, (bytes == null ? 0 : bytes.length));
037        }
038
039        public ByteArrayRandomAccessData(byte[] bytes, long offset, long length) {
040                this.bytes = (bytes == null ? new byte[0] : bytes);
041                this.offset = offset;
042                this.length = length;
043        }
044
045        @Override
046        public InputStream getInputStream(ResourceAccess access) {
047                return new ByteArrayInputStream(this.bytes, (int) this.offset, (int) this.length);
048        }
049
050        @Override
051        public RandomAccessData getSubsection(long offset, long length) {
052                return new ByteArrayRandomAccessData(this.bytes, this.offset + offset, length);
053        }
054
055        @Override
056        public long getSize() {
057                return this.length;
058        }
059
060}