2016-04-26 21:40:43 +00:00
|
|
|
#include <unistd.h>
|
2017-02-28 23:49:04 +00:00
|
|
|
#include <zstd.h>
|
2016-04-26 21:40:43 +00:00
|
|
|
#include <vector>
|
|
|
|
#include <stdexcept>
|
|
|
|
|
|
|
|
|
|
|
|
int main(int argc, char ** argv)
|
|
|
|
{
|
2017-04-01 07:20:54 +00:00
|
|
|
bool compress = argc == 1;
|
2016-04-26 21:40:43 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
const size_t size = 1048576;
|
|
|
|
std::vector<char> src_buf(size);
|
|
|
|
std::vector<char> dst_buf;
|
2016-04-26 21:40:43 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
size_t pos = 0;
|
|
|
|
while (true)
|
|
|
|
{
|
|
|
|
ssize_t read_res = read(STDIN_FILENO, &src_buf[pos], size - pos);
|
|
|
|
if (read_res < 0)
|
|
|
|
throw std::runtime_error("Cannot read from stdin");
|
|
|
|
if (read_res == 0)
|
|
|
|
break;
|
|
|
|
pos += read_res;
|
|
|
|
}
|
2016-04-26 21:40:43 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
src_buf.resize(pos);
|
2016-04-26 21:40:43 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
size_t zstd_res;
|
2016-04-26 21:40:43 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
if (compress)
|
|
|
|
{
|
|
|
|
dst_buf.resize(ZSTD_compressBound(src_buf.size()));
|
2016-04-26 21:40:43 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
zstd_res = ZSTD_compress(
|
|
|
|
&dst_buf[0],
|
|
|
|
dst_buf.size(),
|
|
|
|
&src_buf[0],
|
|
|
|
src_buf.size(),
|
|
|
|
1);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
dst_buf.resize(size);
|
2016-04-26 21:40:43 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
zstd_res = ZSTD_decompress(
|
|
|
|
&dst_buf[0],
|
|
|
|
dst_buf.size(),
|
|
|
|
&src_buf[0],
|
|
|
|
src_buf.size());
|
|
|
|
}
|
2016-04-26 21:40:43 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
if (ZSTD_isError(zstd_res))
|
|
|
|
throw std::runtime_error(ZSTD_getErrorName(zstd_res));
|
2016-04-26 21:40:43 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
dst_buf.resize(zstd_res);
|
2016-04-26 21:40:43 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
pos = 0;
|
|
|
|
while (pos < dst_buf.size())
|
|
|
|
{
|
|
|
|
ssize_t write_res = write(STDOUT_FILENO, &dst_buf[pos], dst_buf.size());
|
|
|
|
if (write_res <= 0)
|
|
|
|
throw std::runtime_error("Cannot write to stdout");
|
|
|
|
pos += write_res;
|
|
|
|
}
|
2016-04-26 21:40:43 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
return 0;
|
2016-04-26 21:40:43 +00:00
|
|
|
}
|