20 #ifndef RIPPLED_COMPRESSIONALGORITHMS_H_INCLUDED
21 #define RIPPLED_COMPRESSIONALGORITHMS_H_INCLUDED
23 #include <ripple/basics/contract.h>
29 namespace compression_algorithms {
37 Throw<std::runtime_error>(message);
48 template <
typename BufferFactory>
52 if (inSize > UINT32_MAX)
53 doThrow(
"lz4 compress: invalid size");
55 auto const outCapacity = LZ4_compressBound(inSize);
59 auto compressed = bf(outCapacity);
61 auto compressedSize = LZ4_compress_default(
62 reinterpret_cast<const char*
>(
in),
63 reinterpret_cast<char*
>(compressed),
66 if (compressedSize == 0)
67 doThrow(
"lz4 compress: failed");
69 return compressedSize;
86 auto ret = LZ4_decompress_safe(
87 reinterpret_cast<const char*
>(
in),
88 reinterpret_cast<char*
>(decompressed),
92 if (ret <= 0 || ret != decompressedSize)
93 doThrow(
"lz4 decompress: failed");
95 return decompressedSize;
106 template <
typename InputStream>
117 int copiedInSize = 0;
118 auto const currentBytes =
in.ByteCount();
123 while (
in.Next(
reinterpret_cast<void const**
>(&chunk), &chunkSize))
125 if (copiedInSize == 0)
127 if (chunkSize >= inSize)
129 copiedInSize = inSize;
132 compressed.
resize(inSize);
135 chunkSize = chunkSize < (inSize - copiedInSize)
137 : (inSize - copiedInSize);
139 std::copy(chunk, chunk + chunkSize, compressed.
data() + copiedInSize);
141 copiedInSize += chunkSize;
143 if (copiedInSize == inSize)
145 chunk = compressed.
data();
151 if (
in.ByteCount() > (currentBytes + copiedInSize))
152 in.BackUp(
in.ByteCount() - currentBytes - copiedInSize);
154 if ((copiedInSize == 0 && chunkSize < inSize) ||
155 (copiedInSize > 0 && copiedInSize != inSize))
156 doThrow(
"lz4 decompress: insufficient input size");
158 return lz4Decompress(chunk, inSize, decompressed, decompressedSize);
165 #endif // RIPPLED_COMPRESSIONALGORITHMS_H_INCLUDED