package org.opends.common;

import org.glassfish.grizzly.streams.StreamWriter;

import java.io.OutputStream;
import java.io.IOException;

public class StreamWriterOutputStream extends OutputStream
{
  private StreamWriter streamWriter;

  public StreamWriterOutputStream(StreamWriter streamWriter)
  {
    this.streamWriter = streamWriter;
    this.streamWriter.setBlocking(true);
  }

  public void write(int i) throws IOException {
    streamWriter.writeByte((byte)i);
  }

  @Override
  public void write(byte[] bytes) throws IOException {
    streamWriter.writeByteArray(bytes);
  }

  @Override
  public void write(byte[] bytes, int i, int i1) throws IOException {
    byte[] bytesToWrite;
    if(i > 0 || i1 < bytes.length)
    {
      bytesToWrite = new byte[i1];
      System.arraycopy(bytes, i, bytesToWrite, 0, i1);
    }
    else
    {
      bytesToWrite = bytes;
    }

    streamWriter.writeByteArray(bytesToWrite);
  }

  @Override
  public void flush() throws IOException {
    streamWriter.flush();
  }
}