@@ -66,7 +66,7 @@ public class LayoutPath {
66
66
private static final MethodHandle MH_SLICE_LAYOUT ;
67
67
private static final MethodHandle MH_CHECK_ENCL_LAYOUT ;
68
68
private static final MethodHandle MH_SEGMENT_RESIZE ;
69
- private static final MethodHandle MH_ADD ;
69
+ private static final MethodHandle MH_ADD_EXACT ;
70
70
71
71
static {
72
72
try {
@@ -81,7 +81,7 @@ public class LayoutPath {
81
81
MethodType .methodType (void .class , MemorySegment .class , long .class , MemoryLayout .class ));
82
82
MH_SEGMENT_RESIZE = lookup .findStatic (LayoutPath .class , "resizeSegment" ,
83
83
MethodType .methodType (MemorySegment .class , MemorySegment .class ));
84
- MH_ADD = lookup .findStatic (Long .class , "sum " ,
84
+ MH_ADD_EXACT = lookup .findStatic (Math .class , "addExact " ,
85
85
MethodType .methodType (long .class , long .class , long .class ));
86
86
} catch (Throwable ex ) {
87
87
throw new ExceptionInInitializerError (ex );
@@ -244,15 +244,18 @@ private static long addScaledOffset(long base, long index, long stride, long bou
244
244
}
245
245
246
246
public MethodHandle offsetHandle () {
247
- MethodHandle mh = MethodHandles . insertArguments ( MH_ADD , 0 , offset ) ;
247
+ MethodHandle mh = MH_ADD_EXACT ;
248
248
for (int i = strides .length - 1 ; i >= 0 ; i --) {
249
249
MethodHandle collector = MethodHandles .insertArguments (MH_ADD_SCALED_OFFSET , 2 , strides [i ], bounds [i ]);
250
- // (J, ...) -> J to (J, J, ...) -> J
251
- // i.e. new coord is prefixed. Last coord will correspond to innermost layout
252
- mh = MethodHandles .collectArguments (mh , 0 , collector );
253
- }
254
-
255
- return mh ;
250
+ // (J, J, ...) -> J to (J, J, J, ...) -> J
251
+ // 1. the leading argument is the base offset (externally provided).
252
+ // 2. index arguments are added. The last index correspond to the innermost layout.
253
+ // 3. overflow can only occur at the outermost layer, due to the final addition with the base offset.
254
+ // This is because the layout API ensures (by construction) that all offsets generated from layout paths
255
+ // are always < Long.MAX_VALUE.
256
+ mh = MethodHandles .collectArguments (mh , 1 , collector );
257
+ }
258
+ return MethodHandles .insertArguments (mh , 1 , offset );
256
259
}
257
260
258
261
private MemoryLayout rootLayout () {
0 commit comments