@Override
        public LinkedBuffer writeByteArray(final byte[] value,
                final int offset, final int valueLen,
                final WriteSession session, LinkedBuffer lb) throws IOException
        {
            if (valueLen == 0)
                return lb;

            session.size += valueLen;

            final int available = lb.buffer.length - lb.offset;
            if (valueLen > available)
            {
                if (available + session.nextBufferSize < valueLen)
                {
                    // too large ... so we wrap and insert (zero-copy)
                    if (available == 0)
                    {
                        // buffer was actually full ... return a fresh buffer
                        return new LinkedBuffer(session.nextBufferSize,
                                new LinkedBuffer(value, offset, offset + valueLen, lb));
                    }

                    // continue with the existing byte array of the previous buffer
                    return new LinkedBuffer(lb,
                            new LinkedBuffer(value, offset, offset + valueLen, lb));
                }

                // copy what can fit
                System.arraycopy(value, offset, lb.buffer, lb.offset, available);

                lb.offset += available;

                // grow
                lb = new LinkedBuffer(session.nextBufferSize, lb);

                final int leftover = valueLen - available;

                // copy what's left
                System.arraycopy(value, offset + available, lb.buffer, 0, leftover);

                lb.offset += leftover;

                return lb;
            }

            // it fits
            System.arraycopy(value, offset, lb.buffer, lb.offset, valueLen);

            lb.offset += valueLen;

            return lb;
        }
The flexible output for outputs that use {@link WriteSession}.

@author David Yu
@created Sep 20, 2010
protostuff-api/src/main/java/io/protostuff/WriteSink.java