Last active
June 20, 2023 13:25
-
-
Save wendigo/c3584cf390c32a18e44cf65289d41af1 to your computer and use it in GitHub Desktop.
Java Foreign Linker + jextract
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.foreign.Arena; | |
import java.lang.foreign.MemorySegment; | |
import static io.airlift.slice.Preconditions.verify; | |
import static io.airlift.slice.snappy.snappy_c_h.SNAPPY_OK; | |
import static java.lang.foreign.ValueLayout.JAVA_CHAR; | |
import static java.lang.foreign.ValueLayout.JAVA_LONG; | |
public class SnappyTest | |
{ | |
public static void main(String[] args) throws Throwable | |
{ | |
try (var arena = Arena.openConfined()) { | |
String data = "Hello World!".repeat(10000 / 15); | |
long length = data.length() + 1; | |
long maxCompressedSize = snappy_max_compressed_length(length); | |
MemorySegment input = arena.allocate(length); | |
input.setUtf8String(0, data); | |
MemorySegment output = arena.allocate(maxCompressedSize); | |
MemorySegment retSize = arena.allocate(JAVA_LONG, maxCompressedSize); | |
if (snappy_compress(input, input.byteSize(), output, retSize) == SNAPPY_OK()) { | |
long actualCompressedSize = retSize.get(JAVA_LONG, 0); | |
MemorySegment compressedData = output.asSlice(0, actualCompressedSize); | |
if (snappy_uncompressed_length(compressedData, compressedData.byteSize(), retSize) == SNAPPY_OK()) { | |
long actualUncompressedSize = retSize.get(JAVA_LONG, 0); | |
verify(actualUncompressedSize == length); | |
MemorySegment uncompressedOutput = arena.allocate(actualUncompressedSize); | |
if (snappy_uncompress(compressedData, compressedData.byteSize(), uncompressedOutput, retSize) == SNAPPY_OK()) { | |
verify(uncompressedOutput.getUtf8String(0).equals(data)); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Generating API from c header file using https://jdk.java.net/jextract/: