[e-lang] Joe-E ByteArray API for working with streams

Tyler Close tyler.close at gmail.com
Sat Sep 22 08:58:06 EDT 2007


Hi Adrian,

I'd like to add a couple new members to the ByteArray class to make it
easier to work with streams. In particular, the method:

    /**
      * Views this array as an input stream.
      */
    public InputStream open() { return new ByteArrayInputStream(bytes); }

and the inner class:

    /**
     * A {@link ByteArray} factory.
     */
    static public final class
    Generator extends OutputStream {

        private byte[] buffer;
        private int size;

        /**
         * Constructs an instance.
         * @param estimate  estimated array length
         */
        public
        Generator(int estimate) {
            buffer = new byte[0 == estimate ? 32 : estimate];
            size = 0;
        }

        // java.io.OutputStream interface

        public void
        write(final int b) {
            if (size == buffer.length) {
                System.arraycopy(buffer, 0, buffer = new byte[2*size], 0, size);
            }
            buffer[size++] = (byte)b;
        }

        public void
        write(final byte[] b, final int off, final int len) {
            if (size + len > buffer.length) {
                System.arraycopy(buffer,0, buffer = new byte[size+len],0, size);
            }
            System.arraycopy(b, off, buffer, size, len);
            size += len;
        }

        // org.joe_e.array.ByteArray.Generator interface

        /**
         * Creates a snapshot of the current content.
         */
        public ByteArray
        snapshot() {
            final byte[] r;
            if (size == buffer.length) {
                r = buffer;
            } else {
                r = new byte[size];
                System.arraycopy(buffer, 0, r, 0, size);
            }
            return new ByteArray(r);
        }
    }

The above needs to be an inner class to get access to the private
ByteArray constructor that enables construction without copying the
array.

Look alright?

--Tyler

-- 
The web-calculus is the union of REST and capability-based security:
http://www.waterken.com/dev/Web/

Name your trusted sites to distinguish them from phishing sites.
https://addons.mozilla.org/firefox/957/


More information about the e-lang mailing list