1 /*
2  * Copyright 2012 The Netty Project
3  *
4  * The Netty Project licenses this file to you under the Apache License,
5  * version 2.0 (the "License"); you may not use this file except in compliance
6  * with the License. You may obtain a copy of the License at:
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations
14  * under the License.
15  */

16 package io.netty.buffer;
17
18 import io.netty.util.AsciiString;
19 import io.netty.util.ByteProcessor;
20 import io.netty.util.CharsetUtil;
21 import io.netty.util.IllegalReferenceCountException;
22 import io.netty.util.ResourceLeakDetector;
23 import io.netty.util.ResourceLeakDetectorFactory;
24 import io.netty.util.internal.ObjectUtil;
25 import io.netty.util.internal.PlatformDependent;
26 import io.netty.util.internal.StringUtil;
27 import io.netty.util.internal.SystemPropertyUtil;
28 import io.netty.util.internal.logging.InternalLogger;
29 import io.netty.util.internal.logging.InternalLoggerFactory;
30
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.OutputStream;
34 import java.nio.ByteBuffer;
35 import java.nio.ByteOrder;
36 import java.nio.channels.FileChannel;
37 import java.nio.channels.GatheringByteChannel;
38 import java.nio.channels.ScatteringByteChannel;
39 import java.nio.charset.Charset;
40
41 import static io.netty.util.internal.MathUtil.isOutOfBounds;
42 import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
43
44 /**
45  * A skeletal implementation of a buffer.
46  */

47 public abstract class AbstractByteBuf extends ByteBuf {
48     private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractByteBuf.class);
49     private static final String LEGACY_PROP_CHECK_ACCESSIBLE = "io.netty.buffer.bytebuf.checkAccessible";
50     private static final String PROP_CHECK_ACCESSIBLE = "io.netty.buffer.checkAccessible";
51     static final boolean checkAccessible; // accessed from CompositeByteBuf
52     private static final String PROP_CHECK_BOUNDS = "io.netty.buffer.checkBounds";
53     private static final boolean checkBounds;
54
55     static {
56         if (SystemPropertyUtil.contains(PROP_CHECK_ACCESSIBLE)) {
57             checkAccessible = SystemPropertyUtil.getBoolean(PROP_CHECK_ACCESSIBLE, true);
58         } else {
59             checkAccessible = SystemPropertyUtil.getBoolean(LEGACY_PROP_CHECK_ACCESSIBLE, true);
60         }
61         checkBounds = SystemPropertyUtil.getBoolean(PROP_CHECK_BOUNDS, true);
62         if (logger.isDebugEnabled()) {
63             logger.debug("-D{}: {}", PROP_CHECK_ACCESSIBLE, checkAccessible);
64             logger.debug("-D{}: {}", PROP_CHECK_BOUNDS, checkBounds);
65         }
66     }
67
68     static final ResourceLeakDetector<ByteBuf> leakDetector =
69             ResourceLeakDetectorFactory.instance().newResourceLeakDetector(ByteBuf.class);
70
71     int readerIndex;
72     int writerIndex;
73     private int markedReaderIndex;
74     private int markedWriterIndex;
75     private int maxCapacity;
76
77     protected AbstractByteBuf(int maxCapacity) {
78         checkPositiveOrZero(maxCapacity, "maxCapacity");
79         this.maxCapacity = maxCapacity;
80     }
81
82     @Override
83     public boolean isReadOnly() {
84         return false;
85     }
86
87     @SuppressWarnings("deprecation")
88     @Override
89     public ByteBuf asReadOnly() {
90         if (isReadOnly()) {
91             return this;
92         }
93         return Unpooled.unmodifiableBuffer(this);
94     }
95
96     @Override
97     public int maxCapacity() {
98         return maxCapacity;
99     }
100
101     protected final void maxCapacity(int maxCapacity) {
102         this.maxCapacity = maxCapacity;
103     }
104
105     @Override
106     public int readerIndex() {
107         return readerIndex;
108     }
109
110     private static void checkIndexBounds(final int readerIndex, final int writerIndex, final int capacity) {
111         if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > capacity) {
112             throw new IndexOutOfBoundsException(String.format(
113                     "readerIndex: %d, writerIndex: %d (expected: 0 <= readerIndex <= writerIndex <= capacity(%d))",
114                     readerIndex, writerIndex, capacity));
115         }
116     }
117
118     @Override
119     public ByteBuf readerIndex(int readerIndex) {
120         if (checkBounds) {
121             checkIndexBounds(readerIndex, writerIndex, capacity());
122         }
123         this.readerIndex = readerIndex;
124         return this;
125     }
126
127     @Override
128     public int writerIndex() {
129         return writerIndex;
130     }
131
132     @Override
133     public ByteBuf writerIndex(int writerIndex) {
134         if (checkBounds) {
135             checkIndexBounds(readerIndex, writerIndex, capacity());
136         }
137         this.writerIndex = writerIndex;
138         return this;
139     }
140
141     @Override
142     public ByteBuf setIndex(int readerIndex, int writerIndex) {
143         if (checkBounds) {
144             checkIndexBounds(readerIndex, writerIndex, capacity());
145         }
146         setIndex0(readerIndex, writerIndex);
147         return this;
148     }
149
150     @Override
151     public ByteBuf clear() {
152         readerIndex = writerIndex = 0;
153         return this;
154     }
155
156     @Override
157     public boolean isReadable() {
158         return writerIndex > readerIndex;
159     }
160
161     @Override
162     public boolean isReadable(int numBytes) {
163         return writerIndex - readerIndex >= numBytes;
164     }
165
166     @Override
167     public boolean isWritable() {
168         return capacity() > writerIndex;
169     }
170
171     @Override
172     public boolean isWritable(int numBytes) {
173         return capacity() - writerIndex >= numBytes;
174     }
175
176     @Override
177     public int readableBytes() {
178         return writerIndex - readerIndex;
179     }
180
181     @Override
182     public int writableBytes() {
183         return capacity() - writerIndex;
184     }
185
186     @Override
187     public int maxWritableBytes() {
188         return maxCapacity() - writerIndex;
189     }
190
191     @Override
192     public ByteBuf markReaderIndex() {
193         markedReaderIndex = readerIndex;
194         return this;
195     }
196
197     @Override
198     public ByteBuf resetReaderIndex() {
199         readerIndex(markedReaderIndex);
200         return this;
201     }
202
203     @Override
204     public ByteBuf markWriterIndex() {
205         markedWriterIndex = writerIndex;
206         return this;
207     }
208
209     @Override
210     public ByteBuf resetWriterIndex() {
211         writerIndex(markedWriterIndex);
212         return this;
213     }
214
215     @Override
216     public ByteBuf discardReadBytes() {
217         if (readerIndex == 0) {
218             ensureAccessible();
219             return this;
220         }
221
222         if (readerIndex != writerIndex) {
223             setBytes(0, this, readerIndex, writerIndex - readerIndex);
224             writerIndex -= readerIndex;
225             adjustMarkers(readerIndex);
226             readerIndex = 0;
227         } else {
228             ensureAccessible();
229             adjustMarkers(readerIndex);
230             writerIndex = readerIndex = 0;
231         }
232         return this;
233     }
234
235     @Override
236     public ByteBuf discardSomeReadBytes() {
237         if (readerIndex > 0) {
238             if (readerIndex == writerIndex) {
239                 ensureAccessible();
240                 adjustMarkers(readerIndex);
241                 writerIndex = readerIndex = 0;
242                 return this;
243             }
244
245             if (readerIndex >= capacity() >>> 1) {
246                 setBytes(0, this, readerIndex, writerIndex - readerIndex);
247                 writerIndex -= readerIndex;
248                 adjustMarkers(readerIndex);
249                 readerIndex = 0;
250                 return this;
251             }
252         }
253         ensureAccessible();
254         return this;
255     }
256
257     protected final void adjustMarkers(int decrement) {
258         int markedReaderIndex = this.markedReaderIndex;
259         if (markedReaderIndex <= decrement) {
260             this.markedReaderIndex = 0;
261             int markedWriterIndex = this.markedWriterIndex;
262             if (markedWriterIndex <= decrement) {
263                 this.markedWriterIndex = 0;
264             } else {
265                 this.markedWriterIndex = markedWriterIndex - decrement;
266             }
267         } else {
268             this.markedReaderIndex = markedReaderIndex - decrement;
269             markedWriterIndex -= decrement;
270         }
271     }
272
273     // Called after a capacity reduction
274     protected final void trimIndicesToCapacity(int newCapacity) {
275         if (writerIndex() > newCapacity) {
276             setIndex0(Math.min(readerIndex(), newCapacity), newCapacity);
277         }
278     }
279
280     @Override
281     public ByteBuf ensureWritable(int minWritableBytes) {
282         ensureWritable0(checkPositiveOrZero(minWritableBytes, "minWritableBytes"));
283         return this;
284     }
285
286     final void ensureWritable0(int minWritableBytes) {
287         final int writerIndex = writerIndex();
288         final int targetCapacity = writerIndex + minWritableBytes;
289         // using non-short-circuit & to reduce branching - this is a hot path and targetCapacity should rarely overflow
290         if (targetCapacity >= 0 & targetCapacity <= capacity()) {
291             ensureAccessible();
292             return;
293         }
294         if (checkBounds && (targetCapacity < 0 || targetCapacity > maxCapacity)) {
295             ensureAccessible();
296             throw new IndexOutOfBoundsException(String.format(
297                     "writerIndex(%d) + minWritableBytes(%d) exceeds maxCapacity(%d): %s",
298                     writerIndex, minWritableBytes, maxCapacity, this));
299         }
300
301         // Normalize the target capacity to the power of 2.
302         final int fastWritable = maxFastWritableBytes();
303         int newCapacity = fastWritable >= minWritableBytes ? writerIndex + fastWritable
304                 : alloc().calculateNewCapacity(targetCapacity, maxCapacity);
305
306         // Adjust to the new capacity.
307         capacity(newCapacity);
308     }
309
310     @Override
311     public int ensureWritable(int minWritableBytes, boolean force) {
312         ensureAccessible();
313         checkPositiveOrZero(minWritableBytes, "minWritableBytes");
314
315         if (minWritableBytes <= writableBytes()) {
316             return 0;
317         }
318
319         final int maxCapacity = maxCapacity();
320         final int writerIndex = writerIndex();
321         if (minWritableBytes > maxCapacity - writerIndex) {
322             if (!force || capacity() == maxCapacity) {
323                 return 1;
324             }
325
326             capacity(maxCapacity);
327             return 3;
328         }
329
330         int fastWritable = maxFastWritableBytes();
331         int newCapacity = fastWritable >= minWritableBytes ? writerIndex + fastWritable
332                 : alloc().calculateNewCapacity(writerIndex + minWritableBytes, maxCapacity);
333
334         // Adjust to the new capacity.
335         capacity(newCapacity);
336         return 2;
337     }
338
339     @Override
340     public ByteBuf order(ByteOrder endianness) {
341         if (endianness == order()) {
342             return this;
343         }
344         ObjectUtil.checkNotNull(endianness, "endianness");
345         return newSwappedByteBuf();
346     }
347
348     /**
349      * Creates a new {@link SwappedByteBuf} for this {@link ByteBuf} instance.
350      */

351     protected SwappedByteBuf newSwappedByteBuf() {
352         return new SwappedByteBuf(this);
353     }
354
355     @Override
356     public byte getByte(int index) {
357         checkIndex(index);
358         return _getByte(index);
359     }
360
361     protected abstract byte _getByte(int index);
362
363     @Override
364     public boolean getBoolean(int index) {
365         return getByte(index) != 0;
366     }
367
368     @Override
369     public short getUnsignedByte(int index) {
370         return (short) (getByte(index) & 0xFF);
371     }
372
373     @Override
374     public short getShort(int index) {
375         checkIndex(index, 2);
376         return _getShort(index);
377     }
378
379     protected abstract short _getShort(int index);
380
381     @Override
382     public short getShortLE(int index) {
383         checkIndex(index, 2);
384         return _getShortLE(index);
385     }
386
387     protected abstract short _getShortLE(int index);
388
389     @Override
390     public int getUnsignedShort(int index) {
391         return getShort(index) & 0xFFFF;
392     }
393
394     @Override
395     public int getUnsignedShortLE(int index) {
396         return getShortLE(index) & 0xFFFF;
397     }
398
399     @Override
400     public int getUnsignedMedium(int index) {
401         checkIndex(index, 3);
402         return _getUnsignedMedium(index);
403     }
404
405     protected abstract int _getUnsignedMedium(int index);
406
407     @Override
408     public int getUnsignedMediumLE(int index) {
409         checkIndex(index, 3);
410         return _getUnsignedMediumLE(index);
411     }
412
413     protected abstract int _getUnsignedMediumLE(int index);
414
415     @Override
416     public int getMedium(int index) {
417         int value = getUnsignedMedium(index);
418         if ((value & 0x800000) != 0) {
419             value |= 0xff000000;
420         }
421         return value;
422     }
423
424     @Override
425     public int getMediumLE(int index) {
426         int value = getUnsignedMediumLE(index);
427         if ((value & 0x800000) != 0) {
428             value |= 0xff000000;
429         }
430         return value;
431     }
432
433     @Override
434     public int getInt(int index) {
435         checkIndex(index, 4);
436         return _getInt(index);
437     }
438
439     protected abstract int _getInt(int index);
440
441     @Override
442     public int getIntLE(int index) {
443         checkIndex(index, 4);
444         return _getIntLE(index);
445     }
446
447     protected abstract int _getIntLE(int index);
448
449     @Override
450     public long getUnsignedInt(int index) {
451         return getInt(index) & 0xFFFFFFFFL;
452     }
453
454     @Override
455     public long getUnsignedIntLE(int index) {
456         return getIntLE(index) & 0xFFFFFFFFL;
457     }
458
459     @Override
460     public long getLong(int index) {
461         checkIndex(index, 8);
462         return _getLong(index);
463     }
464
465     protected abstract long _getLong(int index);
466
467     @Override
468     public long getLongLE(int index) {
469         checkIndex(index, 8);
470         return _getLongLE(index);
471     }
472
473     protected abstract long _getLongLE(int index);
474
475     @Override
476     public char getChar(int index) {
477         return (char) getShort(index);
478     }
479
480     @Override
481     public float getFloat(int index) {
482         return Float.intBitsToFloat(getInt(index));
483     }
484
485     @Override
486     public double getDouble(int index) {
487         return Double.longBitsToDouble(getLong(index));
488     }
489
490     @Override
491     public ByteBuf getBytes(int index, byte[] dst) {
492         getBytes(index, dst, 0, dst.length);
493         return this;
494     }
495
496     @Override
497     public ByteBuf getBytes(int index, ByteBuf dst) {
498         getBytes(index, dst, dst.writableBytes());
499         return this;
500     }
501
502     @Override
503     public ByteBuf getBytes(int index, ByteBuf dst, int length) {
504         getBytes(index, dst, dst.writerIndex(), length);
505         dst.writerIndex(dst.writerIndex() + length);
506         return this;
507     }
508
509     @Override
510     public CharSequence getCharSequence(int index, int length, Charset charset) {
511         if (CharsetUtil.US_ASCII.equals(charset) || CharsetUtil.ISO_8859_1.equals(charset)) {
512             // ByteBufUtil.getBytes(...) will return a new copy which the AsciiString uses directly
513             return new AsciiString(ByteBufUtil.getBytes(this, index, length, true), false);
514         }
515         return toString(index, length, charset);
516     }
517
518     @Override
519     public CharSequence readCharSequence(int length, Charset charset) {
520         CharSequence sequence = getCharSequence(readerIndex, length, charset);
521         readerIndex += length;
522         return sequence;
523     }
524
525     @Override
526     public ByteBuf setByte(int index, int value) {
527         checkIndex(index);
528         _setByte(index, value);
529         return this;
530     }
531
532     protected abstract void _setByte(int index, int value);
533
534     @Override
535     public ByteBuf setBoolean(int index, boolean value) {
536         setByte(index, value? 1 : 0);
537         return this;
538     }
539
540     @Override
541     public ByteBuf setShort(int index, int value) {
542         checkIndex(index, 2);
543         _setShort(index, value);
544         return this;
545     }
546
547     protected abstract void _setShort(int index, int value);
548
549     @Override
550     public ByteBuf setShortLE(int index, int value) {
551         checkIndex(index, 2);
552         _setShortLE(index, value);
553         return this;
554     }
555
556     protected abstract void _setShortLE(int index, int value);
557
558     @Override
559     public ByteBuf setChar(int index, int value) {
560         setShort(index, value);
561         return this;
562     }
563
564     @Override
565     public ByteBuf setMedium(int index, int value) {
566         checkIndex(index, 3);
567         _setMedium(index, value);
568         return this;
569     }
570
571     protected abstract void _setMedium(int index, int value);
572
573     @Override
574     public ByteBuf setMediumLE(int index, int value) {
575         checkIndex(index, 3);
576         _setMediumLE(index, value);
577         return this;
578     }
579
580     protected abstract void _setMediumLE(int index, int value);
581
582     @Override
583     public ByteBuf setInt(int index, int value) {
584         checkIndex(index, 4);
585         _setInt(index, value);
586         return this;
587     }
588
589     protected abstract void _setInt(int index, int value);
590
591     @Override
592     public ByteBuf setIntLE(int index, int value) {
593         checkIndex(index, 4);
594         _setIntLE(index, value);
595         return this;
596     }
597
598     protected abstract void _setIntLE(int index, int value);
599
600     @Override
601     public ByteBuf setFloat(int index, float value) {
602         setInt(index, Float.floatToRawIntBits(value));
603         return this;
604     }
605
606     @Override
607     public ByteBuf setLong(int index, long value) {
608         checkIndex(index, 8);
609         _setLong(index, value);
610         return this;
611     }
612
613     protected abstract void _setLong(int index, long value);
614
615     @Override
616     public ByteBuf setLongLE(int index, long value) {
617         checkIndex(index, 8);
618         _setLongLE(index, value);
619         return this;
620     }
621
622     protected abstract void _setLongLE(int index, long value);
623
624     @Override
625     public ByteBuf setDouble(int index, double value) {
626         setLong(index, Double.doubleToRawLongBits(value));
627         return this;
628     }
629
630     @Override
631     public ByteBuf setBytes(int index, byte[] src) {
632         setBytes(index, src, 0, src.length);
633         return this;
634     }
635
636     @Override
637     public ByteBuf setBytes(int index, ByteBuf src) {
638         setBytes(index, src, src.readableBytes());
639         return this;
640     }
641
642     private static void checkReadableBounds(final ByteBuf src, final int length) {
643         if (length > src.readableBytes()) {
644             throw new IndexOutOfBoundsException(String.format(
645                     "length(%d) exceeds src.readableBytes(%d) where src is: %s", length, src.readableBytes(), src));
646         }
647     }
648
649     @Override
650     public ByteBuf setBytes(int index, ByteBuf src, int length) {
651         checkIndex(index, length);
652         ObjectUtil.checkNotNull(src, "src");
653         if (checkBounds) {
654             checkReadableBounds(src, length);
655         }
656
657         setBytes(index, src, src.readerIndex(), length);
658         src.readerIndex(src.readerIndex() + length);
659         return this;
660     }
661
662     @Override
663     public ByteBuf setZero(int index, int length) {
664         if (length == 0) {
665             return this;
666         }
667
668         checkIndex(index, length);
669
670         int nLong = length >>> 3;
671         int nBytes = length & 7;
672         for (int i = nLong; i > 0; i --) {
673             _setLong(index, 0);
674             index += 8;
675         }
676         if (nBytes == 4) {
677             _setInt(index, 0);
678             // Not need to update the index as we not will use it after this.
679         } else if (nBytes < 4) {
680             for (int i = nBytes; i > 0; i --) {
681                 _setByte(index, (byte) 0);
682                 index ++;
683             }
684         } else {
685             _setInt(index, 0);
686             index += 4;
687             for (int i = nBytes - 4; i > 0; i --) {
688                 _setByte(index, (byte) 0);
689                 index ++;
690             }
691         }
692         return this;
693     }
694
695     @Override
696     public int setCharSequence(int index, CharSequence sequence, Charset charset) {
697         return setCharSequence0(index, sequence, charset, false);
698     }
699
700     private int setCharSequence0(int index, CharSequence sequence, Charset charset, boolean expand) {
701         if (charset.equals(CharsetUtil.UTF_8)) {
702             int length = ByteBufUtil.utf8MaxBytes(sequence);
703             if (expand) {
704                 ensureWritable0(length);
705                 checkIndex0(index, length);
706             } else {
707                 checkIndex(index, length);
708             }
709             return ByteBufUtil.writeUtf8(this, index, length, sequence, sequence.length());
710         }
711         if (charset.equals(CharsetUtil.US_ASCII) || charset.equals(CharsetUtil.ISO_8859_1)) {
712             int length = sequence.length();
713             if (expand) {
714                 ensureWritable0(length);
715                 checkIndex0(index, length);
716             } else {
717                 checkIndex(index, length);
718             }
719             return ByteBufUtil.writeAscii(this, index, sequence, length);
720         }
721         byte[] bytes = sequence.toString().getBytes(charset);
722         if (expand) {
723             ensureWritable0(bytes.length);
724             // setBytes(...) will take care of checking the indices.
725         }
726         setBytes(index, bytes);
727         return bytes.length;
728     }
729
730     @Override
731     public byte readByte() {
732         checkReadableBytes0(1);
733         int i = readerIndex;
734         byte b = _getByte(i);
735         readerIndex = i + 1;
736         return b;
737     }
738
739     @Override
740     public boolean readBoolean() {
741         return readByte() != 0;
742     }
743
744     @Override
745     public short readUnsignedByte() {
746         return (short) (readByte() & 0xFF);
747     }
748
749     @Override
750     public short readShort() {
751         checkReadableBytes0(2);
752         short v = _getShort(readerIndex);
753         readerIndex += 2;
754         return v;
755     }
756
757     @Override
758     public short readShortLE() {
759         checkReadableBytes0(2);
760         short v = _getShortLE(readerIndex);
761         readerIndex += 2;
762         return v;
763     }
764
765     @Override
766     public int readUnsignedShort() {
767         return readShort() & 0xFFFF;
768     }
769
770     @Override
771     public int readUnsignedShortLE() {
772         return readShortLE() & 0xFFFF;
773     }
774
775     @Override
776     public int readMedium() {
777         int value = readUnsignedMedium();
778         if ((value & 0x800000) != 0) {
779             value |= 0xff000000;
780         }
781         return value;
782     }
783
784     @Override
785     public int readMediumLE() {
786         int value = readUnsignedMediumLE();
787         if ((value & 0x800000) != 0) {
788             value |= 0xff000000;
789         }
790         return value;
791     }
792
793     @Override
794     public int readUnsignedMedium() {
795         checkReadableBytes0(3);
796         int v = _getUnsignedMedium(readerIndex);
797         readerIndex += 3;
798         return v;
799     }
800
801     @Override
802     public int readUnsignedMediumLE() {
803         checkReadableBytes0(3);
804         int v = _getUnsignedMediumLE(readerIndex);
805         readerIndex += 3;
806         return v;
807     }
808
809     @Override
810     public int readInt() {
811         checkReadableBytes0(4);
812         int v = _getInt(readerIndex);
813         readerIndex += 4;
814         return v;
815     }
816
817     @Override
818     public int readIntLE() {
819         checkReadableBytes0(4);
820         int v = _getIntLE(readerIndex);
821         readerIndex += 4;
822         return v;
823     }
824
825     @Override
826     public long readUnsignedInt() {
827         return readInt() & 0xFFFFFFFFL;
828     }
829
830     @Override
831     public long readUnsignedIntLE() {
832         return readIntLE() & 0xFFFFFFFFL;
833     }
834
835     @Override
836     public long readLong() {
837         checkReadableBytes0(8);
838         long v = _getLong(readerIndex);
839         readerIndex += 8;
840         return v;
841     }
842
843     @Override
844     public long readLongLE() {
845         checkReadableBytes0(8);
846         long v = _getLongLE(readerIndex);
847         readerIndex += 8;
848         return v;
849     }
850
851     @Override
852     public char readChar() {
853         return (char) readShort();
854     }
855
856     @Override
857     public float readFloat() {
858         return Float.intBitsToFloat(readInt());
859     }
860
861     @Override
862     public double readDouble() {
863         return Double.longBitsToDouble(readLong());
864     }
865
866     @Override
867     public ByteBuf readBytes(int length) {
868         checkReadableBytes(length);
869         if (length == 0) {
870             return Unpooled.EMPTY_BUFFER;
871         }
872
873         ByteBuf buf = alloc().buffer(length, maxCapacity);
874         buf.writeBytes(this, readerIndex, length);
875         readerIndex += length;
876         return buf;
877     }
878
879     @Override
880     public ByteBuf readSlice(int length) {
881         checkReadableBytes(length);
882         ByteBuf slice = slice(readerIndex, length);
883         readerIndex += length;
884         return slice;
885     }
886
887     @Override
888     public ByteBuf readRetainedSlice(int length) {
889         checkReadableBytes(length);
890         ByteBuf slice = retainedSlice(readerIndex, length);
891         readerIndex += length;
892         return slice;
893     }
894
895     @Override
896     public ByteBuf readBytes(byte[] dst, int dstIndex, int length) {
897         checkReadableBytes(length);
898         getBytes(readerIndex, dst, dstIndex, length);
899         readerIndex += length;
900         return this;
901     }
902
903     @Override
904     public ByteBuf readBytes(byte[] dst) {
905         readBytes(dst, 0, dst.length);
906         return this;
907     }
908
909     @Override
910     public ByteBuf readBytes(ByteBuf dst) {
911         readBytes(dst, dst.writableBytes());
912         return this;
913     }
914
915     @Override
916     public ByteBuf readBytes(ByteBuf dst, int length) {
917         if (checkBounds) {
918             if (length > dst.writableBytes()) {
919                 throw new IndexOutOfBoundsException(String.format(
920                         "length(%d) exceeds dst.writableBytes(%d) where dst is: %s", length, dst.writableBytes(), dst));
921             }
922         }
923         readBytes(dst, dst.writerIndex(), length);
924         dst.writerIndex(dst.writerIndex() + length);
925         return this;
926     }
927
928     @Override
929     public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) {
930         checkReadableBytes(length);
931         getBytes(readerIndex, dst, dstIndex, length);
932         readerIndex += length;
933         return this;
934     }
935
936     @Override
937     public ByteBuf readBytes(ByteBuffer dst) {
938         int length = dst.remaining();
939         checkReadableBytes(length);
940         getBytes(readerIndex, dst);
941         readerIndex += length;
942         return this;
943     }
944
945     @Override
946     public int readBytes(GatheringByteChannel out, int length)
947             throws IOException {
948         checkReadableBytes(length);
949         int readBytes = getBytes(readerIndex, out, length);
950         readerIndex += readBytes;
951         return readBytes;
952     }
953
954     @Override
955     public int readBytes(FileChannel out, long position, int length)
956             throws IOException {
957         checkReadableBytes(length);
958         int readBytes = getBytes(readerIndex, out, position, length);
959         readerIndex += readBytes;
960         return readBytes;
961     }
962
963     @Override
964     public ByteBuf readBytes(OutputStream out, int length) throws IOException {
965         checkReadableBytes(length);
966         getBytes(readerIndex, out, length);
967         readerIndex += length;
968         return this;
969     }
970
971     @Override
972     public ByteBuf skipBytes(int length) {
973         checkReadableBytes(length);
974         readerIndex += length;
975         return this;
976     }
977
978     @Override
979     public ByteBuf writeBoolean(boolean value) {
980         writeByte(value ? 1 : 0);
981         return this;
982     }
983
984     @Override
985     public ByteBuf writeByte(int value) {
986         ensureWritable0(1);
987         _setByte(writerIndex++, value);
988         return this;
989     }
990
991     @Override
992     public ByteBuf writeShort(int value) {
993         ensureWritable0(2);
994         _setShort(writerIndex, value);
995         writerIndex += 2;
996         return this;
997     }
998
999     @Override
1000     public ByteBuf writeShortLE(int value) {
1001         ensureWritable0(2);
1002         _setShortLE(writerIndex, value);
1003         writerIndex += 2;
1004         return this;
1005     }
1006
1007     @Override
1008     public ByteBuf writeMedium(int value) {
1009         ensureWritable0(3);
1010         _setMedium(writerIndex, value);
1011         writerIndex += 3;
1012         return this;
1013     }
1014
1015     @Override
1016     public ByteBuf writeMediumLE(int value) {
1017         ensureWritable0(3);
1018         _setMediumLE(writerIndex, value);
1019         writerIndex += 3;
1020         return this;
1021     }
1022
1023     @Override
1024     public ByteBuf writeInt(int value) {
1025         ensureWritable0(4);
1026         _setInt(writerIndex, value);
1027         writerIndex += 4;
1028         return this;
1029     }
1030
1031     @Override
1032     public ByteBuf writeIntLE(int value) {
1033         ensureWritable0(4);
1034         _setIntLE(writerIndex, value);
1035         writerIndex += 4;
1036         return this;
1037     }
1038
1039     @Override
1040     public ByteBuf writeLong(long value) {
1041         ensureWritable0(8);
1042         _setLong(writerIndex, value);
1043         writerIndex += 8;
1044         return this;
1045     }
1046
1047     @Override
1048     public ByteBuf writeLongLE(long value) {
1049         ensureWritable0(8);
1050         _setLongLE(writerIndex, value);
1051         writerIndex += 8;
1052         return this;
1053     }
1054
1055     @Override
1056     public ByteBuf writeChar(int value) {
1057         writeShort(value);
1058         return this;
1059     }
1060
1061     @Override
1062     public ByteBuf writeFloat(float value) {
1063         writeInt(Float.floatToRawIntBits(value));
1064         return this;
1065     }
1066
1067     @Override
1068     public ByteBuf writeDouble(double value) {
1069         writeLong(Double.doubleToRawLongBits(value));
1070         return this;
1071     }
1072
1073     @Override
1074     public ByteBuf writeBytes(byte[] src, int srcIndex, int length) {
1075         ensureWritable(length);
1076         setBytes(writerIndex, src, srcIndex, length);
1077         writerIndex += length;
1078         return this;
1079     }
1080
1081     @Override
1082     public ByteBuf writeBytes(byte[] src) {
1083         writeBytes(src, 0, src.length);
1084         return this;
1085     }
1086
1087     @Override
1088     public ByteBuf writeBytes(ByteBuf src) {
1089         writeBytes(src, src.readableBytes());
1090         return this;
1091     }
1092
1093     @Override
1094     public ByteBuf writeBytes(ByteBuf src, int length) {
1095         if (checkBounds) {
1096             checkReadableBounds(src, length);
1097         }
1098         writeBytes(src, src.readerIndex(), length);
1099         src.readerIndex(src.readerIndex() + length);
1100         return this;
1101     }
1102
1103     @Override
1104     public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) {
1105         ensureWritable(length);
1106         setBytes(writerIndex, src, srcIndex, length);
1107         writerIndex += length;
1108         return this;
1109     }
1110
1111     @Override
1112     public ByteBuf writeBytes(ByteBuffer src) {
1113         int length = src.remaining();
1114         ensureWritable0(length);
1115         setBytes(writerIndex, src);
1116         writerIndex += length;
1117         return this;
1118     }
1119
1120     @Override
1121     public int writeBytes(InputStream in, int length)
1122             throws IOException {
1123         ensureWritable(length);
1124         int writtenBytes = setBytes(writerIndex, in, length);
1125         if (writtenBytes > 0) {
1126             writerIndex += writtenBytes;
1127         }
1128         return writtenBytes;
1129     }
1130
1131     @Override
1132     public int writeBytes(ScatteringByteChannel in, int length) throws IOException {
1133         ensureWritable(length);
1134         int writtenBytes = setBytes(writerIndex, in, length);
1135         if (writtenBytes > 0) {
1136             writerIndex += writtenBytes;
1137         }
1138         return writtenBytes;
1139     }
1140
1141     @Override
1142     public int writeBytes(FileChannel in, long position, int length) throws IOException {
1143         ensureWritable(length);
1144         int writtenBytes = setBytes(writerIndex, in, position, length);
1145         if (writtenBytes > 0) {
1146             writerIndex += writtenBytes;
1147         }
1148         return writtenBytes;
1149     }
1150
1151     @Override
1152     public ByteBuf writeZero(int length) {
1153         if (length == 0) {
1154             return this;
1155         }
1156
1157         ensureWritable(length);
1158         int wIndex = writerIndex;
1159         checkIndex0(wIndex, length);
1160
1161         int nLong = length >>> 3;
1162         int nBytes = length & 7;
1163         for (int i = nLong; i > 0; i --) {
1164             _setLong(wIndex, 0);
1165             wIndex += 8;
1166         }
1167         if (nBytes == 4) {
1168             _setInt(wIndex, 0);
1169             wIndex += 4;
1170         } else if (nBytes < 4) {
1171             for (int i = nBytes; i > 0; i --) {
1172                 _setByte(wIndex, (byte) 0);
1173                 wIndex++;
1174             }
1175         } else {
1176             _setInt(wIndex, 0);
1177             wIndex += 4;
1178             for (int i = nBytes - 4; i > 0; i --) {
1179                 _setByte(wIndex, (byte) 0);
1180                 wIndex++;
1181             }
1182         }
1183         writerIndex = wIndex;
1184         return this;
1185     }
1186
1187     @Override
1188     public int writeCharSequence(CharSequence sequence, Charset charset) {
1189         int written = setCharSequence0(writerIndex, sequence, charset, true);
1190         writerIndex += written;
1191         return written;
1192     }
1193
1194     @Override
1195     public ByteBuf copy() {
1196         return copy(readerIndex, readableBytes());
1197     }
1198
1199     @Override
1200     public ByteBuf duplicate() {
1201         ensureAccessible();
1202         return new UnpooledDuplicatedByteBuf(this);
1203     }
1204
1205     @Override
1206     public ByteBuf retainedDuplicate() {
1207         return duplicate().retain();
1208     }
1209
1210     @Override
1211     public ByteBuf slice() {
1212         return slice(readerIndex, readableBytes());
1213     }
1214
1215     @Override
1216     public ByteBuf retainedSlice() {
1217         return slice().retain();
1218     }
1219
1220     @Override
1221     public ByteBuf slice(int index, int length) {
1222         ensureAccessible();
1223         return new UnpooledSlicedByteBuf(this, index, length);
1224     }
1225
1226     @Override
1227     public ByteBuf retainedSlice(int index, int length) {
1228         return slice(index, length).retain();
1229     }
1230
1231     @Override
1232     public ByteBuffer nioBuffer() {
1233         return nioBuffer(readerIndex, readableBytes());
1234     }
1235
1236     @Override
1237     public ByteBuffer[] nioBuffers() {
1238         return nioBuffers(readerIndex, readableBytes());
1239     }
1240
1241     @Override
1242     public String toString(Charset charset) {
1243         return toString(readerIndex, readableBytes(), charset);
1244     }
1245
1246     @Override
1247     public String toString(int index, int length, Charset charset) {
1248         return ByteBufUtil.decodeString(this, index, length, charset);
1249     }
1250
1251     @Override
1252     public int indexOf(int fromIndex, int toIndex, byte value) {
1253         if (fromIndex <= toIndex) {
1254             return firstIndexOf(fromIndex, toIndex, value);
1255         } else {
1256             return lastIndexOf(fromIndex, toIndex, value);
1257         }
1258     }
1259
1260     private int firstIndexOf(int fromIndex, int toIndex, byte value) {
1261         fromIndex = Math.max(fromIndex, 0);
1262         if (fromIndex >= toIndex || capacity() == 0) {
1263             return -1;
1264         }
1265         checkIndex(fromIndex, toIndex - fromIndex);
1266
1267         for (int i = fromIndex; i < toIndex; i ++) {
1268             if (_getByte(i) == value) {
1269                 return i;
1270             }
1271         }
1272
1273         return -1;
1274     }
1275
1276     private int lastIndexOf(int fromIndex, int toIndex, byte value) {
1277         fromIndex = Math.min(fromIndex, capacity());
1278         if (fromIndex < 0 || capacity() == 0) {
1279             return -1;
1280         }
1281
1282         checkIndex(toIndex, fromIndex - toIndex);
1283
1284         for (int i = fromIndex - 1; i >= toIndex; i --) {
1285             if (_getByte(i) == value) {
1286                 return i;
1287             }
1288         }
1289
1290         return -1;
1291     }
1292
1293     @Override
1294     public int bytesBefore(byte value) {
1295         return bytesBefore(readerIndex(), readableBytes(), value);
1296     }
1297
1298     @Override
1299     public int bytesBefore(int length, byte value) {
1300         checkReadableBytes(length);
1301         return bytesBefore(readerIndex(), length, value);
1302     }
1303
1304     @Override
1305     public int bytesBefore(int index, int length, byte value) {
1306         int endIndex = indexOf(index, index + length, value);
1307         if (endIndex < 0) {
1308             return -1;
1309         }
1310         return endIndex - index;
1311     }
1312
1313     @Override
1314     public int forEachByte(ByteProcessor processor) {
1315         ensureAccessible();
1316         try {
1317             return forEachByteAsc0(readerIndex, writerIndex, processor);
1318         } catch (Exception e) {
1319             PlatformDependent.throwException(e);
1320             return -1;
1321         }
1322     }
1323
1324     @Override
1325     public int forEachByte(int index, int length, ByteProcessor processor) {
1326         checkIndex(index, length);
1327         try {
1328             return forEachByteAsc0(index, index + length, processor);
1329         } catch (Exception e) {
1330             PlatformDependent.throwException(e);
1331             return -1;
1332         }
1333     }
1334
1335     int forEachByteAsc0(int start, int end, ByteProcessor processor) throws Exception {
1336         for (; start < end; ++start) {
1337             if (!processor.process(_getByte(start))) {
1338                 return start;
1339             }
1340         }
1341
1342         return -1;
1343     }
1344
1345     @Override
1346     public int forEachByteDesc(ByteProcessor processor) {
1347         ensureAccessible();
1348         try {
1349             return forEachByteDesc0(writerIndex - 1, readerIndex, processor);
1350         } catch (Exception e) {
1351             PlatformDependent.throwException(e);
1352             return -1;
1353         }
1354     }
1355
1356     @Override
1357     public int forEachByteDesc(int index, int length, ByteProcessor processor) {
1358         checkIndex(index, length);
1359         try {
1360             return forEachByteDesc0(index + length - 1, index, processor);
1361         } catch (Exception e) {
1362             PlatformDependent.throwException(e);
1363             return -1;
1364         }
1365     }
1366
1367     int forEachByteDesc0(int rStart, final int rEnd, ByteProcessor processor) throws Exception {
1368         for (; rStart >= rEnd; --rStart) {
1369             if (!processor.process(_getByte(rStart))) {
1370                 return rStart;
1371             }
1372         }
1373         return -1;
1374     }
1375
1376     @Override
1377     public int hashCode() {
1378         return ByteBufUtil.hashCode(this);
1379     }
1380
1381     @Override
1382     public boolean equals(Object o) {
1383         return this == o || (o instanceof ByteBuf && ByteBufUtil.equals(this, (ByteBuf) o));
1384     }
1385
1386     @Override
1387     public int compareTo(ByteBuf that) {
1388         return ByteBufUtil.compare(this, that);
1389     }
1390
1391     @Override
1392     public String toString() {
1393         if (refCnt() == 0) {
1394             return StringUtil.simpleClassName(this) + "(freed)";
1395         }
1396
1397         StringBuilder buf = new StringBuilder()
1398             .append(StringUtil.simpleClassName(this))
1399             .append("(ridx: ").append(readerIndex)
1400             .append(", widx: ").append(writerIndex)
1401             .append(", cap: ").append(capacity());
1402         if (maxCapacity != Integer.MAX_VALUE) {
1403             buf.append('/').append(maxCapacity);
1404         }
1405
1406         ByteBuf unwrapped = unwrap();
1407         if (unwrapped != null) {
1408             buf.append(", unwrapped: ").append(unwrapped);
1409         }
1410         buf.append(')');
1411         return buf.toString();
1412     }
1413
1414     protected final void checkIndex(int index) {
1415         checkIndex(index, 1);
1416     }
1417
1418     protected final void checkIndex(int index, int fieldLength) {
1419         ensureAccessible();
1420         checkIndex0(index, fieldLength);
1421     }
1422
1423     private static void checkRangeBounds(final String indexName, final int index,
1424             final int fieldLength, final int capacity) {
1425         if (isOutOfBounds(index, fieldLength, capacity)) {
1426             throw new IndexOutOfBoundsException(String.format(
1427                     "%s: %d, length: %d (expected: range(0, %d))", indexName, index, fieldLength, capacity));
1428         }
1429     }
1430
1431     final void checkIndex0(int index, int fieldLength) {
1432         if (checkBounds) {
1433             checkRangeBounds("index", index, fieldLength, capacity());
1434         }
1435     }
1436
1437     protected final void checkSrcIndex(int index, int length, int srcIndex, int srcCapacity) {
1438         checkIndex(index, length);
1439         if (checkBounds) {
1440             checkRangeBounds("srcIndex", srcIndex, length, srcCapacity);
1441         }
1442     }
1443
1444     protected final void checkDstIndex(int index, int length, int dstIndex, int dstCapacity) {
1445         checkIndex(index, length);
1446         if (checkBounds) {
1447             checkRangeBounds("dstIndex", dstIndex, length, dstCapacity);
1448         }
1449     }
1450
1451     protected final void checkDstIndex(int length, int dstIndex, int dstCapacity) {
1452         checkReadableBytes(length);
1453         if (checkBounds) {
1454             checkRangeBounds("dstIndex", dstIndex, length, dstCapacity);
1455         }
1456     }
1457
1458     /**
1459      * Throws an {@link IndexOutOfBoundsException} if the current
1460      * {@linkplain #readableBytes() readable bytes} of this buffer is less
1461      * than the specified value.
1462      */

1463     protected final void checkReadableBytes(int minimumReadableBytes) {
1464         checkReadableBytes0(checkPositiveOrZero(minimumReadableBytes, "minimumReadableBytes"));
1465     }
1466
1467     protected final void checkNewCapacity(int newCapacity) {
1468         ensureAccessible();
1469         if (checkBounds && (newCapacity < 0 || newCapacity > maxCapacity())) {
1470             throw new IllegalArgumentException("newCapacity: " + newCapacity +
1471                     " (expected: 0-" + maxCapacity() + ')');
1472         }
1473     }
1474
1475     private void checkReadableBytes0(int minimumReadableBytes) {
1476         ensureAccessible();
1477         if (checkBounds && readerIndex > writerIndex - minimumReadableBytes) {
1478             throw new IndexOutOfBoundsException(String.format(
1479                     "readerIndex(%d) + length(%d) exceeds writerIndex(%d): %s",
1480                     readerIndex, minimumReadableBytes, writerIndex, this));
1481         }
1482     }
1483
1484     /**
1485      * Should be called by every method that tries to access the buffers content to check
1486      * if the buffer was released before.
1487      */

1488     protected final void ensureAccessible() {
1489         if (checkAccessible && !isAccessible()) {
1490             throw new IllegalReferenceCountException(0);
1491         }
1492     }
1493
1494     final void setIndex0(int readerIndex, int writerIndex) {
1495         this.readerIndex = readerIndex;
1496         this.writerIndex = writerIndex;
1497     }
1498
1499     final void discardMarks() {
1500         markedReaderIndex = markedWriterIndex = 0;
1501     }
1502 }
1503