[JGIT PATCH 1/5] Add toByteArray() to TemporaryBuffer

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



It can be more useful to convert a buffered output stream into
a single byte array, without paying the penalties associated
with ByteArrayOutputStream to do the same action.

Signed-off-by: Shawn O. Pearce <spearce@xxxxxxxxxxx>
---
 .../src/org/spearce/jgit/util/TemporaryBuffer.java |   34 ++++++++++++++++++++
 1 files changed, 34 insertions(+), 0 deletions(-)

diff --git a/org.spearce.jgit/src/org/spearce/jgit/util/TemporaryBuffer.java b/org.spearce.jgit/src/org/spearce/jgit/util/TemporaryBuffer.java
index d597c38..b1ffd6e 100644
--- a/org.spearce.jgit/src/org/spearce/jgit/util/TemporaryBuffer.java
+++ b/org.spearce.jgit/src/org/spearce/jgit/util/TemporaryBuffer.java
@@ -182,6 +182,40 @@ public long length() {
 	}
 
 	/**
+	 * Convert this buffer's contents into a contiguous byte array.
+	 * <p>
+	 * The buffer is only complete after {@link #close()} has been invoked.
+	 * 
+	 * @return the complete byte array; length matches {@link #length()}.
+	 * @throws IOException
+	 *             an error occurred reading from a local temporary file
+	 * @throws OutOfMemoryError
+	 *             the buffer cannot fit in memory
+	 */
+	public byte[] toByteArray() throws IOException {
+		final long len = length();
+		if (Integer.MAX_VALUE < len)
+			throw new OutOfMemoryError("Length exceeds maximum array size");
+
+		final byte[] out = new byte[(int) len];
+		if (blocks != null) {
+			int outPtr = 0;
+			for (final Block b : blocks) {
+				System.arraycopy(b.buffer, 0, out, outPtr, b.count);
+				outPtr += b.count;
+			}
+		} else {
+			final FileInputStream in = new FileInputStream(onDiskFile);
+			try {
+				NB.readFully(in, out, 0, (int) len);
+			} finally {
+				in.close();
+			}
+		}
+		return out;
+	}
+
+	/**
 	 * Send this buffer to an output stream.
 	 * <p>
 	 * This method may only be invoked after {@link #close()} has completed
-- 
1.6.1.rc2.299.gead4c

--
To unsubscribe from this list: send the line "unsubscribe git" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html

[Index of Archives]     [Linux Kernel Development]     [Gcc Help]     [IETF Annouce]     [DCCP]     [Netdev]     [Networking]     [Security]     [V4L]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux Security]     [Linux RAID]     [Linux SCSI]     [Fedora Users]

  Powered by Linux