Skip to content

Commit

Permalink
Merge pull request #10 from pmembrey/master
Browse files Browse the repository at this point in the history
snappy should be able to decompress an empty binary
  • Loading branch information
dch committed Jan 6, 2015
2 parents 868243b + 73f2014 commit 1d29d69
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
19 changes: 19 additions & 0 deletions c_src/snappy_nif.cc
Expand Up @@ -143,6 +143,16 @@ snappy_compress_erl(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
return enif_make_badarg(env);
}

// If empty binary has been provided, return an empty binary.
// Snappy will do this in any case, so might as well skip the
// overhead...
if(input.size == 0) {
ErlNifBinary empty;
// init empty;
memset(&empty,0,sizeof(ErlNifBinary));
return make_ok(env, enif_make_binary(env,&empty));
}

try {
snappy::ByteArraySource source(SC_PTR(input.data), input.size);
SnappyNifSink sink(env);
Expand All @@ -167,6 +177,15 @@ snappy_decompress_erl(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
return enif_make_badarg(env);
}

// Check that the binary is not empty
if(bin.size == 0) {
// Snappy library cannot decompress an empty binary - although
// it will unfortunately let you compress one. If an empty binary
// has been passed - send an empty binary back.
memset(&ret,0,sizeof(ErlNifBinary));
return make_ok(env, enif_make_binary(env,&ret));
}

try {
if(!snappy::GetUncompressedLength(SC_PTR(bin.data), bin.size, &len)) {
return make_error(env, "data_not_compressed");
Expand Down
33 changes: 33 additions & 0 deletions test/snappy_tests.erl
Expand Up @@ -72,3 +72,36 @@ decompression() ->
?assertEqual({ok, BigData}, snappy:decompress(Compressed3)),
ok.

check_double_decompress_doesnt_cause_segault_test() ->
% Try to decompress an empty binary
?assertMatch({ok,<<>>}, snappy:decompress(<<>>)),
% And once more...
?assertMatch({ok,<<>>}, snappy:decompress(<<>>)),
ok.

check_double_compress_doesnt_cause_segault_test() ->
% Try to compress an empty binary
?assertMatch({ok,<<>>},snappy:compress(<<>>)),
% And once more...
?assertMatch({ok,<<>>},snappy:compress(<<>>)),
ok.

can_compress_and_decompress_empty_binary_test() ->
% Try to compress an empty binary...
{ok, Compressed} = snappy:compress(<<>>),
% Try to decompress the result of the compression...
{ok, Decompressed} = snappy:decompress(Compressed),
ok.

can_compress_an_empty_binary_test() ->
% Try to compress an empty binary...
{ok, Compressed} = snappy:compress(<<>>),
% Check an empty binary was returned
?assertMatch(Compressed,<<>>),
ok.

can_decompress_an_empty_binary_test() ->
% Try to decompress an empty binary
{ok, Decompressed} = snappy:decompress(<<>>),
?assertMatch(Decompressed,<<>>),
ok.

0 comments on commit 1d29d69

Please sign in to comment.