Path: blob/master/test/jdk/java/nio/Buffer/BasicByte.java
41149 views
/*1* Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/* Type-specific source code for unit test24*25* Regenerate the BasicX classes via genBasic.sh whenever this file changes.26* We check in the generated source files so that the test tree can be used27* independently of the rest of the source tree.28*/2930// -- This file was mechanically generated: Do not edit! -- //313233import java.io.IOException;34import java.io.UncheckedIOException;3536import java.nio.*;3738import java.nio.channels.FileChannel;39import java.nio.file.Files;40import java.nio.file.Path;41import java.util.Random;42434445public class BasicByte46extends Basic47{4849private static final byte[] VALUES = {50Byte.MIN_VALUE,51(byte) -1,52(byte) 0,53(byte) 1,54Byte.MAX_VALUE,55565758596061626364656667};6869private static void relGet(ByteBuffer b) {70int n = b.capacity();71for (int i = 0; i < n; i++)72ck(b, (long)b.get(), (long)((byte)ic(i)));73b.rewind();74}7576private static void relGet(ByteBuffer b, int start) {77int n = b.remaining();78for (int i = start; i < n; i++)79ck(b, (long)b.get(), (long)((byte)ic(i)));80b.rewind();81}8283private static void absGet(ByteBuffer b) {84int n = b.capacity();85for (int i = 0; i < n; i++)86ck(b, (long)b.get(), (long)((byte)ic(i)));87b.rewind();88}8990private static void bulkGet(ByteBuffer b) {91int n = b.capacity();92byte[] a = new byte[n + 7];93b.get(a, 7, n);94for (int i = 0; i < n; i++) {95ck(b, (long)a[i + 7], (long)((byte)ic(i)));96}97}9899private static void absBulkGet(ByteBuffer b) {100int n = b.capacity();101int len = n - 7*2;102byte[] a = new byte[n + 7];103b.position(42);104b.get(7, a, 7, len);105ck(b, b.position() == 42);106for (int i = 0; i < len; i++) {107ck(b, (long)a[i + 7], (long)((byte)ic(i)));108}109}110111private static void relPut(ByteBuffer b) {112int n = b.capacity();113b.clear();114for (int i = 0; i < n; i++)115b.put((byte)ic(i));116b.flip();117}118119private static void absPut(ByteBuffer b) {120int n = b.capacity();121b.clear();122for (int i = 0; i < n; i++)123b.put(i, (byte)ic(i));124b.limit(n);125b.position(0);126}127128private static void bulkPutArray(ByteBuffer b) {129int n = b.capacity();130b.clear();131byte[] a = new byte[n + 7];132for (int i = 0; i < n; i++)133a[i + 7] = (byte)ic(i);134b.put(a, 7, n);135b.flip();136}137138private static void bulkPutBuffer(ByteBuffer b) {139int n = b.capacity();140b.clear();141ByteBuffer c = ByteBuffer.allocate(n + 7);142c.position(7);143for (int i = 0; i < n; i++)144c.put((byte)ic(i));145c.flip();146c.position(7);147b.put(c);148b.flip();149try {150b.put(b);151fail("IllegalArgumentException expected for put into same buffer");152} catch (IllegalArgumentException e) {153if (e.getMessage() == null) {154fail("Non-null IllegalArgumentException message expected from"155+ " put into same buffer");156}157}158}159160private static void absBulkPutArray(ByteBuffer b) {161int n = b.capacity();162b.clear();163int lim = n - 7;164int len = lim - 7;165b.limit(lim);166byte[] a = new byte[len + 7];167for (int i = 0; i < len; i++)168a[i + 7] = (byte)ic(i);169b.position(42);170b.put(7, a, 7, len);171ck(b, b.position() == 42);172}173174//6231529175private static void callReset(ByteBuffer b) {176b.position(0);177b.mark();178179b.duplicate().reset();180b.asReadOnlyBuffer().reset();181}182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223private static void checkSlice(ByteBuffer b, ByteBuffer slice) {224ck(slice, 0, slice.position());225ck(slice, b.remaining(), slice.limit());226ck(slice, b.remaining(), slice.capacity());227if (b.isDirect() != slice.isDirect())228fail("Lost direction", slice);229if (b.isReadOnly() != slice.isReadOnly())230fail("Lost read-only", slice);231}232233234235private static void checkBytes(ByteBuffer b, byte[] bs) {236int n = bs.length;237int p = b.position();238if (b.order() == ByteOrder.BIG_ENDIAN) {239for (int i = 0; i < n; i++) {240ck(b, b.get(), bs[i]);241}242} else {243for (int i = n - 1; i >= 0; i--) {244ck(b, b.get(), bs[i]);245}246}247b.position(p);248}249250private static void compact(Buffer b) {251try {252Class<?> cl = b.getClass();253java.lang.reflect.Method m = cl.getDeclaredMethod("compact");254m.setAccessible(true);255m.invoke(b);256} catch (Exception e) {257fail(e.getMessage(), b);258}259}260261private static void checkInvalidMarkException(final Buffer b) {262tryCatch(b, InvalidMarkException.class, () -> {263b.mark();264compact(b);265b.reset();266});267}268269private static void testViews(int level, ByteBuffer b, boolean direct) {270271ShortBuffer sb = b.asShortBuffer();272BasicShort.test(level, sb, direct);273checkBytes(b, new byte[] { 0, (byte)ic(0) });274checkInvalidMarkException(sb);275276CharBuffer cb = b.asCharBuffer();277BasicChar.test(level, cb, direct);278checkBytes(b, new byte[] { 0, (byte)ic(0) });279checkInvalidMarkException(cb);280281IntBuffer ib = b.asIntBuffer();282BasicInt.test(level, ib, direct);283checkBytes(b, new byte[] { 0, 0, 0, (byte)ic(0) });284checkInvalidMarkException(ib);285286LongBuffer lb = b.asLongBuffer();287BasicLong.test(level, lb, direct);288checkBytes(b, new byte[] { 0, 0, 0, 0, 0, 0, 0, (byte)ic(0) });289checkInvalidMarkException(lb);290291FloatBuffer fb = b.asFloatBuffer();292BasicFloat.test(level, fb, direct);293checkBytes(b, new byte[] { 0x42, (byte)0xc2, 0, 0 });294checkInvalidMarkException(fb);295296DoubleBuffer db = b.asDoubleBuffer();297BasicDouble.test(level, db, direct);298checkBytes(b, new byte[] { 0x40, 0x58, 0x40, 0, 0, 0, 0, 0 });299checkInvalidMarkException(db);300}301302private static void testHet(int level, ByteBuffer b) {303304int p = b.position();305b.limit(b.capacity());306show(level, b);307out.print(" put:");308309b.putChar((char)1);310b.putChar((char)Character.MAX_VALUE);311out.print(" char");312313b.putShort((short)1);314b.putShort((short)Short.MAX_VALUE);315out.print(" short");316317b.putInt(1);318b.putInt(Integer.MAX_VALUE);319out.print(" int");320321b.putLong((long)1);322b.putLong((long)Long.MAX_VALUE);323out.print(" long");324325b.putFloat((float)1);326b.putFloat((float)Float.MIN_VALUE);327b.putFloat((float)Float.MAX_VALUE);328out.print(" float");329330b.putDouble((double)1);331b.putDouble((double)Double.MIN_VALUE);332b.putDouble((double)Double.MAX_VALUE);333out.print(" double");334335out.println();336b.limit(b.position());337b.position(p);338show(level, b);339out.print(" get:");340341ck(b, b.getChar(), 1);342ck(b, b.getChar(), Character.MAX_VALUE);343out.print(" char");344345ck(b, b.getShort(), 1);346ck(b, b.getShort(), Short.MAX_VALUE);347out.print(" short");348349ck(b, b.getInt(), 1);350ck(b, b.getInt(), Integer.MAX_VALUE);351out.print(" int");352353ck(b, b.getLong(), 1);354ck(b, b.getLong(), Long.MAX_VALUE);355out.print(" long");356357ck(b, (long)b.getFloat(), 1);358ck(b, (long)b.getFloat(), (long)Float.MIN_VALUE);359ck(b, (long)b.getFloat(), (long)Float.MAX_VALUE);360out.print(" float");361362ck(b, (long)b.getDouble(), 1);363ck(b, (long)b.getDouble(), (long)Double.MIN_VALUE);364ck(b, (long)b.getDouble(), (long)Double.MAX_VALUE);365out.print(" double");366367out.println();368369}370371private static void testAlign(final ByteBuffer b, boolean direct) {372// index out-of bounds373catchIllegalArgument(b, () -> b.alignmentOffset(-1, (short) 1));374375// unit size values376catchIllegalArgument(b, () -> b.alignmentOffset(0, (short) 0));377for (int us = 1; us < 65; us++) {378int _us = us;379if ((us & (us - 1)) != 0) {380// unit size not a power of two381catchIllegalArgument(b, () -> b.alignmentOffset(0, _us));382} else {383if (direct || us <= 8) {384b.alignmentOffset(0, us);385} else {386// unit size > 8 with non-direct buffer387tryCatch(b, UnsupportedOperationException.class,388() -> b.alignmentOffset(0, _us));389}390}391}392393// Probe for long misalignment at index zero for a newly created buffer394ByteBuffer empty =395direct ? ByteBuffer.allocateDirect(0) : ByteBuffer.allocate(0);396int longMisalignmentAtZero = empty.alignmentOffset(0, 8);397398if (direct) {399// Freshly created direct byte buffers should be aligned at index 0400// for ref and primitive values (see Unsafe.allocateMemory)401if (longMisalignmentAtZero != 0) {402fail("Direct byte buffer misaligned at index 0"403+ " for ref and primitive values "404+ longMisalignmentAtZero);405}406} else {407// For heap byte buffers misalignment may occur on 32-bit systems408// where Unsafe.ARRAY_BYTE_BASE_OFFSET % 8 == 4 and not 0409// Note the GC will preserve alignment of the base address of the410// array411if (jdk.internal.misc.Unsafe.ARRAY_BYTE_BASE_OFFSET % 8412!= longMisalignmentAtZero) {413fail("Heap byte buffer misaligned at index 0"414+ " for ref and primitive values "415+ longMisalignmentAtZero);416}417}418419// Ensure test buffer is correctly aligned at index 0420if (b.alignmentOffset(0, 8) != longMisalignmentAtZero)421fail("Test input buffer not correctly aligned at index 0", b);422423// Test misalignment values424for (int us : new int[]{1, 2, 4, 8}) {425for (int i = 0; i < us * 2; i++) {426int am = b.alignmentOffset(i, us);427int expectedAm = (longMisalignmentAtZero + i) % us;428429if (am != expectedAm) {430String f = "b.alignmentOffset(%d, %d) == %d incorrect, expected %d";431fail(String.format(f, i, us, am, expectedAm));432}433}434}435436// Created aligned slice to test against437int ap = 8 - longMisalignmentAtZero;438int al = b.limit() - b.alignmentOffset(b.limit(), 8);439ByteBuffer ab = b.position(ap).limit(al).440slice();441if (ab.limit() == 0) {442fail("Test input buffer not sufficiently sized to cover" +443" an aligned region for all values", b);444}445if (ab.alignmentOffset(0, 8) != 0)446fail("Aligned test input buffer not correctly aligned at index 0", ab);447448for (int us : new int[]{1, 2, 4, 8}) {449for (int p = 1; p < 16; p++) {450int l = ab.limit() - p;451452ByteBuffer as = ab.slice().position(p).limit(l).453alignedSlice(us);454455ck(as, 0, as.position());456ck(as, as.capacity(), as.limit());457if (b.isDirect() != as.isDirect())458fail("Lost direction", as);459if (b.isReadOnly() != as.isReadOnly())460fail("Lost read-only", as);461462if (as.alignmentOffset(0, us) != 0)463fail("Buffer not correctly aligned at index 0", as);464465if (as.alignmentOffset(as.limit(), us) != 0)466fail("Buffer not correctly aligned at limit", as);467468int p_mod = ab.alignmentOffset(p, us);469int l_mod = ab.alignmentOffset(l, us);470// Round up position471p = (p_mod > 0) ? p + (us - p_mod) : p;472// Round down limit473l = l - l_mod;474475int ec = l - p;476if (as.limit() != ec) {477fail("Buffer capacity incorrect, expected: " + ec, as);478}479}480}481482// mapped buffers483try {484for (MappedByteBuffer bb : mappedBuffers()) {485try {486int offset = bb.alignmentOffset(1, 4);487ck(bb, offset >= 0);488} catch (UnsupportedOperationException e) {489System.out.println("Not applicable, UOE thrown: ");490}491}492} catch (IOException e) {493throw new UncheckedIOException(e);494}495496// alignment identities497final int maxPow2 = 12;498ByteBuffer bb = ByteBuffer.allocateDirect(1 << maxPow2); // cap 4096499500Random rnd = new Random();501long seed = rnd.nextLong();502rnd = new Random(seed);503504for (int i = 0; i < 100; i++) {505// 1 == 2^0 <= unitSize == 2^k <= bb.capacity()/2506int unitSize = 1 << rnd.nextInt(maxPow2);507// 0 <= index < 2*unitSize508int index = rnd.nextInt(unitSize << 1);509int value = bb.alignmentOffset(index, unitSize);510try {511if (value < 0 || value >= unitSize) {512throw new RuntimeException(value + " < 0 || " +513value + " >= " + unitSize);514}515if (value <= index &&516bb.alignmentOffset(index - value, unitSize) != 0)517throw new RuntimeException("Identity 1");518if (bb.alignmentOffset(index + (unitSize - value),519unitSize) != 0)520throw new RuntimeException("Identity 2");521} catch (RuntimeException re) {522System.err.format("seed %d, index %d, unitSize %d, value %d%n",523seed, index, unitSize, value);524throw re;525}526}527}528529private static MappedByteBuffer[] mappedBuffers() throws IOException {530return new MappedByteBuffer[]{531createMappedBuffer(new byte[]{0, 1, 2, 3}),532createMappedBuffer(new byte[]{0, 1, 2, -3,53345, 6, 7, 78, 3, -7, 6, 7, -128, 127}),534};535}536537private static MappedByteBuffer createMappedBuffer(byte[] contents)538throws IOException {539Path tempFile = Files.createTempFile("mbb", null);540tempFile.toFile().deleteOnExit();541Files.write(tempFile, contents);542try (FileChannel fc = FileChannel.open(tempFile)) {543MappedByteBuffer map =544fc.map(FileChannel.MapMode.READ_ONLY, 0, contents.length);545map.load();546return map;547}548}549550551private static void fail(String problem,552ByteBuffer xb, ByteBuffer yb,553byte x, byte y) {554fail(problem + String.format(": x=%s y=%s", x, y), xb, yb);555}556557private static void catchNullArgument(Buffer b, Runnable thunk) {558tryCatch(b, NullPointerException.class, thunk);559}560561private static void catchIllegalArgument(Buffer b, Runnable thunk) {562tryCatch(b, IllegalArgumentException.class, thunk);563}564565private static void catchReadOnlyBuffer(Buffer b, Runnable thunk) {566tryCatch(b, ReadOnlyBufferException.class, thunk);567}568569private static void catchIndexOutOfBounds(Buffer b, Runnable thunk) {570tryCatch(b, IndexOutOfBoundsException.class, thunk);571}572573private static void catchIndexOutOfBounds(byte[] t, Runnable thunk) {574tryCatch(t, IndexOutOfBoundsException.class, thunk);575}576577private static void tryCatch(Buffer b, Class<?> ex, Runnable thunk) {578boolean caught = false;579try {580thunk.run();581} catch (Throwable x) {582if (ex.isAssignableFrom(x.getClass())) {583caught = true;584} else {585String s = x.getMessage();586if (s == null)587s = x.getClass().getName();588fail(s + " not expected");589}590}591if (!caught) {592fail(ex.getName() + " not thrown", b);593}594}595596private static void tryCatch(byte[] t, Class<?> ex, Runnable thunk) {597tryCatch(ByteBuffer.wrap(t), ex, thunk);598}599600public static void test(int level, final ByteBuffer b, boolean direct) {601602show(level, b);603604if (direct != b.isDirect())605fail("Wrong direction", b);606607// Gets and puts608609relPut(b);610relGet(b);611absGet(b);612bulkGet(b);613614absPut(b);615relGet(b);616absGet(b);617bulkGet(b);618619bulkPutArray(b);620relGet(b);621622bulkPutBuffer(b);623relGet(b);624625absBulkPutArray(b);626absBulkGet(b);627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664// Compact665666relPut(b);667b.position(13);668b.compact();669b.flip();670relGet(b, 13);671672// Exceptions673674relPut(b);675b.limit(b.capacity() / 2);676b.position(b.limit());677678tryCatch(b, BufferUnderflowException.class, () -> b.get());679tryCatch(b, BufferOverflowException.class, () -> b.put((byte)42));680// The index must be non-negative and less than the buffer's limit.681catchIndexOutOfBounds(b, () -> b.get(b.limit()));682catchIndexOutOfBounds(b, () -> b.get(-1));683catchIndexOutOfBounds(b, () -> b.put(b.limit(), (byte)42));684tryCatch(b, InvalidMarkException.class,685() -> b.position(0).mark().compact().reset());686687try {688b.position(b.limit() + 1);689fail("IllegalArgumentException expected for position beyond limit");690} catch (IllegalArgumentException e) {691if (e.getMessage() == null) {692fail("Non-null IllegalArgumentException message expected for"693+ " position beyond limit");694}695}696697try {698b.position(-1);699fail("IllegalArgumentException expected for negative position");700} catch (IllegalArgumentException e) {701if (e.getMessage() == null) {702fail("Non-null IllegalArgumentException message expected for"703+ " negative position");704}705}706707try {708b.limit(b.capacity() + 1);709fail("IllegalArgumentException expected for limit beyond capacity");710} catch (IllegalArgumentException e) {711if (e.getMessage() == null) {712fail("Non-null IllegalArgumentException message expected for"713+ " limit beyond capacity");714}715}716717try {718b.limit(-1);719fail("IllegalArgumentException expected for negative limit");720} catch (IllegalArgumentException e) {721if (e.getMessage() == null) {722fail("Non-null IllegalArgumentException message expected for"723+ " negative limit");724}725}726727// Exceptions in absolute bulk and slice operations728729catchNullArgument(b, () -> b.get(7, null, 0, 42));730catchNullArgument(b, () -> b.put(7, (byte[])null, 0, 42));731732byte[] tmpa = new byte[42];733catchIndexOutOfBounds(b, () -> b.get(7, tmpa, -1, 42));734catchIndexOutOfBounds(b, () -> b.get(7, tmpa, 42, 1));735catchIndexOutOfBounds(b, () -> b.get(7, tmpa, 41, -1));736catchIndexOutOfBounds(b, () -> b.get(-1, tmpa, 0, 1));737catchIndexOutOfBounds(b, () -> b.get(b.limit(), tmpa, 0, 1));738catchIndexOutOfBounds(b, () -> b.get(b.limit() - 41, tmpa, 0, 42));739740catchIndexOutOfBounds(b, () -> b.put(7, tmpa, -1, 42));741catchIndexOutOfBounds(b, () -> b.put(7, tmpa, 42, 1));742catchIndexOutOfBounds(b, () -> b.put(7, tmpa, 41, -1));743catchIndexOutOfBounds(b, () -> b.put(-1, tmpa, 0, 1));744catchIndexOutOfBounds(b, () -> b.put(b.limit(), tmpa, 0, 1));745catchIndexOutOfBounds(b, () -> b.put(b.limit() - 41, tmpa, 0, 42));746747catchIndexOutOfBounds(b, () -> b.slice(-1, 7));748catchIndexOutOfBounds(b, () -> b.slice(b.limit() + 1, 7));749catchIndexOutOfBounds(b, () -> b.slice(0, -1));750catchIndexOutOfBounds(b, () -> b.slice(7, b.limit() - 7 + 1));751752// Values753754b.clear();755b.put((byte)0);756b.put((byte)-1);757b.put((byte)1);758b.put(Byte.MAX_VALUE);759b.put(Byte.MIN_VALUE);760761762763764765766767768769770771772773774775776777b.flip();778ck(b, b.get(), 0);779ck(b, b.get(), (byte)-1);780ck(b, b.get(), 1);781ck(b, b.get(), Byte.MAX_VALUE);782ck(b, b.get(), Byte.MIN_VALUE);783784785786787788789790791792793794795796797798799800801802803804805806807808809810// Comparison811b.rewind();812ByteBuffer b2 = ByteBuffer.allocate(b.capacity());813b2.put(b);814b2.flip();815b.position(2);816b2.position(2);817if (!b.equals(b2)) {818for (int i = 2; i < b.limit(); i++) {819byte x = b.get(i);820byte y = b2.get(i);821if (x != y822823824825826827828) {829out.println("[" + i + "] " + x + " != " + y);830}831}832fail("Identical buffers not equal", b, b2);833}834if (b.compareTo(b2) != 0) {835fail("Comparison to identical buffer != 0", b, b2);836}837b.limit(b.limit() + 1);838b.position(b.limit() - 1);839b.put((byte)99);840b.rewind();841b2.rewind();842if (b.equals(b2))843fail("Non-identical buffers equal", b, b2);844if (b.compareTo(b2) <= 0)845fail("Comparison to shorter buffer <= 0", b, b2);846b.limit(b.limit() - 1);847848b.put(2, (byte)42);849if (b.equals(b2))850fail("Non-identical buffers equal", b, b2);851if (b.compareTo(b2) <= 0)852fail("Comparison to lesser buffer <= 0", b, b2);853854// Check equals and compareTo with interesting values855for (byte x : VALUES) {856ByteBuffer xb = ByteBuffer.wrap(new byte[] { x });857if (xb.compareTo(xb) != 0) {858fail("compareTo not reflexive", xb, xb, x, x);859}860if (!xb.equals(xb)) {861fail("equals not reflexive", xb, xb, x, x);862}863for (byte y : VALUES) {864ByteBuffer yb = ByteBuffer.wrap(new byte[] { y });865if (xb.compareTo(yb) != - yb.compareTo(xb)) {866fail("compareTo not anti-symmetric",867xb, yb, x, y);868}869if ((xb.compareTo(yb) == 0) != xb.equals(yb)) {870fail("compareTo inconsistent with equals",871xb, yb, x, y);872}873if (xb.compareTo(yb) != Byte.compare(x, y)) {874875876877878879880fail("Incorrect results for ByteBuffer.compareTo",881xb, yb, x, y);882}883if (xb.equals(yb) != ((x == y) || ((x != x) && (y != y)))) {884fail("Incorrect results for ByteBuffer.equals",885xb, yb, x, y);886}887}888}889890// Sub, dup891892relPut(b);893relGet(b.duplicate());894b.position(13);895relGet(b.duplicate(), 13);896relGet(b.duplicate().slice(), 13);897relGet(b.slice(), 13);898relGet(b.slice().duplicate(), 13);899900// Slice901902b.position(5);903ByteBuffer sb = b.slice();904checkSlice(b, sb);905b.position(0);906ByteBuffer sb2 = sb.slice();907checkSlice(sb, sb2);908909if (!sb.equals(sb2))910fail("Sliced slices do not match", sb, sb2);911if ((sb.hasArray()) && (sb.arrayOffset() != sb2.arrayOffset())) {912fail("Array offsets do not match: "913+ sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2);914}915916int bPos = b.position();917int bLim = b.limit();918919b.position(7);920b.limit(42);921ByteBuffer rsb = b.slice();922b.position(0);923b.limit(b.capacity());924ByteBuffer asb = b.slice(7, 35);925checkSlice(rsb, asb);926927b.position(bPos);928b.limit(bLim);929930931932// Views933934b.clear();935b.order(ByteOrder.BIG_ENDIAN);936testViews(level + 1, b, direct);937938for (int i = 1; i <= 9; i++) {939b.position(i);940show(level + 1, b);941testViews(level + 2, b, direct);942}943944b.position(0);945b.order(ByteOrder.LITTLE_ENDIAN);946testViews(level + 1, b, direct);947948// Heterogeneous accessors949950b.order(ByteOrder.BIG_ENDIAN);951for (int i = 0; i <= 9; i++) {952b.position(i);953testHet(level + 1, b);954}955b.order(ByteOrder.LITTLE_ENDIAN);956b.position(3);957testHet(level + 1, b);958959960961// Read-only views962963b.rewind();964final ByteBuffer rb = b.asReadOnlyBuffer();965if (!b.equals(rb))966fail("Buffer not equal to read-only view", b, rb);967show(level + 1, rb);968969catchReadOnlyBuffer(b, () -> relPut(rb));970catchReadOnlyBuffer(b, () -> absPut(rb));971catchReadOnlyBuffer(b, () -> bulkPutArray(rb));972catchReadOnlyBuffer(b, () -> bulkPutBuffer(rb));973catchReadOnlyBuffer(b, () -> absBulkPutArray(rb));974975// put(ByteBuffer) should not change source position976final ByteBuffer src = ByteBuffer.allocate(1);977catchReadOnlyBuffer(b, () -> rb.put(src));978ck(src, src.position(), 0);979980catchReadOnlyBuffer(b, () -> rb.compact());981982983984catchReadOnlyBuffer(b, () -> rb.putChar((char)1));985catchReadOnlyBuffer(b, () -> rb.putChar(0, (char)1));986catchReadOnlyBuffer(b, () -> rb.putShort((short)1));987catchReadOnlyBuffer(b, () -> rb.putShort(0, (short)1));988catchReadOnlyBuffer(b, () -> rb.putInt(1));989catchReadOnlyBuffer(b, () -> rb.putInt(0, 1));990catchReadOnlyBuffer(b, () -> rb.putLong((long)1));991catchReadOnlyBuffer(b, () -> rb.putLong(0, (long)1));992catchReadOnlyBuffer(b, () -> rb.putFloat((float)1));993catchReadOnlyBuffer(b, () -> rb.putFloat(0, (float)1));994catchReadOnlyBuffer(b, () -> rb.putDouble((double)1));995catchReadOnlyBuffer(b, () -> rb.putDouble(0, (double)1));99699799899910001001100210031004100510061007if (rb.getClass().getName().startsWith("java.nio.Heap")) {1008catchReadOnlyBuffer(b, () -> rb.array());1009catchReadOnlyBuffer(b, () -> rb.arrayOffset());1010if (rb.hasArray()) {1011fail("Read-only heap buffer's backing array is accessible", rb);1012}1013}10141015// Bulk puts from read-only buffers10161017b.clear();1018rb.rewind();1019b.put(rb);102010211022// For byte buffers, test both the direct and non-direct cases1023ByteBuffer ob1024= (b.isDirect()1025? ByteBuffer.allocate(rb.capacity())1026: ByteBuffer.allocateDirect(rb.capacity()));1027rb.rewind();1028ob.put(rb);102910301031relPut(b); // Required by testViews103210331034// Test alignment10351036testAlign(b, direct);10371038}1039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090public static void test(final byte [] ba) {1091int offset = 47;1092int length = 900;1093final ByteBuffer b = ByteBuffer.wrap(ba, offset, length);1094show(0, b);1095ck(b, b.capacity(), ba.length);1096ck(b, b.position(), offset);1097ck(b, b.limit(), offset + length);10981099// The offset must be non-negative and no larger than <array.length>.1100catchIndexOutOfBounds(ba, () -> ByteBuffer.wrap(ba, -1, ba.length));1101catchIndexOutOfBounds(ba, () -> ByteBuffer.wrap(ba, ba.length + 1, ba.length));1102catchIndexOutOfBounds(ba, () -> ByteBuffer.wrap(ba, 0, -1));1103catchIndexOutOfBounds(ba, () -> ByteBuffer.wrap(ba, 0, ba.length + 1));11041105// A NullPointerException will be thrown if the array is null.1106tryCatch(ba, NullPointerException.class,1107() -> ByteBuffer.wrap((byte []) null, 0, 5));1108tryCatch(ba, NullPointerException.class,1109() -> ByteBuffer.wrap((byte []) null));1110}11111112private static void testAllocate() {1113// An IllegalArgumentException will be thrown for negative capacities.1114catchIllegalArgument((Buffer) null, () -> ByteBuffer.allocate(-1));1115try {1116ByteBuffer.allocate(-1);1117} catch (IllegalArgumentException e) {1118if (e.getMessage() == null) {1119fail("Non-null IllegalArgumentException message expected for"1120+ " attempt to allocate negative capacity buffer");1121}1122}11231124catchIllegalArgument((Buffer) null, () -> ByteBuffer.allocateDirect(-1));1125try {1126ByteBuffer.allocateDirect(-1);1127} catch (IllegalArgumentException e) {1128if (e.getMessage() == null) {1129fail("Non-null IllegalArgumentException message expected for"1130+ " attempt to allocate negative capacity direct buffer");1131}1132}11331134}11351136public static void test() {1137testAllocate();1138test(0, ByteBuffer.allocate(7 * 1024), false);1139test(0, ByteBuffer.wrap(new byte[7 * 1024], 0, 7 * 1024), false);1140test(new byte[1024]);11411142ByteBuffer b = ByteBuffer.allocateDirect(7 * 1024);1143for (b.position(0); b.position() < b.limit(); )1144ck(b, b.get(), 0);1145test(0, b, true);114611471148114911501151callReset(ByteBuffer.allocate(10));115211531154115511561157}11581159}116011611162