package org.tshlabs.baja.protocol;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Objects;

/**
 *
 * This class is thread safe.
 */
public class RespEncoder {

    private final Charset payloadCharset;

    public RespEncoder(Charset payloadCharset) {
        this.payloadCharset = Objects.requireNonNull(payloadCharset);
    }

    public byte[] encode(List<String> args) {
        Objects.requireNonNull(args);
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        quietWrite(out, getArrayPreamble(args));

        for (String arg : args) {
            quietWrite(out, getArgPreamble(arg));
            quietWrite(out, arg.getBytes(payloadCharset));
            out.write('\r');
            out.write('\n');
        }

        return out.toByteArray();
    }

    private static void quietWrite(ByteArrayOutputStream stream, byte[] bytes) {
        try {
            stream.write(bytes);
        } catch (IOException e) {
            throw new IllegalStateException("" +
                    "IOException when writing to a an in-memory byte array. This " +
                    "should be impossible. Please ensure hell has not frozen over", e);
        }
    }

    // VisibleForTesting
    static byte[] getArrayPreamble(List<String> args) {
        return (RespType.ARRAY.getString() + args.size() +
                "\r\n").getBytes(RespEncodings.PROTOCOL);
    }

    // VisibleForTesting
    static byte[] getArgPreamble(String arg) {
        return (RespType.BULK_STRING.getString() + arg.length() +
                "\r\n").getBytes(RespEncodings.PROTOCOL);
    }
}

@@ -71,36 +71,8 @@
 am;%0A
-import java.io.IOException;%0A
 impo
@@ -158,11 +158,8 @@
 /**%0A
- *%0A
  * T
@@ -544,34 +544,37 @@
 ();%0A        
-quietWrite
+writeToStream
 (out, getArr
@@ -635,34 +635,37 @@
             
-quietWrite
+writeToStream
 (out, getArg
@@ -692,26 +692,29 @@
         
-quietWrite
+writeToStream
 (out, ar
@@ -880,18 +880,21 @@
 oid 
-quietWrite
+writeToStream
 (Byt
@@ -948,115 +948,223 @@
     
-try %7B%0A            stream.write(bytes);%0A        %7D catch (IOException e) %7B%0A            throw new IllegalState
+// Pass the offset and length here explicitly so that we're calling%0A        // the .write() method defined in ByteArrayOutputStream (instead of the%0A        // one defined in OutputStream) which doesn't include an IO
 Exce
@@ -1172,13 +1172,11 @@
 tion
-(%22%22 +
+ as
 %0A   
@@ -1184,182 +1184,174 @@
     
-            %22IOException when writing to a an in-memory byte array. This %22 +%0A                    %22should be impossible. Please ensure hell has not frozen over%22, e);%0A        %7D
+// part of its signature. This way we don't have to pretend to handle an%0A        // exception that will never be raised.%0A        stream.write(bytes, 0, bytes.length);
 %0A   

Use .write() of byte array that never raises an IOException