public synchronized int fillFrom(ByteChannel channel) throws IOException {
    if (buffer == null) {
      buffer = bufferFactory.newBuffer();
    }

    return channel.read(buffer);
  }
  public synchronized ByteBuffer dequeueBytes(int count) {
    if ((buffer == null) || (buffer.position() == 0) || (count == 0)) {
      return emptyBuffer;
    }

    int size = Math.min(count, buffer.position());

    ByteBuffer result = ByteBuffer.allocate(size);

    buffer.flip();

    // TODO: Validate this
    //			result.put (buffer.array(), 0, size);
    //			buffer.position (size);
    //			result.position (size);

    // TODO: this if() should be replaceable by the above
    if (buffer.remaining() <= result.remaining()) {
      result.put(buffer);
    } else {
      while (result.hasRemaining()) {
        result.put(buffer.get());
      }
    }

    if (buffer.remaining() == 0) {
      bufferFactory.returnBuffer(buffer);
      buffer = null;
    } else {
      buffer.compact();
    }

    result.flip();

    return (result);
  }