private int ensureBuffering(int size) throws IOException {
        if (size < bpos) {
            return bpos;
        }
        // refill the buffer as more buffering is requested than the current buffer status
        try {

            if (chunk.size() < buffer.length) {
            	while (reader.hasNext()) {
            		writer.add(reader.nextEvent());

            		// check if the chunk is full
            		final int csize = buffer.length - bpos;
            		if (chunk.size() > csize) {
            			System.arraycopy(chunk.getByteArray(), 0, buffer, bpos, csize);
            			bpos = buffer.length;
            			chunk.trim(csize, 0);
            			return buffer.length;
            		}
            	}
            }
            final int csize = chunk.size() < buffer.length - bpos ? chunk.size() : buffer.length - bpos; 
			if (csize > 0) {
				System.arraycopy(chunk.getByteArray(), 0, buffer, bpos, csize);
				bpos += csize;
				chunk.trim(csize, 0);
				return bpos;
			} else {
				return bpos > 0 ? bpos : -1;
			}
		} catch (XMLStreamException e) {
			throw new IOException(e);
		}
    }