package pers.zlf.fhsp;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import pers.zlf.fhsp.config.Configuration;
import pers.zlf.fhsp.splitter.ChunkSizeEmitter;
import pers.zlf.fhsp.splitter.DoubleChunkSizeEmitter;

@ChannelHandler.Sharable
public class ByteBufSplitter extends MessageToMessageDecoder<ByteBuf> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ByteBufSplitter.class);
    private static final ByteBufSplitter INSTANCE = new ByteBufSplitter();

    private ChunkSizeEmitter splitter;

    private ByteBufSplitter() {
        try {
            this.splitter = (ChunkSizeEmitter) Class.forName(Configuration.splitter())
                                                    .newInstance();
        } catch (Throwable t) {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("Failed to create instance of {}, using default splitter {}",
                            Configuration.splitter(),
                            DoubleChunkSizeEmitter.class.getSimpleName());
            }
            this.splitter = new DoubleChunkSizeEmitter();
        }
    }

    public static ByteBufSplitter getInstance() {
        return INSTANCE;
    }

    @Override
    protected void decode(
            ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        int size = 1;
        ByteBufAllocator allocator = ctx.alloc();

        for (;;) {
            if (size >= msg.readableBytes()) {
                out.add(msg.retain());
                break;
            } else {
                ByteBuf buf = allocator.buffer(size);
                buf.writeBytes(msg, size);
                out.add(buf);
                size = splitter.nextChunkSize(size, msg.readableBytes());
            }
        }
    }
}

@@ -135,49 +135,8 @@
 uf;%0A
-import io.netty.buffer.ByteBufAllocator;%0A
 impo
@@ -1532,66 +1532,69 @@
 int 
-size = 1;%0A        ByteBufAllocator allocator = ctx.alloc()
+chunkSize = 2;%0A        int written = 0;%0A        ByteBuf chunk
 ;%0A%0A 
@@ -1627,17 +1627,22 @@
     if (
-s
+chunkS
 ize %3E= m
@@ -1766,43 +1766,118 @@
     
-ByteBuf buf = allocator.buffer(size
+written += chunkSize;%0A                chunk = msg.retainedDuplicate();%0A                msg.readerIndex(written
 );%0A 
@@ -1895,32 +1895,33 @@
     
-buf
+chunk
 .write
-Bytes(msg, size
+rIndex(written
 );%0A 
@@ -1943,19 +1943,21 @@
 out.add(
-buf
+chunk
 );%0A     
@@ -1967,17 +1967,22 @@
         
-s
+chunkS
 ize = sp
@@ -2002,17 +2002,22 @@
 unkSize(
-s
+chunkS
 ize, msg

Resolve #1