20 #ifndef RIPPLED_COMPRESSIONALGORITHMS_H_INCLUDED
21 #define RIPPLED_COMPRESSIONALGORITHMS_H_INCLUDED
23 #include <ripple/basics/contract.h>
29 namespace compression_algorithms {
36 Throw<std::runtime_error>(message);
47 template<
typename BufferFactory>
52 if (inSize > UINT32_MAX)
53 doThrow(
"lz4 compress: invalid size");
55 auto const outCapacity = LZ4_compressBound(inSize);
58 auto compressed = bf(outCapacity);
60 auto compressedSize = LZ4_compress_default(
61 reinterpret_cast<const char*
>(
in),
62 reinterpret_cast<char*
>(compressed),
65 if (compressedSize == 0)
66 doThrow(
"lz4 compress: failed");
68 return compressedSize;
83 auto ret = LZ4_decompress_safe(
reinterpret_cast<const char*
>(
in),
84 reinterpret_cast<char*
>(decompressed), inSize, decompressedSize);
86 if (ret <= 0 || ret != decompressedSize)
87 doThrow(
"lz4 decompress: failed");
89 return decompressedSize;
100 template<
typename InputStream>
108 int copiedInSize = 0;
109 auto const currentBytes =
in.ByteCount();
114 while (
in.Next(
reinterpret_cast<void const**
>(&chunk), &chunkSize))
116 if (copiedInSize == 0)
118 if (chunkSize >= inSize)
120 copiedInSize = inSize;
123 compressed.
resize(inSize);
126 chunkSize = chunkSize < (inSize - copiedInSize) ? chunkSize : (inSize - copiedInSize);
128 std::copy(chunk, chunk + chunkSize, compressed.
data() + copiedInSize);
130 copiedInSize += chunkSize;
132 if (copiedInSize == inSize)
134 chunk = compressed.
data();
140 if (
in.ByteCount() > (currentBytes + copiedInSize))
141 in.BackUp(
in.ByteCount() - currentBytes - copiedInSize);
143 if ((copiedInSize == 0 && chunkSize < inSize) || (copiedInSize > 0 && copiedInSize != inSize))
144 doThrow(
"lz4 decompress: insufficient input size");
146 return lz4Decompress(chunk, inSize, decompressed, decompressedSize);
153 #endif //RIPPLED_COMPRESSIONALGORITHMS_H_INCLUDED