01: /*
02: * ByteBuffer.java
03: *
04: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
05: *
06: * Copyright 2002-2008, Thomas Kellerer
07: * No part of this code maybe reused without the permission of the author
08: *
09: * To contact the author please send an email to: support@sql-workbench.net
10: *
11: */
12: package workbench.util;
13:
14: /**
15: * A dynamic byte[] array which gives direct access to the underlying
16: * byte[] array which is more efficient than ByteArrayOutputStream which
17: * copies the array when calling toByteArray() (thus doubling memory usage)
18: * It is not as efficient as it does not pre-allocate bytes (in order to
19: * be able to give direct access to the underlying array.
20: * {@link #getLength()} returns the physical length of the internal array
21: * and is equivalent to getBuffer().length;
22: */
23: public class ByteBuffer {
24: private byte[] byteData;
25:
26: public ByteBuffer() {
27: }
28:
29: /**
30: * Expand the storage size to 'minStorage' number of bytes.
31: */
32: private void ensureSize(int minStorage) {
33: int currentSize = (byteData == null ? 0 : byteData.length);
34:
35: if (minStorage < currentSize)
36: return;
37:
38: if (this .byteData == null) {
39: this .byteData = new byte[minStorage];
40: } else {
41: byte newBuf[] = new byte[minStorage];
42: System.arraycopy(this .byteData, 0, newBuf, 0,
43: byteData.length);
44: this .byteData = newBuf;
45: }
46: }
47:
48: /**
49: * Returns a reference to the internal buffer.
50: * May be null if append() has never been called.
51: */
52: public byte[] getBuffer() {
53: return this .byteData;
54: }
55:
56: public ByteBuffer append(byte[] buf) {
57: return append(buf, 0, buf.length);
58: }
59:
60: public ByteBuffer append(byte[] buf, int start, int len) {
61: if (len < 0)
62: return this ;
63: int pos = getLength();
64: int newlen = getLength() + len;
65: ensureSize(newlen);
66: System.arraycopy(buf, start, byteData, pos, len);
67: return this ;
68: }
69:
70: /**
71: * Returns the current length of this ByteBuffer.
72: * This is equivalent to getBuffer().length
73: */
74: public int getLength() {
75: if (this .byteData == null)
76: return 0;
77: return this.byteData.length;
78: }
79:
80: }
|