Skip to content

Instantly share code, notes, and snippets.

@redrabbit
Created December 19, 2017 11:00
Show Gist options
  • Save redrabbit/c913e24a2c0bf00405c53855203bec71 to your computer and use it in GitHub Desktop.
Save redrabbit/c913e24a2c0bf00405c53855203bec71 to your computer and use it in GitHub Desktop.
ERL_NIF_TERM
geef_object_zlib_inflate(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
ErlNifBinary bin;
char chunk[1024];
int error;
z_stream z;
z.zalloc = Z_NULL;
z.zfree = Z_NULL;
z.opaque = Z_NULL;
if (!enif_inspect_binary(env, argv[0], &bin))
return enif_make_badarg(env);
if (!geef_terminate_binary(&bin)) {
enif_release_binary(&bin);
return geef_oom(env);
}
z.avail_in = bin.size;
z.next_in = bin.data;
if (inflateInit(&z) != Z_OK)
return geef_oom(env);
do {
z.avail_out = 1024;
z.next_out = chunk;
error = inflate(&z, Z_NO_FLUSH);
switch (error) {
case Z_NEED_DICT:
case Z_DATA_ERROR:
case Z_MEM_ERROR:
inflateEnd(&z);
return geef_oom(env);
}
if (!enif_realloc_binary(&bin, z.total_out)) {
inflateEnd(&z);
return geef_error(env);
}
strcat(bin.data, chunk);
} while (error != Z_STREAM_END);
return enif_make_tuple3(env, atoms.ok, enif_make_binary(env, &bin), enif_make_ulong(env, z.total_in));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment