From 1cd6846a0d677c2a4d9f3cb57f5883a7718fd6d2 Mon Sep 17 00:00:00 2001 From: Gary Miguel Date: Sat, 9 Mar 2024 16:50:18 -0800 Subject: [PATCH] return error for src too small (#130) Change-Id: I745f447fb22a843257d1ae211a130cd39dad4ccc --- src/decompress.cpp | 10 +++++----- src/decompress.hpp | 1 + src/test/decompress_test.cpp | 7 +++++-- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/decompress.cpp b/src/decompress.cpp index ba996bf..9a986f4 100644 --- a/src/decompress.cpp +++ b/src/decompress.cpp @@ -54,11 +54,11 @@ auto decompress(std::span src, std::span dst) if (len != static_cast(~nlen)) { return DecompressStatus::NoCompressionLenMismatch; } - // TODO: should we return an error instead of assert? - assert( - std::cmp_greater_equal( - src_bits.size(), std::size_t{len} * CHAR_BIT) and - "not enough bits in src"); + // Surprisingly size() does not return size_t on libstdc++ 13, hence cast. + if (static_cast(src_bits.size()) < + std::size_t{len} * std::size_t{CHAR_BIT}) { + return DecompressStatus::SrcTooSmall; + } if (dst.size() < len) { return DecompressStatus::DstTooSmall; diff --git a/src/decompress.hpp b/src/decompress.hpp index e13b57a..07f88f4 100644 --- a/src/decompress.hpp +++ b/src/decompress.hpp @@ -17,6 +17,7 @@ enum class DecompressStatus : std::uint8_t InvalidBlockHeader, NoCompressionLenMismatch, DstTooSmall, + SrcTooSmall, }; namespace detail { diff --git a/src/test/decompress_test.cpp b/src/test/decompress_test.cpp index 7a9c1f6..c80083f 100644 --- a/src/test/decompress_test.cpp +++ b/src/test/decompress_test.cpp @@ -116,10 +116,13 @@ auto main(int, char* argv[]) -> int std::array dst_array{}; const std::span dst_too_small{ dst_array.data(), dst_array.size() - 1}; - const auto status_too_small = decompress(src, dst_too_small); - expect(status_too_small == DecompressStatus::DstTooSmall); + const auto status_dst_too_small = decompress(src, dst_too_small); + expect(status_dst_too_small == DecompressStatus::DstTooSmall); const std::span dst{dst_array}; + const auto status_src_too_small = decompress(src.subspan(0, 5), dst); + expect(status_src_too_small == DecompressStatus::SrcTooSmall); + const auto status = decompress(src, dst); expect(status == DecompressStatus::Success); expect(std::ranges::equal(dst, expected));