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.nio.ByteBuffer;
 26 import java.util.Arrays;
 27 import java.util.Random;
 28 import java.util.concurrent.ExecutionException;
 29 import java.util.function.Supplier;
 30 import java.util.stream.Stream;
 31 
 32 import jdk.incubator.foreign.MemorySegment;
 33 import jdk.incubator.foreign.ResourceScope;
 34 import jdk.test.lib.RandomFactory;
 35 import org.testng.annotations.*;
 36 
 37 import static jdk.incubator.foreign.ValueLayout.JAVA_BYTE;
 38 import static org.testng.Assert.*;
 39 
 40 /**
 41  * Not a test, but infra for channel tests.
 42  */
 43 public class AbstractChannelsTest {
 44 
 45     static final Class<IOException> IOE = IOException.class;
 46     static final Class<ExecutionException> EE = ExecutionException.class;
 47     static final Class<IllegalStateException> ISE = IllegalStateException.class;
 48 
 49     @FunctionalInterface
 50     interface ThrowingConsumer<T, X extends Throwable> {
 51         void accept(T action) throws X;
 52     }
 53 
 54     static ResourceScope closeableScopeOrNull(ResourceScope scope) {
 55         if (scope == ResourceScope.globalScope())
 56             return null;
 57         return scope;
 58     }
 59 
 60     static long remaining(ByteBuffer[] buffers) {
 61         return Arrays.stream(buffers).mapToLong(ByteBuffer::remaining).sum();
 62     }
 63 
 64     static ByteBuffer[] flip(ByteBuffer[] buffers) {
 65         Arrays.stream(buffers).forEach(ByteBuffer::flip);
 66         return buffers;
 67     }
 68 
 69     static ByteBuffer[] clear(ByteBuffer[] buffers) {
 70         Arrays.stream(buffers).forEach(ByteBuffer::clear);
 71         return buffers;
 72     }
 73 
 74     static final Random RANDOM = RandomFactory.getRandom();
 75 
 76     static ByteBuffer segmentBufferOfSize(ResourceScope scope, int size) {
 77         var segment = MemorySegment.allocateNative(size, 1, scope);
 78         for (int i = 0; i < size; i++) {
 79             segment.set(JAVA_BYTE, i, ((byte)RANDOM.nextInt()));
 80         }
 81         return segment.asByteBuffer();
 82     }
 83 
 84     static ByteBuffer[] segmentBuffersOfSize(int len, ResourceScope scope, int size) {
 85         ByteBuffer[] bufs = new ByteBuffer[len];
 86         for (int i = 0; i < len; i++)
 87             bufs[i] = segmentBufferOfSize(scope, size);
 88         return bufs;
 89     }
 90 
 91     /**
 92      * Returns an array of mixed source byte buffers; both heap and direct,
 93      * where heap can be from the global scope or scope-less, and direct are
 94      * associated with the given scope.
 95      */
 96     static ByteBuffer[] mixedBuffersOfSize(int len, ResourceScope scope, int size) {
 97         ByteBuffer[] bufs;
 98         boolean atLeastOneScopeBuffer = false;
 99         do {
100             bufs = new ByteBuffer[len];
101             for (int i = 0; i < len; i++) {
102                 bufs[i] = switch (RANDOM.nextInt(3)) {
103                     case 0 -> { byte[] b = new byte[size];
104                                 RANDOM.nextBytes(b);
105                                 yield ByteBuffer.wrap(b); }
106                     case 1 -> { byte[] b = new byte[size];
107                                 RANDOM.nextBytes(b);
108                                 yield MemorySegment.ofArray(b).asByteBuffer(); }
109                     case 2 -> { atLeastOneScopeBuffer = true;
110                                 yield segmentBufferOfSize(scope, size); }
111                     default -> throw new AssertionError("cannot happen");
112                 };
113             }
114         } while (!atLeastOneScopeBuffer);
115         return bufs;
116     }
117 
118     static void assertMessage(Exception ex, String msg) {
119         assertTrue(ex.getMessage().contains(msg), "Expected [%s], in: [%s]".formatted(msg, ex.getMessage()));
120     }
121 
122     static void assertCauses(Throwable ex, Class<? extends Exception>... exceptions) {
123         for (var expectedClass : exceptions) {
124             ex = ex.getCause();
125             assertTrue(expectedClass.isInstance(ex), "Expected %s, got: %s".formatted(expectedClass, ex));
126         }
127     }
128 
129     @DataProvider(name = "confinedScopes")
130     public static Object[][] confinedScopes() {
131         return new Object[][] {
132                 { ScopeSupplier.NEW_CONFINED          },
133         };
134     }
135 
136     @DataProvider(name = "sharedScopes")
137     public static Object[][] sharedScopes() {
138         return new Object[][] {
139                 { ScopeSupplier.NEW_SHARED          },
140         };
141     }
142 
143     @DataProvider(name = "closeableScopes")
144     public static Object[][] closeableScopes() {
145         return Stream.of(sharedScopes(), confinedScopes())
146                 .flatMap(Arrays::stream)
147                 .toArray(Object[][]::new);
148     }
149 
150     @DataProvider(name = "implicitScopes")
151     public static Object[][] implicitScopes() {
152         return new Object[][] {
153                 { ScopeSupplier.GLOBAL       },
154         };
155     }
156 
157     @DataProvider(name = "sharedAndImplicitScopes")
158     public static Object[][] sharedAndImplicitScopes() {
159         return Stream.of(sharedScopes(), implicitScopes())
160                 .flatMap(Arrays::stream)
161                 .toArray(Object[][]::new);
162     }
163 
164     @DataProvider(name = "allScopes")
165     public static Object[][] allScopes() {
166         return Stream.of(implicitScopes(), closeableScopes())
167                 .flatMap(Arrays::stream)
168                 .toArray(Object[][]::new);
169     }
170 
171     @DataProvider(name = "sharedScopesAndTimeouts")
172     public static Object[][] sharedScopesAndTimeouts() {
173         return new Object[][] {
174                 { ScopeSupplier.NEW_SHARED          ,  0 },
175                 { ScopeSupplier.NEW_SHARED          , 30 },
176         };
177     }
178 
179     static class ScopeSupplier implements Supplier<ResourceScope> {
180 
181         static final Supplier<ResourceScope> NEW_CONFINED =
182                 new ScopeSupplier(ResourceScope::newConfinedScope, "newConfinedScope()");
183         static final Supplier<ResourceScope> NEW_SHARED =
184                 new ScopeSupplier(ResourceScope::newSharedScope, "newSharedScope()");
185         static final Supplier<ResourceScope> NEW_IMPLICIT =
186                 new ScopeSupplier(ResourceScope::newImplicitScope, "newImplicitScope()");
187         static final Supplier<ResourceScope> GLOBAL =
188                 new ScopeSupplier(ResourceScope::globalScope, "globalScope()");
189 
190         private final Supplier<ResourceScope> supplier;
191         private final String str;
192         private ScopeSupplier(Supplier<ResourceScope> supplier, String str) {
193             this.supplier = supplier;
194             this.str = str;
195         }
196         @Override public String toString() { return str; }
197         @Override public ResourceScope get() { return supplier.get(); }
198     }
199 }
200