-module(regular_ffi). -export([ compress/1, decompress/1, new_compression_context/0, compress_chunk/2, finish_compress_frame/2, new_decompression_context/0, decompress_chunk/2, finish_decompress_frame/2 ]). -spec compress(Data :: bitstring()) -> {ok, binary()} | {error, nil}. compress(Data) -> try zstd:compress(Data) of Compressed -> {ok, iolist_to_binary(Compressed)} catch _:_ -> {error, nil} end. -spec decompress(Data :: bitstring()) -> {ok, binary()} | {error, nil}. decompress(Data) -> try zstd:decompress(Data) of Decompressed -> {ok, iolist_to_binary(Decompressed)} catch _:_ -> {error, nil} end. -spec new_compression_context() -> zstd:context(). new_compression_context() -> {ok, Context} = zstd:context(compress), Context. -spec compress_chunk(Context :: zstd:context(), Chunk :: bitstring()) -> {ok, {compression_finished, binary()}} | {ok, {compression_unfinished, binary(), binary()}} | {error, nil}. compress_chunk(Context, Chunk) -> try zstd:stream(Context, Chunk) of {continue, Remainder, Output} -> {ok, {compression_unfinished, Output, iolist_to_binary(Remainder)}}; {continue, Output} -> {ok, {compression_finished, Output}} catch _:_ -> {error, nil} end. -spec finish_compress_frame(Context :: zstd:context(), Chunk :: bitstring()) -> {ok, binary()} | {error, nil}. finish_compress_frame(Context, Chunk) -> try zstd:finish(Context, Chunk) of {done, Output} -> {ok, iolist_to_binary(Output)} catch _:_ -> {error, nil} end. -spec new_decompression_context() -> zstd:context(). new_decompression_context() -> {ok, Context} = zstd:context(decompress), Context. -spec decompress_chunk(Context :: zstd:context(), Chunk :: bitstring()) -> {ok, {decompression_finished, binary()}} | {ok, {decompression_unfinished, binary(), binary()}} | {error, nil}. decompress_chunk(Context, Chunk) -> try zstd:stream(Context, Chunk) of {continue, Remainder, Output} -> {ok, {decompression_unfinished, Output, iolist_to_binary(Remainder)}}; {continue, Output} -> {ok, {decompression_finished, Output}} catch _:_ -> {error, nil} end. -spec finish_decompress_frame(Context :: zstd:context(), Chunk :: bitstring()) -> {ok, binary()} | {error, nil}. finish_decompress_frame(Context, Chunk) -> try zstd:finish(Context, Chunk) of {done, Output} -> {ok, iolist_to_binary(Output)} catch _:_ -> {error, nil} end.