package net.md_5.bungee.packet;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import net.md_5.mendax.datainput.DataInputPacketReader;

/**
 * A specialized input stream to parse packets using the Mojang packet
 * definitions and then return them as a byte array.
 */
public class PacketInputStream implements AutoCloseable
{

    private final DataInputStream dataInput;
    private final TrackingInputStream tracker;

    public PacketInputStream(InputStream in)
    {
        tracker = new TrackingInputStream(in);
        dataInput = new DataInputStream(tracker);
    }

    /**
     * Read an entire packet from the stream and return it as a byte array.
     *
     * @return the read packet
     * @throws IOException when the underlying input stream throws an exception
     */
    public byte[] readPacket() throws IOException
    {
        tracker.out.reset();
        DataInputPacketReader.readPacket(dataInput);
        return tracker.out.toByteArray();
    }

    @Override
    public void close() throws Exception
    {
        dataInput.close();
    }

    /**
     * Input stream which will wrap another stream and copy all bytes read to a
     * {@link ByteArrayOutputStream}.
     */
    private class TrackingInputStream extends InputStream
    {

        private final ByteArrayOutputStream out = new ByteArrayOutputStream();
        private final InputStream wrapped;

        public TrackingInputStream(InputStream wrapped)
        {
            this.wrapped = wrapped;
        }

        @Override
        public int read() throws IOException
        {
            int ret = wrapped.read();
            out.write(ret);
            return ret;
        }
    }
}

@@ -88,32 +88,66 @@
 ataInputStream;%0A
+import java.io.FilterInputStream;%0A
 import java.io.I
@@ -241,16 +241,69 @@
 tReader;
+%0Aimport org.bouncycastle.crypto.io.CipherInputStream;
 %0A%0A/**%0A *
@@ -578,16 +578,69 @@
 tracker;
+%0A    private final byte%5B%5D buffer = new byte%5B1 %3C%3C 18%5D;
 %0A%0A    pu
@@ -1133,16 +1133,24 @@
 ataInput
+, buffer
 );%0A     
@@ -1468,16 +1468,22 @@
 extends 
+Filter
 InputStr
@@ -1568,24 +1568,25 @@
 utStream();%0A
+%0A
         priv
@@ -1586,143 +1586,250 @@
    p
-rivate final InputStream wrapped;%0A%0A        public TrackingInputStream(InputStream wrapped)%0A        %7B%0A            this.wrapped = wrapped
+ublic TrackingInputStream(InputStream in)%0A        %7B%0A            super(in);%0A        %7D%0A%0A        @Override%0A        public int read() throws IOException%0A        %7B%0A            int ret = in.read();%0A            out.write(ret);%0A            return ret
 ;%0A  
@@ -1871,32 +1871,58 @@
 public int read(
+byte%5B%5D b, int off, int len
 ) throws IOExcep
@@ -1962,21 +1962,27 @@
 t = 
-wrapped.read(
+in.read(b, off, len
 );%0A 
@@ -1994,32 +1994,40 @@
       out.write(
+b, off, 
 ret);%0A          

Use more ram to reduce CPU.