Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

TemporaryBuffer.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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. /**
  57. * A fully buffered output stream.
  58. * <p>
  59. * Subclasses determine the behavior when the in-memory buffer capacity has been
  60. * exceeded and additional bytes are still being received for output.
  61. */
  62. public abstract class TemporaryBuffer extends OutputStream {
  63. /** Default limit for in-core storage. */
  64. protected static final int DEFAULT_IN_CORE_LIMIT = 1024 * 1024;
  65. /** Chain of data, if we are still completely in-core; otherwise null. */
  66. ArrayList<Block> blocks;
  67. /**
  68. * Maximum number of bytes we will permit storing in memory.
  69. * <p>
  70. * When this limit is reached the data will be shifted to a file on disk,
  71. * preventing the JVM heap from growing out of control.
  72. */
  73. private int inCoreLimit;
  74. /** Initial size of block list. */
  75. private int initialBlocks;
  76. /** If {@link #inCoreLimit} has been reached, remainder goes here. */
  77. private OutputStream overflow;
  78. /**
  79. * Create a new empty temporary buffer.
  80. *
  81. * @param limit
  82. * maximum number of bytes to store in memory before entering the
  83. * overflow output path; also used as the estimated size.
  84. */
  85. protected TemporaryBuffer(int limit) {
  86. this(limit, limit);
  87. }
  88. /**
  89. * Create a new empty temporary buffer.
  90. *
  91. * @param estimatedSize
  92. * estimated size of storage used, to size the initial list of
  93. * block pointers.
  94. * @param limit
  95. * maximum number of bytes to store in memory before entering the
  96. * overflow output path.
  97. * @since 4.0
  98. */
  99. protected TemporaryBuffer(int estimatedSize, int limit) {
  100. if (estimatedSize > limit)
  101. throw new IllegalArgumentException();
  102. this.inCoreLimit = limit;
  103. this.initialBlocks = (estimatedSize - 1) / Block.SZ + 1;
  104. reset();
  105. }
  106. /** {@inheritDoc} */
  107. @Override
  108. public void write(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. /** {@inheritDoc} */
  125. @Override
  126. public void write(byte[] b, int off, int len) throws IOException {
  127. if (overflow == null) {
  128. while (len > 0) {
  129. Block s = last();
  130. if (s.isFull()) {
  131. if (reachedInCoreLimit())
  132. break;
  133. s = new Block();
  134. blocks.add(s);
  135. }
  136. final int n = Math.min(s.buffer.length - s.count, len);
  137. System.arraycopy(b, off, s.buffer, s.count, n);
  138. s.count += n;
  139. len -= n;
  140. off += n;
  141. }
  142. }
  143. if (len > 0)
  144. overflow.write(b, off, len);
  145. }
  146. /**
  147. * Dumps the entire buffer into the overflow stream, and flushes it.
  148. *
  149. * @throws java.io.IOException
  150. * the overflow stream cannot be started, or the buffer contents
  151. * cannot be written to it, or it failed to flush.
  152. */
  153. protected void doFlush() throws IOException {
  154. if (overflow == null)
  155. switchToOverflow();
  156. overflow.flush();
  157. }
  158. /**
  159. * Copy all bytes remaining on the input stream into this buffer.
  160. *
  161. * @param in
  162. * the stream to read from, until EOF is reached.
  163. * @throws java.io.IOException
  164. * an error occurred reading from the input stream, or while
  165. * writing to a local temporary file.
  166. */
  167. public void copy(InputStream in) throws IOException {
  168. if (blocks != null) {
  169. for (;;) {
  170. Block s = last();
  171. if (s.isFull()) {
  172. if (reachedInCoreLimit())
  173. break;
  174. s = new Block();
  175. blocks.add(s);
  176. }
  177. int n = in.read(s.buffer, s.count, s.buffer.length - s.count);
  178. if (n < 1)
  179. return;
  180. s.count += n;
  181. }
  182. }
  183. final byte[] tmp = new byte[Block.SZ];
  184. int n;
  185. while ((n = in.read(tmp)) > 0)
  186. overflow.write(tmp, 0, n);
  187. }
  188. /**
  189. * Obtain the length (in bytes) of the buffer.
  190. * <p>
  191. * The length is only accurate after {@link #close()} has been invoked.
  192. *
  193. * @return total length of the buffer, in bytes.
  194. */
  195. public long length() {
  196. return inCoreLength();
  197. }
  198. private long inCoreLength() {
  199. final Block last = last();
  200. return ((long) blocks.size() - 1) * Block.SZ + last.count;
  201. }
  202. /**
  203. * Convert this buffer's contents into a contiguous byte array.
  204. * <p>
  205. * The buffer is only complete after {@link #close()} has been invoked.
  206. *
  207. * @return the complete byte array; length matches {@link #length()}.
  208. * @throws java.io.IOException
  209. * an error occurred reading from a local temporary file
  210. */
  211. public byte[] toByteArray() throws IOException {
  212. final long len = length();
  213. if (Integer.MAX_VALUE < len)
  214. throw new OutOfMemoryError(JGitText.get().lengthExceedsMaximumArraySize);
  215. final byte[] out = new byte[(int) len];
  216. int outPtr = 0;
  217. for (Block b : blocks) {
  218. System.arraycopy(b.buffer, 0, out, outPtr, b.count);
  219. outPtr += b.count;
  220. }
  221. return out;
  222. }
  223. /**
  224. * Convert this buffer's contents into a contiguous byte array. If this size
  225. * of the buffer exceeds the limit only return the first {@code limit} bytes
  226. * <p>
  227. * The buffer is only complete after {@link #close()} has been invoked.
  228. *
  229. * @param limit
  230. * the maximum number of bytes to be returned
  231. * @return the byte array limited to {@code limit} bytes.
  232. * @throws java.io.IOException
  233. * an error occurred reading from a local temporary file
  234. * @since 4.2
  235. */
  236. public byte[] toByteArray(int limit) throws IOException {
  237. final long len = Math.min(length(), limit);
  238. if (Integer.MAX_VALUE < len)
  239. throw new OutOfMemoryError(
  240. JGitText.get().lengthExceedsMaximumArraySize);
  241. final byte[] out = new byte[(int) len];
  242. int outPtr = 0;
  243. for (Block b : blocks) {
  244. System.arraycopy(b.buffer, 0, out, outPtr, b.count);
  245. outPtr += b.count;
  246. }
  247. return out;
  248. }
  249. /**
  250. * Send this buffer to an output stream.
  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. * @param os
  256. * stream to send this buffer's complete content to.
  257. * @param pm
  258. * if not null progress updates are sent here. Caller should
  259. * initialize the task and the number of work units to <code>
  260. * {@link #length()}/1024</code>.
  261. * @throws java.io.IOException
  262. * an error occurred reading from a temporary file on the local
  263. * system, or writing to the output stream.
  264. */
  265. public void writeTo(OutputStream os, ProgressMonitor pm)
  266. throws IOException {
  267. if (pm == null)
  268. pm = NullProgressMonitor.INSTANCE;
  269. for (Block b : blocks) {
  270. os.write(b.buffer, 0, b.count);
  271. pm.update(b.count / 1024);
  272. }
  273. }
  274. /**
  275. * Open an input stream to read from the buffered data.
  276. * <p>
  277. * This method may only be invoked after {@link #close()} has completed
  278. * normally, to ensure all data is completely transferred.
  279. *
  280. * @return a stream to read from the buffer. The caller must close the
  281. * stream when it is no longer useful.
  282. * @throws java.io.IOException
  283. * an error occurred opening the temporary file.
  284. */
  285. public InputStream openInputStream() throws IOException {
  286. return new BlockInputStream();
  287. }
  288. /**
  289. * Same as {@link #openInputStream()} but handling destruction of any
  290. * associated resources automatically when closing the returned stream.
  291. *
  292. * @return an InputStream which will automatically destroy any associated
  293. * temporary file on {@link #close()}
  294. * @throws IOException
  295. * in case of an error.
  296. * @since 4.11
  297. */
  298. public InputStream openInputStreamWithAutoDestroy() throws IOException {
  299. return new BlockInputStream() {
  300. @Override
  301. public void close() throws IOException {
  302. super.close();
  303. destroy();
  304. }
  305. };
  306. }
  307. /**
  308. * Reset this buffer for reuse, purging all buffered content.
  309. */
  310. public void reset() {
  311. if (overflow != null) {
  312. destroy();
  313. }
  314. if (blocks != null)
  315. blocks.clear();
  316. else
  317. blocks = new ArrayList<>(initialBlocks);
  318. blocks.add(new Block(Math.min(inCoreLimit, Block.SZ)));
  319. }
  320. /**
  321. * Open the overflow output stream, so the remaining output can be stored.
  322. *
  323. * @return the output stream to receive the buffered content, followed by
  324. * the remaining output.
  325. * @throws java.io.IOException
  326. * the buffer cannot create the overflow stream.
  327. */
  328. protected abstract OutputStream overflow() throws IOException;
  329. private Block last() {
  330. return blocks.get(blocks.size() - 1);
  331. }
  332. private boolean reachedInCoreLimit() throws IOException {
  333. if (inCoreLength() < inCoreLimit)
  334. return false;
  335. switchToOverflow();
  336. return true;
  337. }
  338. private void switchToOverflow() throws IOException {
  339. overflow = overflow();
  340. final Block last = blocks.remove(blocks.size() - 1);
  341. for (Block b : blocks)
  342. overflow.write(b.buffer, 0, b.count);
  343. blocks = null;
  344. overflow = new BufferedOutputStream(overflow, Block.SZ);
  345. overflow.write(last.buffer, 0, last.count);
  346. }
  347. /** {@inheritDoc} */
  348. @Override
  349. public void close() throws IOException {
  350. if (overflow != null) {
  351. try {
  352. overflow.close();
  353. } finally {
  354. overflow = null;
  355. }
  356. }
  357. }
  358. /**
  359. * Clear this buffer so it has no data, and cannot be used again.
  360. */
  361. public void destroy() {
  362. blocks = null;
  363. if (overflow != null) {
  364. try {
  365. overflow.close();
  366. } catch (IOException err) {
  367. // We shouldn't encounter an error closing the file.
  368. } finally {
  369. overflow = null;
  370. }
  371. }
  372. }
  373. /**
  374. * A fully buffered output stream using local disk storage for large data.
  375. * <p>
  376. * Initially this output stream buffers to memory and is therefore similar
  377. * to ByteArrayOutputStream, but it shifts to using an on disk temporary
  378. * file if the output gets too large.
  379. * <p>
  380. * The content of this buffered stream may be sent to another OutputStream
  381. * only after this stream has been properly closed by {@link #close()}.
  382. */
  383. public static class LocalFile extends TemporaryBuffer {
  384. /** Directory to store the temporary file under. */
  385. private final File directory;
  386. /**
  387. * Location of our temporary file if we are on disk; otherwise null.
  388. * <p>
  389. * If we exceeded the {@link #inCoreLimit} we nulled out {@link #blocks}
  390. * and created this file instead. All output goes here through
  391. * {@link #overflow}.
  392. */
  393. private File onDiskFile;
  394. /**
  395. * Create a new temporary buffer, limiting memory usage.
  396. *
  397. * @param directory
  398. * if the buffer has to spill over into a temporary file, the
  399. * directory where the file should be saved. If null the
  400. * system default temporary directory (for example /tmp) will
  401. * be used instead.
  402. */
  403. public LocalFile(File directory) {
  404. this(directory, DEFAULT_IN_CORE_LIMIT);
  405. }
  406. /**
  407. * Create a new temporary buffer, limiting memory usage.
  408. *
  409. * @param directory
  410. * if the buffer has to spill over into a temporary file, the
  411. * directory where the file should be saved. If null the
  412. * system default temporary directory (for example /tmp) will
  413. * be used instead.
  414. * @param inCoreLimit
  415. * maximum number of bytes to store in memory. Storage beyond
  416. * this limit will use the local file.
  417. */
  418. public LocalFile(File directory, int inCoreLimit) {
  419. super(inCoreLimit);
  420. this.directory = directory;
  421. }
  422. @Override
  423. protected OutputStream overflow() throws IOException {
  424. onDiskFile = File.createTempFile("jgit_", ".buf", directory); //$NON-NLS-1$ //$NON-NLS-2$
  425. return new BufferedOutputStream(new FileOutputStream(onDiskFile));
  426. }
  427. @Override
  428. public long length() {
  429. if (onDiskFile == null) {
  430. return super.length();
  431. }
  432. return onDiskFile.length();
  433. }
  434. @Override
  435. public byte[] toByteArray() throws IOException {
  436. if (onDiskFile == null) {
  437. return super.toByteArray();
  438. }
  439. final long len = length();
  440. if (Integer.MAX_VALUE < len)
  441. throw new OutOfMemoryError(JGitText.get().lengthExceedsMaximumArraySize);
  442. final byte[] out = new byte[(int) len];
  443. try (FileInputStream in = new FileInputStream(onDiskFile)) {
  444. IO.readFully(in, out, 0, (int) len);
  445. }
  446. return out;
  447. }
  448. @Override
  449. public void writeTo(OutputStream os, ProgressMonitor pm)
  450. throws IOException {
  451. if (onDiskFile == null) {
  452. super.writeTo(os, pm);
  453. return;
  454. }
  455. if (pm == null)
  456. pm = NullProgressMonitor.INSTANCE;
  457. try (FileInputStream in = new FileInputStream(onDiskFile)) {
  458. int cnt;
  459. final byte[] buf = new byte[Block.SZ];
  460. while ((cnt = in.read(buf)) >= 0) {
  461. os.write(buf, 0, cnt);
  462. pm.update(cnt / 1024);
  463. }
  464. }
  465. }
  466. @Override
  467. public InputStream openInputStream() throws IOException {
  468. if (onDiskFile == null)
  469. return super.openInputStream();
  470. return new FileInputStream(onDiskFile);
  471. }
  472. @Override
  473. public InputStream openInputStreamWithAutoDestroy() throws IOException {
  474. if (onDiskFile == null) {
  475. return super.openInputStreamWithAutoDestroy();
  476. }
  477. return new FileInputStream(onDiskFile) {
  478. @Override
  479. public void close() throws IOException {
  480. super.close();
  481. destroy();
  482. }
  483. };
  484. }
  485. @Override
  486. public void destroy() {
  487. super.destroy();
  488. if (onDiskFile != null) {
  489. try {
  490. if (!onDiskFile.delete())
  491. onDiskFile.deleteOnExit();
  492. } finally {
  493. onDiskFile = null;
  494. }
  495. }
  496. }
  497. }
  498. /**
  499. * A temporary buffer that will never exceed its in-memory limit.
  500. * <p>
  501. * If the in-memory limit is reached an IOException is thrown, rather than
  502. * attempting to spool to local disk.
  503. */
  504. public static class Heap extends TemporaryBuffer {
  505. /**
  506. * Create a new heap buffer with a maximum storage limit.
  507. *
  508. * @param limit
  509. * maximum number of bytes that can be stored in this buffer;
  510. * also used as the estimated size. Storing beyond this many
  511. * will cause an IOException to be thrown during write.
  512. */
  513. public Heap(int limit) {
  514. super(limit);
  515. }
  516. /**
  517. * Create a new heap buffer with a maximum storage limit.
  518. *
  519. * @param estimatedSize
  520. * estimated size of storage used, to size the initial list of
  521. * block pointers.
  522. * @param limit
  523. * maximum number of bytes that can be stored in this buffer.
  524. * Storing beyond this many will cause an IOException to be
  525. * thrown during write.
  526. * @since 4.0
  527. */
  528. public Heap(int estimatedSize, int limit) {
  529. super(estimatedSize, limit);
  530. }
  531. @Override
  532. protected OutputStream overflow() throws IOException {
  533. throw new IOException(JGitText.get().inMemoryBufferLimitExceeded);
  534. }
  535. }
  536. static class Block {
  537. static final int SZ = 8 * 1024;
  538. final byte[] buffer;
  539. int count;
  540. Block() {
  541. buffer = new byte[SZ];
  542. }
  543. Block(int sz) {
  544. buffer = new byte[sz];
  545. }
  546. boolean isFull() {
  547. return count == buffer.length;
  548. }
  549. }
  550. private class BlockInputStream extends InputStream {
  551. private byte[] singleByteBuffer;
  552. private int blockIndex;
  553. private Block block;
  554. private int blockPos;
  555. BlockInputStream() {
  556. block = blocks.get(blockIndex);
  557. }
  558. @Override
  559. public int read() throws IOException {
  560. if (singleByteBuffer == null)
  561. singleByteBuffer = new byte[1];
  562. int n = read(singleByteBuffer);
  563. return n == 1 ? singleByteBuffer[0] & 0xff : -1;
  564. }
  565. @Override
  566. public long skip(long cnt) throws IOException {
  567. long skipped = 0;
  568. while (0 < cnt) {
  569. int n = (int) Math.min(block.count - blockPos, cnt);
  570. if (0 < n) {
  571. blockPos += n;
  572. skipped += n;
  573. cnt -= n;
  574. } else if (nextBlock())
  575. continue;
  576. else
  577. break;
  578. }
  579. return skipped;
  580. }
  581. @Override
  582. public int read(byte[] b, int off, int len) throws IOException {
  583. if (len == 0)
  584. return 0;
  585. int copied = 0;
  586. while (0 < len) {
  587. int c = Math.min(block.count - blockPos, len);
  588. if (0 < c) {
  589. System.arraycopy(block.buffer, blockPos, b, off, c);
  590. blockPos += c;
  591. off += c;
  592. len -= c;
  593. copied += c;
  594. } else if (nextBlock())
  595. continue;
  596. else
  597. break;
  598. }
  599. return 0 < copied ? copied : -1;
  600. }
  601. private boolean nextBlock() {
  602. if (++blockIndex < blocks.size()) {
  603. block = blocks.get(blockIndex);
  604. blockPos = 0;
  605. return true;
  606. }
  607. return false;
  608. }
  609. }
  610. }