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 auto ret = LZ4_decompress_safe(
81 reinterpret_cast<const char*
>(
in),
82 reinterpret_cast<char*
>(decompressed),
86 if (ret <= 0 || ret != decompressedSize)
87 Throw<std::runtime_error>(
"lz4 decompress: failed");
89 return decompressedSize;
100 template <
typename InputStream>
111 int copiedInSize = 0;
112 auto const currentBytes =
in.ByteCount();
117 while (
in.Next(
reinterpret_cast<void const**
>(&chunk), &chunkSize))
119 if (copiedInSize == 0)
121 if (chunkSize >= inSize)
123 copiedInSize = inSize;
126 compressed.
resize(inSize);
129 chunkSize = chunkSize < (inSize - copiedInSize)
131 : (inSize - copiedInSize);
133 std::copy(chunk, chunk + chunkSize, compressed.
data() + copiedInSize);
135 copiedInSize += chunkSize;
137 if (copiedInSize == inSize)
139 chunk = compressed.
data();
145 if (
in.ByteCount() > (currentBytes + copiedInSize))
146 in.BackUp(
in.ByteCount() - currentBytes - copiedInSize);
148 if ((copiedInSize == 0 && chunkSize < inSize) ||
149 (copiedInSize > 0 && copiedInSize != inSize))
150 Throw<std::runtime_error>(
"lz4 decompress: insufficient input size");
152 return lz4Decompress(chunk, inSize, decompressed, decompressedSize);
159 #endif // RIPPLED_COMPRESSIONALGORITHMS_H_INCLUDED