// 
// Decompiled by Procyon v0.6.0
// 

package io.netty.handler.codec;

import io.netty.util.CharsetUtil;
import io.netty.buffer.ByteBufUtil;
import io.netty.util.AsciiString;
import java.util.Map;
import io.netty.util.internal.ObjectUtil;
import io.netty.buffer.ByteBuf;

public final class AsciiHeadersEncoder
{
    private final ByteBuf buf;
    private final SeparatorType separatorType;
    private final NewlineType newlineType;
    
    public AsciiHeadersEncoder(final ByteBuf buf) {
        this(buf, SeparatorType.COLON_SPACE, NewlineType.CRLF);
    }
    
    public AsciiHeadersEncoder(final ByteBuf buf, final SeparatorType separatorType, final NewlineType newlineType) {
        this.buf = ObjectUtil.checkNotNull(buf, "buf");
        this.separatorType = ObjectUtil.checkNotNull(separatorType, "separatorType");
        this.newlineType = ObjectUtil.checkNotNull(newlineType, "newlineType");
    }
    
    public void encode(final Map.Entry<CharSequence, CharSequence> entry) {
        final CharSequence name = entry.getKey();
        final CharSequence value = entry.getValue();
        final ByteBuf buf = this.buf;
        final int nameLen = name.length();
        final int valueLen = value.length();
        final int entryLen = nameLen + valueLen + 4;
        int offset = buf.writerIndex();
        buf.ensureWritable(entryLen);
        writeAscii(buf, offset, name);
        offset += nameLen;
        switch (this.separatorType) {
            case COLON: {
                buf.setByte(offset++, 58);
                break;
            }
            case COLON_SPACE: {
                buf.setByte(offset++, 58);
                buf.setByte(offset++, 32);
                break;
            }
            default: {
                throw new Error("Unexpected separator type: " + this.separatorType);
            }
        }
        writeAscii(buf, offset, value);
        offset += valueLen;
        switch (this.newlineType) {
            case LF: {
                buf.setByte(offset++, 10);
                break;
            }
            case CRLF: {
                buf.setByte(offset++, 13);
                buf.setByte(offset++, 10);
                break;
            }
            default: {
                throw new Error("Unexpected newline type: " + this.newlineType);
            }
        }
        buf.writerIndex(offset);
    }
    
    private static void writeAscii(final ByteBuf buf, final int offset, final CharSequence value) {
        if (value instanceof AsciiString) {
            ByteBufUtil.copy((AsciiString)value, 0, buf, offset, value.length());
        }
        else {
            buf.setCharSequence(offset, value, CharsetUtil.US_ASCII);
        }
    }
    
    public enum SeparatorType
    {
        COLON, 
        COLON_SPACE;
    }
    
    public enum NewlineType
    {
        LF, 
        CRLF;
    }
}
