1 /*
  2  * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 import java.io.IOException;
 25 import java.lang.ref.Cleaner;
 26 import java.nio.ByteBuffer;
 27 import java.util.Arrays;
 28 import java.util.Random;
 29 import java.util.concurrent.ExecutionException;
 30 import java.util.function.Supplier;
 31 import java.util.stream.Stream;
 32 import jdk.incubator.foreign.MemoryAccess;
 33 import jdk.incubator.foreign.MemorySegment;
 34 import jdk.incubator.foreign.ResourceScope;
 35 import jdk.test.lib.RandomFactory;
 36 import org.testng.annotations.*;
 37 import static org.testng.Assert.*;
 38 
 39 /**
 40  * Not a test, but infra for channel tests.
 41  */
 42 public class AbstractChannelsTest {
 43 
 44     static final Class<IOException> IOE = IOException.class;
 45     static final Class<ExecutionException> EE = ExecutionException.class;
 46     static final Class<IllegalStateException> ISE = IllegalStateException.class;
 47 
 48     @FunctionalInterface
 49     interface ThrowingConsumer<T, X extends Throwable> {
 50         void accept(T action) throws X;
 51     }
 52 
 53     static ResourceScope closeableScopeOrNull(ResourceScope scope) {
 54         if (scope.isImplicit())
 55             return null;
 56         return scope;
 57     }
 58 
 59     static long remaining(ByteBuffer[] buffers) {
 60         return Arrays.stream(buffers).mapToLong(ByteBuffer::remaining).sum();
 61     }
 62 
 63     static ByteBuffer[] flip(ByteBuffer[] buffers) {
 64         Arrays.stream(buffers).forEach(ByteBuffer::flip);
 65         return buffers;
 66     }
 67 
 68     static ByteBuffer[] clear(ByteBuffer[] buffers) {
 69         Arrays.stream(buffers).forEach(ByteBuffer::clear);
 70         return buffers;
 71     }
 72 
 73     static final Random RANDOM = RandomFactory.getRandom();
 74 
 75     static ByteBuffer segmentBufferOfSize(ResourceScope scope, int size) {
 76         var segment = MemorySegment.allocateNative(size, 1, scope);
 77         for (int i = 0; i < size; i++) {
 78             MemoryAccess.setByteAtOffset(segment, i, ((byte)RANDOM.nextInt()));
 79         }
 80         return segment.asByteBuffer();
 81     }
 82 
 83     static ByteBuffer[] segmentBuffersOfSize(int len, ResourceScope scope, int size) {
 84         ByteBuffer[] bufs = new ByteBuffer[len];
 85         for (int i = 0; i < len; i++)
 86             bufs[i] = segmentBufferOfSize(scope, size);
 87         return bufs;
 88     }
 89 
 90     /**
 91      * Returns an array of mixed source byte buffers; both heap and direct,
 92      * where heap can be from the global scope or scope-less, and direct are
 93      * associated with the given scope.
 94      */
 95     static ByteBuffer[] mixedBuffersOfSize(int len, ResourceScope scope, int size) {
 96         ByteBuffer[] bufs;
 97         boolean atLeastOneScopeBuffer = false;
 98         do {
 99             bufs = new ByteBuffer[len];
100             for (int i = 0; i < len; i++) {
101                 bufs[i] = switch (RANDOM.nextInt(3)) {
102                     case 0 -> { byte[] b = new byte[size];
103                                 RANDOM.nextBytes(b);
104                                 yield ByteBuffer.wrap(b); }
105                     case 1 -> { byte[] b = new byte[size];
106                                 RANDOM.nextBytes(b);
107                                 yield MemorySegment.ofArray(b).asByteBuffer(); }
108                     case 2 -> { atLeastOneScopeBuffer = true;
109                                 yield segmentBufferOfSize(scope, size); }
110                     default -> throw new AssertionError("cannot happen");
111                 };
112             }
113         } while (!atLeastOneScopeBuffer);
114         return bufs;
115     }
116 
117     static void assertMessage(Exception ex, String msg) {
118         assertTrue(ex.getMessage().contains(msg), "Expected [%s], in: [%s]".formatted(msg, ex.getMessage()));
119     }
120 
121     static void assertCauses(Throwable ex, Class<? extends Exception>... exceptions) {
122         for (var expectedClass : exceptions) {
123             ex = ex.getCause();
124             assertTrue(expectedClass.isInstance(ex), "Expected %s, got: %s".formatted(expectedClass, ex));
125         }
126     }
127 
128     @DataProvider(name = "confinedScopes")
129     public static Object[][] confinedScopes() {
130         return new Object[][] {
131                 { ScopeSupplier.NEW_CONFINED          },
132                 { ScopeSupplier.NEW_CONFINED_EXPLICIT },
133         };
134     }
135 
136     @DataProvider(name = "sharedScopes")
137     public static Object[][] sharedScopes() {
138         return new Object[][] {
139                 { ScopeSupplier.NEW_SHARED          },
140                 { ScopeSupplier.NEW_SHARED_EXPLICIT },
141         };
142     }
143 
144     @DataProvider(name = "closeableScopes")
145     public static Object[][] closeableScopes() {
146         return Stream.of(sharedScopes(), confinedScopes())
147                 .flatMap(Arrays::stream)
148                 .toArray(Object[][]::new);
149     }
150 
151     @DataProvider(name = "implicitScopes")
152     public static Object[][] implicitScopes() {
153         return new Object[][] {
154                 { ScopeSupplier.NEW_IMPLICIT },
155                 { ScopeSupplier.GLOBAL       },
156         };
157     }
158 
159     @DataProvider(name = "sharedAndImplicitScopes")
160     public static Object[][] sharedAndImplicitScopes() {
161         return Stream.of(sharedScopes(), implicitScopes())
162                 .flatMap(Arrays::stream)
163                 .toArray(Object[][]::new);
164     }
165 
166     @DataProvider(name = "allScopes")
167     public static Object[][] allScopes() {
168         return Stream.of(implicitScopes(), closeableScopes())
169                 .flatMap(Arrays::stream)
170                 .toArray(Object[][]::new);
171     }
172 
173     @DataProvider(name = "sharedScopesAndTimeouts")
174     public static Object[][] sharedScopesAndTimeouts() {
175         return new Object[][] {
176                 { ScopeSupplier.NEW_SHARED          ,  0 },
177                 { ScopeSupplier.NEW_SHARED_EXPLICIT ,  0 },
178                 { ScopeSupplier.NEW_SHARED          , 30 },
179                 { ScopeSupplier.NEW_SHARED_EXPLICIT , 30 },
180         };
181     }
182 
183     static class ScopeSupplier implements Supplier<ResourceScope> {
184 
185         static final Supplier<ResourceScope> NEW_CONFINED =
186                 new ScopeSupplier(() -> ResourceScope.newConfinedScope(), "newConfinedScope()");
187         static final Supplier<ResourceScope> NEW_CONFINED_EXPLICIT =
188                 new ScopeSupplier(() -> ResourceScope.newConfinedScope(Cleaner.create()), "newConfinedScope(Cleaner)");
189         static final Supplier<ResourceScope> NEW_SHARED =
190                 new ScopeSupplier(() -> ResourceScope.newSharedScope(), "newSharedScope()");
191         static final Supplier<ResourceScope> NEW_SHARED_EXPLICIT =
192                 new ScopeSupplier(() -> ResourceScope.newSharedScope(Cleaner.create()), "newSharedScope(Cleaner)");
193         static final Supplier<ResourceScope> NEW_IMPLICIT =
194                 new ScopeSupplier(() -> ResourceScope.newImplicitScope(), "newImplicitScope()");
195         static final Supplier<ResourceScope> GLOBAL =
196                 new ScopeSupplier(() -> ResourceScope.globalScope(), "globalScope()");
197 
198         private final Supplier<ResourceScope> supplier;
199         private final String str;
200         private ScopeSupplier(Supplier<ResourceScope> supplier, String str) {
201             this.supplier = supplier;
202             this.str = str;
203         }
204         @Override public String toString() { return str; }
205         @Override public ResourceScope get() { return supplier.get(); }
206     }
207 }
208