You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TemporaryBuffer.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. /*
  2. * Copyright (C) 2008-2009, Google Inc.
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.util;
  45. import java.io.BufferedOutputStream;
  46. import java.io.File;
  47. import java.io.FileInputStream;
  48. import java.io.FileOutputStream;
  49. import java.io.IOException;
  50. import java.io.InputStream;
  51. import java.io.OutputStream;
  52. import java.util.ArrayList;
  53. import org.eclipse.jgit.internal.JGitText;
  54. import org.eclipse.jgit.lib.NullProgressMonitor;
  55. import org.eclipse.jgit.lib.ProgressMonitor;
  56. import org.eclipse.jgit.util.io.SafeBufferedOutputStream;
  57. /**
  58. * A fully buffered output stream.
  59. * <p>
  60. * Subclasses determine the behavior when the in-memory buffer capacity has been
  61. * exceeded and additional bytes are still being received for output.
  62. */
  63. public abstract class TemporaryBuffer extends OutputStream {
  64. /** Default limit for in-core storage. */
  65. protected static final int DEFAULT_IN_CORE_LIMIT = 1024 * 1024;
  66. /** Chain of data, if we are still completely in-core; otherwise null. */
  67. private ArrayList<Block> blocks;
  68. /**
  69. * Maximum number of bytes we will permit storing in memory.
  70. * <p>
  71. * When this limit is reached the data will be shifted to a file on disk,
  72. * preventing the JVM heap from growing out of control.
  73. */
  74. private int inCoreLimit;
  75. /** Initial size of block list. */
  76. private int initialBlocks;
  77. /** If {@link #inCoreLimit} has been reached, remainder goes here. */
  78. private OutputStream overflow;
  79. /**
  80. * Create a new empty temporary buffer.
  81. *
  82. * @param limit
  83. * maximum number of bytes to store in memory before entering the
  84. * overflow output path; also used as the estimated size.
  85. */
  86. protected TemporaryBuffer(final int limit) {
  87. this(limit, limit);
  88. }
  89. /**
  90. * Create a new empty temporary buffer.
  91. *
  92. * @param estimatedSize
  93. * estimated size of storage used, to size the initial list of
  94. * block pointers.
  95. * @param limit
  96. * maximum number of bytes to store in memory before entering the
  97. * overflow output path.
  98. * @since 4.0
  99. */
  100. protected TemporaryBuffer(final int estimatedSize, final int limit) {
  101. if (estimatedSize > limit)
  102. throw new IllegalArgumentException();
  103. this.inCoreLimit = limit;
  104. this.initialBlocks = (estimatedSize - 1) / Block.SZ + 1;
  105. reset();
  106. }
  107. @Override
  108. public void write(final int b) throws IOException {
  109. if (overflow != null) {
  110. overflow.write(b);
  111. return;
  112. }
  113. Block s = last();
  114. if (s.isFull()) {
  115. if (reachedInCoreLimit()) {
  116. overflow.write(b);
  117. return;
  118. }
  119. s = new Block();
  120. blocks.add(s);
  121. }
  122. s.buffer[s.count++] = (byte) b;
  123. }
  124. @Override
  125. public void write(final byte[] b, int off, int len) throws IOException {
  126. if (overflow == null) {
  127. while (len > 0) {
  128. Block s = last();
  129. if (s.isFull()) {
  130. if (reachedInCoreLimit())
  131. break;
  132. s = new Block();
  133. blocks.add(s);
  134. }
  135. final int n = Math.min(s.buffer.length - s.count, len);
  136. System.arraycopy(b, off, s.buffer, s.count, n);
  137. s.count += n;
  138. len -= n;
  139. off += n;
  140. }
  141. }
  142. if (len > 0)
  143. overflow.write(b, off, len);
  144. }
  145. /**
  146. * Dumps the entire buffer into the overflow stream, and flushes it.
  147. *
  148. * @throws IOException
  149. * the overflow stream cannot be started, or the buffer contents
  150. * cannot be written to it, or it failed to flush.
  151. */
  152. protected void doFlush() throws IOException {
  153. if (overflow == null)
  154. switchToOverflow();
  155. overflow.flush();
  156. }
  157. /**
  158. * Copy all bytes remaining on the input stream into this buffer.
  159. *
  160. * @param in
  161. * the stream to read from, until EOF is reached.
  162. * @throws IOException
  163. * an error occurred reading from the input stream, or while
  164. * writing to a local temporary file.
  165. */
  166. public void copy(final InputStream in) throws IOException {
  167. if (blocks != null) {
  168. for (;;) {
  169. Block s = last();
  170. if (s.isFull()) {
  171. if (reachedInCoreLimit())
  172. break;
  173. s = new Block();
  174. blocks.add(s);
  175. }
  176. int n = in.read(s.buffer, s.count, s.buffer.length - s.count);
  177. if (n < 1)
  178. return;
  179. s.count += n;
  180. }
  181. }
  182. final byte[] tmp = new byte[Block.SZ];
  183. int n;
  184. while ((n = in.read(tmp)) > 0)
  185. overflow.write(tmp, 0, n);
  186. }
  187. /**
  188. * Obtain the length (in bytes) of the buffer.
  189. * <p>
  190. * The length is only accurate after {@link #close()} has been invoked.
  191. *
  192. * @return total length of the buffer, in bytes.
  193. */
  194. public long length() {
  195. return inCoreLength();
  196. }
  197. private long inCoreLength() {
  198. final Block last = last();
  199. return ((long) blocks.size() - 1) * Block.SZ + last.count;
  200. }
  201. /**
  202. * Convert this buffer's contents into a contiguous byte array.
  203. * <p>
  204. * The buffer is only complete after {@link #close()} has been invoked.
  205. *
  206. * @return the complete byte array; length matches {@link #length()}.
  207. * @throws IOException
  208. * an error occurred reading from a local temporary file
  209. * @throws OutOfMemoryError
  210. * the buffer cannot fit in memory
  211. */
  212. public byte[] toByteArray() throws IOException {
  213. final long len = length();
  214. if (Integer.MAX_VALUE < len)
  215. throw new OutOfMemoryError(JGitText.get().lengthExceedsMaximumArraySize);
  216. final byte[] out = new byte[(int) len];
  217. int outPtr = 0;
  218. for (final Block b : blocks) {
  219. System.arraycopy(b.buffer, 0, out, outPtr, b.count);
  220. outPtr += b.count;
  221. }
  222. return out;
  223. }
  224. /**
  225. * Send this buffer to an output stream.
  226. * <p>
  227. * This method may only be invoked after {@link #close()} has completed
  228. * normally, to ensure all data is completely transferred.
  229. *
  230. * @param os
  231. * stream to send this buffer's complete content to.
  232. * @param pm
  233. * if not null progress updates are sent here. Caller should
  234. * initialize the task and the number of work units to <code>
  235. * {@link #length()}/1024</code>.
  236. * @throws IOException
  237. * an error occurred reading from a temporary file on the local
  238. * system, or writing to the output stream.
  239. */
  240. public void writeTo(final OutputStream os, ProgressMonitor pm)
  241. throws IOException {
  242. if (pm == null)
  243. pm = NullProgressMonitor.INSTANCE;
  244. for (final Block b : blocks) {
  245. os.write(b.buffer, 0, b.count);
  246. pm.update(b.count / 1024);
  247. }
  248. }
  249. /**
  250. * Open an input stream to read from the buffered data.
  251. * <p>
  252. * This method may only be invoked after {@link #close()} has completed
  253. * normally, to ensure all data is completely transferred.
  254. *
  255. * @return a stream to read from the buffer. The caller must close the
  256. * stream when it is no longer useful.
  257. * @throws IOException
  258. * an error occurred opening the temporary file.
  259. */
  260. public InputStream openInputStream() throws IOException {
  261. return new BlockInputStream();
  262. }
  263. /** Reset this buffer for reuse, purging all buffered content. */
  264. public void reset() {
  265. if (overflow != null) {
  266. destroy();
  267. }
  268. if (blocks != null)
  269. blocks.clear();
  270. else
  271. blocks = new ArrayList<Block>(initialBlocks);
  272. blocks.add(new Block(Math.min(inCoreLimit, Block.SZ)));
  273. }
  274. /**
  275. * Open the overflow output stream, so the remaining output can be stored.
  276. *
  277. * @return the output stream to receive the buffered content, followed by
  278. * the remaining output.
  279. * @throws IOException
  280. * the buffer cannot create the overflow stream.
  281. */
  282. protected abstract OutputStream overflow() throws IOException;
  283. private Block last() {
  284. return blocks.get(blocks.size() - 1);
  285. }
  286. private boolean reachedInCoreLimit() throws IOException {
  287. if (inCoreLength() < inCoreLimit)
  288. return false;
  289. switchToOverflow();
  290. return true;
  291. }
  292. private void switchToOverflow() throws IOException {
  293. overflow = overflow();
  294. final Block last = blocks.remove(blocks.size() - 1);
  295. for (final Block b : blocks)
  296. overflow.write(b.buffer, 0, b.count);
  297. blocks = null;
  298. overflow = new SafeBufferedOutputStream(overflow, Block.SZ);
  299. overflow.write(last.buffer, 0, last.count);
  300. }
  301. public void close() throws IOException {
  302. if (overflow != null) {
  303. try {
  304. overflow.close();
  305. } finally {
  306. overflow = null;
  307. }
  308. }
  309. }
  310. /** Clear this buffer so it has no data, and cannot be used again. */
  311. public void destroy() {
  312. blocks = null;
  313. if (overflow != null) {
  314. try {
  315. overflow.close();
  316. } catch (IOException err) {
  317. // We shouldn't encounter an error closing the file.
  318. } finally {
  319. overflow = null;
  320. }
  321. }
  322. }
  323. /**
  324. * A fully buffered output stream using local disk storage for large data.
  325. * <p>
  326. * Initially this output stream buffers to memory and is therefore similar
  327. * to ByteArrayOutputStream, but it shifts to using an on disk temporary
  328. * file if the output gets too large.
  329. * <p>
  330. * The content of this buffered stream may be sent to another OutputStream
  331. * only after this stream has been properly closed by {@link #close()}.
  332. */
  333. public static class LocalFile extends TemporaryBuffer {
  334. /** Directory to store the temporary file under. */
  335. private final File directory;
  336. /**
  337. * Location of our temporary file if we are on disk; otherwise null.
  338. * <p>
  339. * If we exceeded the {@link #inCoreLimit} we nulled out {@link #blocks}
  340. * and created this file instead. All output goes here through
  341. * {@link #overflow}.
  342. */
  343. private File onDiskFile;
  344. /**
  345. * Create a new temporary buffer.
  346. *
  347. * @deprecated Use the {@code File} overload to supply a directory.
  348. */
  349. @Deprecated
  350. public LocalFile() {
  351. this(null, DEFAULT_IN_CORE_LIMIT);
  352. }
  353. /**
  354. * Create a new temporary buffer, limiting memory usage.
  355. *
  356. * @param inCoreLimit
  357. * maximum number of bytes to store in memory. Storage beyond
  358. * this limit will use the local file.
  359. * @deprecated Use the {@code File,int} overload to supply a directory.
  360. */
  361. @Deprecated
  362. public LocalFile(final int inCoreLimit) {
  363. this(null, inCoreLimit);
  364. }
  365. /**
  366. * Create a new temporary buffer, limiting memory usage.
  367. *
  368. * @param directory
  369. * if the buffer has to spill over into a temporary file, the
  370. * directory where the file should be saved. If null the
  371. * system default temporary directory (for example /tmp) will
  372. * be used instead.
  373. */
  374. public LocalFile(final File directory) {
  375. this(directory, DEFAULT_IN_CORE_LIMIT);
  376. }
  377. /**
  378. * Create a new temporary buffer, limiting memory usage.
  379. *
  380. * @param directory
  381. * if the buffer has to spill over into a temporary file, the
  382. * directory where the file should be saved. If null the
  383. * system default temporary directory (for example /tmp) will
  384. * be used instead.
  385. * @param inCoreLimit
  386. * maximum number of bytes to store in memory. Storage beyond
  387. * this limit will use the local file.
  388. */
  389. public LocalFile(final File directory, final int inCoreLimit) {
  390. super(inCoreLimit);
  391. this.directory = directory;
  392. }
  393. protected OutputStream overflow() throws IOException {
  394. onDiskFile = File.createTempFile("jgit_", ".buf", directory); //$NON-NLS-1$ //$NON-NLS-2$
  395. return new BufferedOutputStream(new FileOutputStream(onDiskFile));
  396. }
  397. public long length() {
  398. if (onDiskFile == null) {
  399. return super.length();
  400. }
  401. return onDiskFile.length();
  402. }
  403. public byte[] toByteArray() throws IOException {
  404. if (onDiskFile == null) {
  405. return super.toByteArray();
  406. }
  407. final long len = length();
  408. if (Integer.MAX_VALUE < len)
  409. throw new OutOfMemoryError(JGitText.get().lengthExceedsMaximumArraySize);
  410. final byte[] out = new byte[(int) len];
  411. final FileInputStream in = new FileInputStream(onDiskFile);
  412. try {
  413. IO.readFully(in, out, 0, (int) len);
  414. } finally {
  415. in.close();
  416. }
  417. return out;
  418. }
  419. public void writeTo(final OutputStream os, ProgressMonitor pm)
  420. throws IOException {
  421. if (onDiskFile == null) {
  422. super.writeTo(os, pm);
  423. return;
  424. }
  425. if (pm == null)
  426. pm = NullProgressMonitor.INSTANCE;
  427. final FileInputStream in = new FileInputStream(onDiskFile);
  428. try {
  429. int cnt;
  430. final byte[] buf = new byte[Block.SZ];
  431. while ((cnt = in.read(buf)) >= 0) {
  432. os.write(buf, 0, cnt);
  433. pm.update(cnt / 1024);
  434. }
  435. } finally {
  436. in.close();
  437. }
  438. }
  439. @Override
  440. public InputStream openInputStream() throws IOException {
  441. if (onDiskFile == null)
  442. return super.openInputStream();
  443. return new FileInputStream(onDiskFile);
  444. }
  445. @Override
  446. public void destroy() {
  447. super.destroy();
  448. if (onDiskFile != null) {
  449. try {
  450. if (!onDiskFile.delete())
  451. onDiskFile.deleteOnExit();
  452. } finally {
  453. onDiskFile = null;
  454. }
  455. }
  456. }
  457. }
  458. /**
  459. * A temporary buffer that will never exceed its in-memory limit.
  460. * <p>
  461. * If the in-memory limit is reached an IOException is thrown, rather than
  462. * attempting to spool to local disk.
  463. */
  464. public static class Heap extends TemporaryBuffer {
  465. /**
  466. * Create a new heap buffer with a maximum storage limit.
  467. *
  468. * @param limit
  469. * maximum number of bytes that can be stored in this buffer;
  470. * also used as the estimated size. Storing beyond this many
  471. * will cause an IOException to be thrown during write.
  472. */
  473. public Heap(final int limit) {
  474. super(limit);
  475. }
  476. /**
  477. * Create a new heap buffer with a maximum storage limit.
  478. *
  479. * @param estimatedSize
  480. * estimated size of storage used, to size the initial list of
  481. * block pointers.
  482. * @param limit
  483. * maximum number of bytes that can be stored in this buffer.
  484. * Storing beyond this many will cause an IOException to be
  485. * thrown during write.
  486. * @since 4.0
  487. */
  488. public Heap(final int estimatedSize, final int limit) {
  489. super(estimatedSize, limit);
  490. }
  491. @Override
  492. protected OutputStream overflow() throws IOException {
  493. throw new IOException(JGitText.get().inMemoryBufferLimitExceeded);
  494. }
  495. }
  496. static class Block {
  497. static final int SZ = 8 * 1024;
  498. final byte[] buffer;
  499. int count;
  500. Block() {
  501. buffer = new byte[SZ];
  502. }
  503. Block(int sz) {
  504. buffer = new byte[sz];
  505. }
  506. boolean isFull() {
  507. return count == buffer.length;
  508. }
  509. }
  510. private class BlockInputStream extends InputStream {
  511. private byte[] singleByteBuffer;
  512. private int blockIndex;
  513. private Block block;
  514. private int blockPos;
  515. BlockInputStream() {
  516. block = blocks.get(blockIndex);
  517. }
  518. @Override
  519. public int read() throws IOException {
  520. if (singleByteBuffer == null)
  521. singleByteBuffer = new byte[1];
  522. int n = read(singleByteBuffer);
  523. return n == 1 ? singleByteBuffer[0] & 0xff : -1;
  524. }
  525. @Override
  526. public long skip(long cnt) throws IOException {
  527. long skipped = 0;
  528. while (0 < cnt) {
  529. int n = (int) Math.min(block.count - blockPos, cnt);
  530. if (0 < n) {
  531. blockPos += n;
  532. skipped += n;
  533. cnt -= n;
  534. } else if (nextBlock())
  535. continue;
  536. else
  537. break;
  538. }
  539. return skipped;
  540. }
  541. @Override
  542. public int read(byte[] b, int off, int len) throws IOException {
  543. if (len == 0)
  544. return 0;
  545. int copied = 0;
  546. while (0 < len) {
  547. int c = Math.min(block.count - blockPos, len);
  548. if (0 < c) {
  549. System.arraycopy(block.buffer, blockPos, b, off, c);
  550. blockPos += c;
  551. off += c;
  552. len -= c;
  553. copied += c;
  554. } else if (nextBlock())
  555. continue;
  556. else
  557. break;
  558. }
  559. return 0 < copied ? copied : -1;
  560. }
  561. private boolean nextBlock() {
  562. if (++blockIndex < blocks.size()) {
  563. block = blocks.get(blockIndex);
  564. blockPos = 0;
  565. return true;
  566. }
  567. return false;
  568. }
  569. }
  570. }