From a6ab2adf86fd52871b5d8000effe55bfe4704efd Mon Sep 17 00:00:00 2001 From: sowle Date: Mon, 5 Aug 2019 17:07:10 +0300 Subject: [PATCH] zlib_helper::pack() fixed for small amount of data + unit test added (resolves #62) --- contrib/epee/include/zlib_helper.h | 13 +++++-------- tests/unit_tests/zlib_helper.cpp | 25 +++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 8 deletions(-) create mode 100644 tests/unit_tests/zlib_helper.cpp diff --git a/contrib/epee/include/zlib_helper.h b/contrib/epee/include/zlib_helper.h index 86f5f2c0..bbd5044a 100644 --- a/contrib/epee/include/zlib_helper.h +++ b/contrib/epee/include/zlib_helper.h @@ -42,9 +42,8 @@ namespace zlib_helper int ret = deflateInit(&zstream, Z_DEFAULT_COMPRESSION); if(target.size()) { - - - result_packed_buff.resize(target.size()*2, 'X'); + size_t estimated_output_size_max = deflateBound(&zstream, target.size()); + result_packed_buff.resize(estimated_output_size_max, 'X'); zstream.next_in = (Bytef*)target.data(); zstream.avail_in = (uInt)target.size(); @@ -52,12 +51,10 @@ namespace zlib_helper zstream.avail_out = (uInt)result_packed_buff.size(); ret = deflate(&zstream, Z_FINISH); - CHECK_AND_ASSERT_MES(ret>=0, false, "Failed to deflate. err = " << ret); + // as we allocated enough room for a signel pass avail_out should not be zero + CHECK_AND_ASSERT_MES(ret == Z_STREAM_END && zstream.avail_out != 0, false, "Failed to deflate. err = " << ret); - if(result_packed_buff.size() != zstream.avail_out) - result_packed_buff.resize(result_packed_buff.size()-zstream.avail_out); - - + result_packed_buff.resize(result_packed_buff.size() - zstream.avail_out); result_packed_buff.erase(0, 2); } diff --git a/tests/unit_tests/zlib_helper.cpp b/tests/unit_tests/zlib_helper.cpp new file mode 100644 index 00000000..d1aafe16 --- /dev/null +++ b/tests/unit_tests/zlib_helper.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2019 Zano Project +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. +#include "gtest/gtest.h" +#include "epee/include/misc_log_ex.h" +#include "epee/include/zlib_helper.h" +#include "crypto/crypto.h" + +TEST(zlib_helper, test_0) +{ + for (size_t len = 0; len <= 1024; ++len) + { + for(size_t iteration = 0; iteration < 4; ++iteration) + { + std::string original(len, 'X'); + if (len > 0) + crypto::generate_random_bytes(len, &original.front()); + + std::string result, decoded; + ASSERT_TRUE(epee::zlib_helper::pack(original, result)); + ASSERT_TRUE(epee::zlib_helper::unpack(result, decoded)); + ASSERT_EQ(original, decoded); + } + } +}