protected int deflate(int flush) throws IOException {
    deflater.setOutput(buffer, 0, buffer.length);
    int err = deflater.deflate(flush);
    switch(err) {
      case JZlib.Z_OK:
      case JZlib.Z_STREAM_END:
        break;
      case JZlib.Z_BUF_ERROR:
        if(deflater.avail_in<=0 && flush!=JZlib.Z_FINISH){
          // flush() without any data
          break;
        }
      default:
        throw new IOException("failed to deflate: error="+err+" avail_out="+deflater.avail_out);
    }
    int len = deflater.next_out_index;
    if (len > 0) {
      out.write(buffer, 0, len);
    }
    return err;
  }