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