Skip to content

Instantly share code, notes, and snippets.

@wendigo
Last active June 20, 2023 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wendigo/c3584cf390c32a18e44cf65289d41af1 to your computer and use it in GitHub Desktop.
Save wendigo/c3584cf390c32a18e44cf65289d41af1 to your computer and use it in GitHub Desktop.
Java Foreign Linker + jextract
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));
}
}
}
}
}
}
@wendigo
Copy link
Author

wendigo commented Jun 20, 2023

Generating API from c header file using https://jdk.java.net/jextract/:

./bin/jextract --source --output target -l libsnappy -I/opt/homebrew/include -I/Library/Developer/CommandLineTools/Library\ SDKs/MacOSX.sdk/usr/include /opt/homebrew/include/snappy-c.h

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment