class LogFileHandler extends Handler {

    public void writeEscapedBytes(byte[] bytes) throws IOException {
        int magic = 0;
        for (byte b : bytes)
            if (b == MAGIC_BYTE || b == MAGIC_BYTE + 1)
                magic++;

        byte eBytes[] = new byte[bytes.length + magic];

        int i = 0;
        for (byte b : bytes) {
            if (b == MAGIC_BYTE || b == MAGIC_BYTE + 1) {
                eBytes[i++] = MAGIC_BYTE + 1;
                eBytes[i++] = (byte) (b - MAGIC_BYTE);
            } else {
                eBytes[i++] = b;
            }
        }

        byte[] lenBytes = ByteBuffer.allocate(4).putInt(bytes.length).array();
        synchronized (mLogFile) {
            mLogFile.write(MAGIC_BYTE);
            mLogFile.write(lenBytes);
            mLogFile.write(eBytes);
        }
    }

}

class TestLogFileHandler {

     byte[] testUnescaped;
     byte[] expectedEscaped;
    private TestingLogFileHandler lfh;

    @Test
    public void testWriteByteArray() throws IOException {


        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        lfh.setLogFile(byteArrayOutputStream);

        lfh.writeEscapedBytes(testUnescaped);

        byte[] result = byteArrayOutputStream.toByteArray();
        Assert.assertTrue(Arrays.equals(expectedEscaped, result));
    }

}