1 /* 2 * Copyright (c) 2024, 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. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 package wrap; 26 27 import java.lang.foreign.MemoryLayout; 28 import java.lang.foreign.MemorySegment; 29 import java.lang.invoke.VarHandle; 30 31 public record Sequence(String name, MemorySegment memorySegment, 32 VarHandle varHandle) { 33 34 public static Sequence of(MemorySegment memorySegment, MemoryLayout memoryLayout, String name) { 35 return of(memorySegment, memoryLayout, 36 MemoryLayout.PathElement.groupElement(name), MemoryLayout.PathElement.sequenceElement()); 37 } 38 39 public static Sequence of(MemorySegment memorySegment, MemoryLayout memoryLayout, 40 MemoryLayout.PathElement... pathElements) { 41 VarHandle vh = memoryLayout.varHandle(pathElements); 42 String name = null; 43 for (int i = 0; i < pathElements.length; i++) { 44 MemoryLayout.PathElement pathElement = pathElements[i]; 45 // Why can't I access LayoutPath? 46 if (pathElement.toString().isEmpty()) { 47 name = pathElement.toString(); 48 } 49 } 50 return new Sequence(name, memorySegment, vh); 51 52 } 53 54 public Object get(long idx) { 55 return varHandle.get(memorySegment, 0, idx); 56 } 57 58 public byte i8(long idx) { 59 return (byte) get(idx); 60 } 61 62 public short i16(long idx ) { 63 return (short) get(idx); 64 } 65 66 public int i32(long idx ) { 67 return (int) get(idx); 68 } 69 70 public long i64(long idx ) { 71 return (long) get(idx); 72 } 73 74 public float f32(long idx ) { 75 return (float) get(idx); 76 } 77 78 public double f64(long idx ) { 79 return (double) get(idx); 80 } 81 82 public Sequence set(long idx , byte v) { 83 varHandle.set(memorySegment, 0, idx, v); 84 return this; 85 } 86 }