Skip to content

Commit

Permalink
feat(impl): [core] MemoryUtil::asAddressArray use MemorySegment::elem…
Browse files Browse the repository at this point in the history
…ents
  • Loading branch information
squid233 committed Jan 30, 2025
1 parent db29133 commit af1583e
Showing 1 changed file with 6 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -659,18 +659,6 @@ public static double[] asDoubleArray(MemorySegment segment) {
return isNullPointer(segment) ? null : segment.toArray(JAVA_DOUBLE);
}

private static int checkArraySize(MemorySegment segment, String typeName, int elemSize) {
long length = segment.byteSize();
if ((length & (elemSize - 1)) != 0) {
throw new IllegalStateException(String.format("Segment size is not a multiple of %d. Size: %d", elemSize, length));
}
long arraySize = length / elemSize;
if (arraySize > (Integer.MAX_VALUE - 8)) {
throw new IllegalStateException(String.format("Segment is too large to wrap as %s. Size: %d", typeName, length));
}
return (int) arraySize;
}

/// Gets addresses from the given segment.
///
/// The returned segments are zero-length segments.
Expand All @@ -679,12 +667,9 @@ private static int checkArraySize(MemorySegment segment, String typeName, int el
/// @return the address array; or `null` if _`segment`_ is `NULL`
public static MemorySegment[] asAddressArray(MemorySegment segment) {
if (isNullPointer(segment)) return null;
int size = checkArraySize(segment, MemorySegment[].class.getSimpleName(), (int) ADDRESS.byteSize());
var arr = new MemorySegment[size];
for (int i = 0; i < size; i++) {
arr[i] = segment.getAtIndex(ADDRESS, i);
}
return arr;
return segment.elements(ADDRESS)
.map(s -> s.get(ADDRESS, 0))
.toArray(MemorySegment[]::new);
}

/// Gets strings from the given segment.
Expand All @@ -694,12 +679,9 @@ public static MemorySegment[] asAddressArray(MemorySegment segment) {
/// @return the string array; or `null` if _`segment`_ is `NULL`
public static String[] asStringArray(MemorySegment segment, Charset charset) {
if (isNullPointer(segment)) return null;
int size = checkArraySize(segment, String[].class.getSimpleName(), (int) ADDRESS.byteSize());
var arr = new String[size];
for (int i = 0; i < size; i++) {
arr[i] = segment.getAtIndex(STR_LAYOUT, i).getString(0L, charset);
}
return arr;
return segment.elements(ADDRESS)
.map(s -> s.get(STR_LAYOUT, 0).getString(0L, charset))
.toArray(String[]::new);
}

/// Gets strings encoded with UTF-8 from the given segment.
Expand Down

0 comments on commit af1583e

Please sign in to comment.