20 #ifndef RIPPLED_COMPRESSIONALGORITHMS_H_INCLUDED
21 #define RIPPLED_COMPRESSIONALGORITHMS_H_INCLUDED
23 #include <ripple/basics/contract.h>
32 namespace compression_algorithms {
42 template <
typename BufferFactory>
46 if (inSize > UINT32_MAX)
47 Throw<std::runtime_error>(
"lz4 compress: invalid size");
49 auto const outCapacity = LZ4_compressBound(inSize);
53 auto compressed = bf(outCapacity);
55 auto compressedSize = LZ4_compress_default(
56 reinterpret_cast<const char*
>(
in),
57 reinterpret_cast<char*
>(compressed),
60 if (compressedSize == 0)
61 Throw<std::runtime_error>(
"lz4 compress: failed");
63 return compressedSize;
80 int const inSize =
static_cast<int>(inSizeUnchecked);
81 int const decompressedSize =
static_cast<int>(decompressedSizeUnchecked);
84 Throw<std::runtime_error>(
"lz4Decompress: integer overflow (input)");
86 if (decompressedSize <= 0)
87 Throw<std::runtime_error>(
"lz4Decompress: integer overflow (output)");
89 if (LZ4_decompress_safe(
90 reinterpret_cast<const char*
>(
in),
91 reinterpret_cast<char*
>(decompressed),
93 decompressedSize) != decompressedSize)
94 Throw<std::runtime_error>(
"lz4Decompress: failed");
96 return decompressedSize;
107 template <
typename InputStream>
118 int copiedInSize = 0;
119 auto const currentBytes =
in.ByteCount();
124 while (
in.Next(
reinterpret_cast<void const**
>(&chunk), &chunkSize))
126 if (copiedInSize == 0)
128 if (chunkSize >= inSize)
130 copiedInSize = inSize;
133 compressed.
resize(inSize);
136 chunkSize = chunkSize < (inSize - copiedInSize)
138 : (inSize - copiedInSize);
140 std::copy(chunk, chunk + chunkSize, compressed.
data() + copiedInSize);
142 copiedInSize += chunkSize;
144 if (copiedInSize == inSize)
146 chunk = compressed.
data();
152 if (
in.ByteCount() > (currentBytes + copiedInSize))
153 in.BackUp(
in.ByteCount() - currentBytes - copiedInSize);
155 if ((copiedInSize == 0 && chunkSize < inSize) ||
156 (copiedInSize > 0 && copiedInSize != inSize))
157 Throw<std::runtime_error>(
"lz4 decompress: insufficient input size");
159 return lz4Decompress(chunk, inSize, decompressed, decompressedSize);
166 #endif // RIPPLED_COMPRESSIONALGORITHMS_H_INCLUDED