選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

FastByteArrayOutputStream.java 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package com.vaadin.sass.util;
  2. import java.io.InputStream;
  3. import java.io.OutputStream;
  4. /**
  5. * ByteArrayOutputStream implementation that doesn't synchronize methods and
  6. * doesn't copy the data on toByteArray().
  7. */
  8. public class FastByteArrayOutputStream extends OutputStream {
  9. /**
  10. * Buffer and size
  11. */
  12. protected byte[] buf = null;
  13. protected int size = 0;
  14. /**
  15. * Constructs a stream with buffer capacity size 5K
  16. */
  17. public FastByteArrayOutputStream() {
  18. this(5 * 1024);
  19. }
  20. /**
  21. * Constructs a stream with the given initial size
  22. */
  23. public FastByteArrayOutputStream(int initSize) {
  24. size = 0;
  25. buf = new byte[initSize];
  26. }
  27. /**
  28. * Ensures that we have a large enough buffer for the given size.
  29. */
  30. private void verifyBufferSize(int sz) {
  31. if (sz > buf.length) {
  32. byte[] old = buf;
  33. buf = new byte[Math.max(sz, 2 * buf.length)];
  34. System.arraycopy(old, 0, buf, 0, old.length);
  35. old = null;
  36. }
  37. }
  38. public int getSize() {
  39. return size;
  40. }
  41. /**
  42. * Returns the byte array containing the written data. Note that this array
  43. * will almost always be larger than the amount of data actually written.
  44. */
  45. public byte[] getByteArray() {
  46. return buf;
  47. }
  48. @Override
  49. public final void write(byte b[]) {
  50. verifyBufferSize(size + b.length);
  51. System.arraycopy(b, 0, buf, size, b.length);
  52. size += b.length;
  53. }
  54. @Override
  55. public final void write(byte b[], int off, int len) {
  56. verifyBufferSize(size + len);
  57. System.arraycopy(b, off, buf, size, len);
  58. size += len;
  59. }
  60. @Override
  61. public final void write(int b) {
  62. verifyBufferSize(size + 1);
  63. buf[size++] = (byte) b;
  64. }
  65. public void reset() {
  66. size = 0;
  67. }
  68. /**
  69. * Returns a ByteArrayInputStream for reading back the written data
  70. */
  71. public InputStream getInputStream() {
  72. return new FastByteArrayInputStream(buf, size);
  73. }
  74. }