Path: blob/master/src/java.desktop/share/classes/javax/imageio/stream/MemoryCache.java
41153 views
/*1* Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.imageio.stream;2627import java.util.ArrayList;28import java.io.InputStream;29import java.io.OutputStream;30import java.io.IOException;3132/**33* Package-visible class consolidating common code for34* {@code MemoryCacheImageInputStream} and35* {@code MemoryCacheImageOutputStream}.36* This class keeps an {@code ArrayList} of 8K blocks,37* loaded sequentially. Blocks may only be disposed of38* from the index 0 forward. As blocks are freed, the39* corresponding entries in the array list are set to40* {@code null}, but no compacting is performed.41* This allows the index for each block to never change,42* and the length of the cache is always the same as the43* total amount of data ever cached. Cached data is44* therefore always contiguous from the point of last45* disposal to the current length.46*47* <p> The total number of blocks resident in the cache must not48* exceed {@code Integer.MAX_VALUE}. In practice, the limit of49* available memory will be exceeded long before this becomes an50* issue, since a full cache would contain 8192*2^31 = 16 terabytes of51* data.52*53* A {@code MemoryCache} may be reused after a call54* to {@code reset()}.55*/56class MemoryCache {5758private static final int BUFFER_LENGTH = 8192;5960private ArrayList<byte[]> cache = new ArrayList<>();6162private long cacheStart = 0L;6364/**65* The largest position ever written to the cache.66*/67private long length = 0L;6869private byte[] getCacheBlock(long blockNum) throws IOException {70long blockOffset = blockNum - cacheStart;71if (blockOffset > Integer.MAX_VALUE) {72// This can only happen when the cache hits 16 terabytes of73// contiguous data...74throw new IOException("Cache addressing limit exceeded!");75}76return cache.get((int)blockOffset);77}7879/**80* Ensures that at least {@code pos} bytes are cached,81* or the end of the source is reached. The return value82* is equal to the smaller of {@code pos} and the83* length of the source.84*85* @throws IOException if there is no more memory for cache86*/87public long loadFromStream(InputStream stream, long pos)88throws IOException {89// We've already got enough data cached90if (pos < length) {91return pos;92}9394int offset = (int)(length % BUFFER_LENGTH);95byte [] buf = null;9697long len = pos - length;98if (offset != 0) {99buf = getCacheBlock(length/BUFFER_LENGTH);100}101102while (len > 0) {103if (buf == null) {104try {105buf = new byte[BUFFER_LENGTH];106} catch (OutOfMemoryError e) {107throw new IOException("No memory left for cache!");108}109offset = 0;110}111112int left = BUFFER_LENGTH - offset;113int nbytes = (int)Math.min(len, (long)left);114nbytes = stream.read(buf, offset, nbytes);115if (nbytes == -1) {116return length; // EOF117}118119if (offset == 0) {120cache.add(buf);121}122123len -= nbytes;124length += nbytes;125offset += nbytes;126127if (offset >= BUFFER_LENGTH) {128// we've filled the current buffer, so a new one will be129// allocated next time around (and offset will be reset to 0)130buf = null;131}132}133134return pos;135}136137/**138* Writes out a portion of the cache to an {@code OutputStream}.139* This method preserves no state about the output stream, and does140* not dispose of any blocks containing bytes written. To dispose141* blocks, use {@link #disposeBefore disposeBefore()}.142*143* @exception IndexOutOfBoundsException if any portion of144* the requested data is not in the cache (including if {@code pos}145* is in a block already disposed), or if either {@code pos} or146* {@code len} is < 0.147* @throws IOException if there is an I/O exception while writing to the148* stream149*/150public void writeToStream(OutputStream stream, long pos, long len)151throws IOException {152if (pos + len > length) {153throw new IndexOutOfBoundsException("Argument out of cache");154}155if ((pos < 0) || (len < 0)) {156throw new IndexOutOfBoundsException("Negative pos or len");157}158if (len == 0) {159return;160}161162long bufIndex = pos/BUFFER_LENGTH;163if (bufIndex < cacheStart) {164throw new IndexOutOfBoundsException("pos already disposed");165}166int offset = (int)(pos % BUFFER_LENGTH);167168byte[] buf = getCacheBlock(bufIndex++);169while (len > 0) {170if (buf == null) {171buf = getCacheBlock(bufIndex++);172offset = 0;173}174int nbytes = (int)Math.min(len, (long)(BUFFER_LENGTH - offset));175stream.write(buf, offset, nbytes);176buf = null;177len -= nbytes;178}179}180181/**182* Ensure that there is space to write a byte at the given position.183*184* throws IOException if there is no more memory left for cache185*/186private void pad(long pos) throws IOException {187long currIndex = cacheStart + cache.size() - 1;188long lastIndex = pos/BUFFER_LENGTH;189long numNewBuffers = lastIndex - currIndex;190for (long i = 0; i < numNewBuffers; i++) {191try {192cache.add(new byte[BUFFER_LENGTH]);193} catch (OutOfMemoryError e) {194throw new IOException("No memory left for cache!");195}196}197}198199/**200* Overwrites and/or appends the cache from a byte array.201* The length of the cache will be extended as needed to hold202* the incoming data.203*204* @param b an array of bytes containing data to be written.205* @param off the starting offset within the data array.206* @param len the number of bytes to be written.207* @param pos the cache position at which to begin writing.208*209* @exception NullPointerException if {@code b} is {@code null}.210* @exception IndexOutOfBoundsException if {@code off},211* {@code len}, or {@code pos} are negative,212* or if {@code off+len > b.length}.213* @throws IOException if there is an I/O error while writing to the cache214*/215public void write(byte[] b, int off, int len, long pos)216throws IOException {217if (b == null) {218throw new NullPointerException("b == null!");219}220// Fix 4430357 - if off + len < 0, overflow occurred221if ((off < 0) || (len < 0) || (pos < 0) ||222(off + len > b.length) || (off + len < 0)) {223throw new IndexOutOfBoundsException();224}225226// Ensure there is space for the incoming data227long lastPos = pos + len - 1;228if (lastPos >= length) {229pad(lastPos);230length = lastPos + 1;231}232233// Copy the data into the cache, block by block234int offset = (int)(pos % BUFFER_LENGTH);235while (len > 0) {236byte[] buf = getCacheBlock(pos/BUFFER_LENGTH);237int nbytes = Math.min(len, BUFFER_LENGTH - offset);238System.arraycopy(b, off, buf, offset, nbytes);239240pos += nbytes;241off += nbytes;242len -= nbytes;243offset = 0; // Always after the first time244}245}246247/**248* Overwrites or appends a single byte to the cache.249* The length of the cache will be extended as needed to hold250* the incoming data.251*252* @param b an {@code int} whose 8 least significant bits253* will be written.254* @param pos the cache position at which to begin writing.255*256* @exception IndexOutOfBoundsException if {@code pos} is negative.257* @throws IOException if there is an I/O error while writing to the cache258*/259public void write(int b, long pos) throws IOException {260if (pos < 0) {261throw new ArrayIndexOutOfBoundsException("pos < 0");262}263264// Ensure there is space for the incoming data265if (pos >= length) {266pad(pos);267length = pos + 1;268}269270// Insert the data.271byte[] buf = getCacheBlock(pos/BUFFER_LENGTH);272int offset = (int)(pos % BUFFER_LENGTH);273buf[offset] = (byte)b;274}275276/**277* Returns the total length of data that has been cached,278* regardless of whether any early blocks have been disposed.279* This value will only ever increase.280*/281public long getLength() {282return length;283}284285/**286* Returns the single byte at the given position, as an287* {@code int}. Returns -1 if this position has288* not been cached or has been disposed.289*290* @throws IOException if an I/O error occurs while reading from the byte291* array292*/293public int read(long pos) throws IOException {294if (pos >= length) {295return -1;296}297298byte[] buf = getCacheBlock(pos/BUFFER_LENGTH);299if (buf == null) {300return -1;301}302303return buf[(int)(pos % BUFFER_LENGTH)] & 0xff;304}305306/**307* Copy {@code len} bytes from the cache, starting308* at cache position {@code pos}, into the array309* {@code b} at offset {@code off}.310*311* @exception NullPointerException if b is {@code null}312* @exception IndexOutOfBoundsException if {@code off},313* {@code len} or {@code pos} are negative or if314* {@code off + len > b.length} or if any portion of the315* requested data is not in the cache (including if316* {@code pos} is in a block that has already been disposed).317* @throws IOException if an I/O exception occurs while reading from the318* byte array319*/320public void read(byte[] b, int off, int len, long pos)321throws IOException {322if (b == null) {323throw new NullPointerException("b == null!");324}325// Fix 4430357 - if off + len < 0, overflow occurred326if ((off < 0) || (len < 0) || (pos < 0) ||327(off + len > b.length) || (off + len < 0)) {328throw new IndexOutOfBoundsException();329}330if (pos + len > length) {331throw new IndexOutOfBoundsException();332}333334long index = pos/BUFFER_LENGTH;335int offset = (int)(pos % BUFFER_LENGTH);336while (len > 0) {337int nbytes = Math.min(len, BUFFER_LENGTH - offset);338byte[] buf = getCacheBlock(index++);339System.arraycopy(buf, offset, b, off, nbytes);340341len -= nbytes;342off += nbytes;343offset = 0; // Always after the first time344}345}346347/**348* Free the blocks up to the position {@code pos}.349* The byte at {@code pos} remains available.350*351* @exception IndexOutOfBoundsException if {@code pos}352* is in a block that has already been disposed.353*/354public void disposeBefore(long pos) {355long index = pos/BUFFER_LENGTH;356if (index < cacheStart) {357throw new IndexOutOfBoundsException("pos already disposed");358}359long numBlocks = Math.min(index - cacheStart, cache.size());360for (long i = 0; i < numBlocks; i++) {361cache.remove(0);362}363this.cacheStart = index;364}365366/**367* Erase the entire cache contents and reset the length to 0.368* The cache object may subsequently be reused as though it had just369* been allocated.370*/371public void reset() {372cache.clear();373cacheStart = 0;374length = 0L;375}376}377378379