Path: blob/master/test/jdk/java/foreign/NativeTestHelper.java
41144 views
/*1* Copyright (c) 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*22*/2324import jdk.incubator.foreign.CLinker;25import jdk.incubator.foreign.MemoryLayout;26import jdk.incubator.foreign.MemorySegment;27import jdk.incubator.foreign.ResourceScope;28import jdk.incubator.foreign.SegmentAllocator;2930public class NativeTestHelper {3132static CLinker.TypeKind kind(MemoryLayout layout) {33return (CLinker.TypeKind)layout.attribute(CLinker.TypeKind.ATTR_NAME).orElseThrow(34() -> new IllegalStateException("Unexpected value layout: could not determine ABI class"));35}3637public static boolean isIntegral(MemoryLayout layout) {38return kind(layout).isIntegral();39}4041public static boolean isPointer(MemoryLayout layout) {42return kind(layout).isPointer();43}4445public static class NativeScope implements SegmentAllocator, AutoCloseable {46final ResourceScope resourceScope;47final ResourceScope.Handle scopeHandle;48final SegmentAllocator allocator;4950long allocatedBytes = 0;5152public NativeScope() {53this.resourceScope = ResourceScope.newConfinedScope();54this.scopeHandle = resourceScope.acquire();55this.allocator = SegmentAllocator.arenaAllocator(resourceScope);56}5758@Override59public MemorySegment allocate(long bytesSize, long bytesAlignment) {60allocatedBytes += bytesSize;61return allocator.allocate(bytesSize, bytesAlignment);62}6364public ResourceScope scope() {65return resourceScope;66}6768public long allocatedBytes() {69return allocatedBytes;70}7172@Override73public void close() {74resourceScope.release(scopeHandle);75resourceScope.close();76}77}78}798081