package com.paritytrading.nassau.binaryfile;

import static com.paritytrading.foundation.ByteBuffers.*;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.util.zip.GZIPOutputStream;

/**
 * An implementation of a BinaryFILE writer.
 */
public class BinaryFILEWriter implements Closeable {

    private WritableByteChannel channel;

    private ByteBuffer header;

    /**
     * Create a BinaryFILE writer.
     *
     * @param stream an output stream
     */
    public BinaryFILEWriter(OutputStream stream) {
        this(Channels.newChannel(stream));
    }

    /**
     * Create a BinaryFILE writer.
     *
     * @param channel an output channel
     */
    public BinaryFILEWriter(WritableByteChannel channel) {
        this.channel = channel;

        this.header = ByteBuffer.allocate(2);
    }

    /**
     * Open a BinaryFILE writer.
     *
     * @param file the output file
     * @return a BinaryFILE writer
     * @throws IOException if an I/O error occurs
     */
    public static BinaryFILEWriter open(File file) throws IOException {
        FileOutputStream stream = new FileOutputStream(file);

        if (file.getName().endsWith(".gz"))
            return new BinaryFILEWriter(new GZIPOutputStream(stream, 65536));
        else
            return new BinaryFILEWriter(stream.getChannel());
    }

    /**
     * Write a message.
     *
     * @param payload a buffer containing a message
     * @throws IOException if an I/O error occurs
     */
    public void write(ByteBuffer payload) throws IOException {
        header.clear();
        putUnsignedShort(header, payload.remaining());
        header.flip();

        // Unfortunately there is no way to get a GatheringByteChannel from a
        // GZIPOutputStream.

        do {
            channel.write(header);
        } while (header.hasRemaining());

        do {
            channel.write(payload);
        } while (payload.hasRemaining());
    }

    @Override
    public void close() throws IOException {
        channel.close();
    }

}

@@ -347,47 +347,8 @@
 nel;
-%0Aimport java.util.zip.GZIPOutputStream;
 %0A%0A/*
@@ -1281,147 +1281,8 @@
 );%0A%0A
-        if (file.getName().endsWith(%22.gz%22))%0A            return new BinaryFILEWriter(new GZIPOutputStream(stream, 65536));%0A        else%0A    
     
@@ -1661,116 +1661,8 @@
 );%0A%0A
-        // Unfortunately there is no way to get a GatheringByteChannel from a%0A        // GZIPOutputStream.%0A%0A
     

Remove GZIP support from BinaryFILE writer