92 const std::string& dst_tmp,
94# if defined(LOGIT_HAS_ZLIB)
95 std::ifstream in(src.c_str(), std::ios::binary);
96 if (!in)
return false;
100 gzFile out = gzopen(dst_tmp.c_str(), mode);
101 if (!out)
return false;
102 gzbuffer(out, 256 * 1024);
104 std::vector<char> buf(256 * 1024);
106 in.read(&buf[0], buf.size());
107 std::streamsize got = in.gcount();
109 int written = gzwrite(out, &buf[0],
static_cast<unsigned>(got));
110 if (written == 0) { gzclose(out);
return false; }
113 return gzclose(out) == Z_OK;
115 (void)src; (void)dst_tmp; (void)level;
return false;
125 const std::string& dst_tmp,
127# if defined(LOGIT_HAS_ZSTD)
128 std::ifstream in(src.c_str(), std::ios::binary);
129 std::ofstream out(dst_tmp.c_str(), std::ios::binary | std::ios::trunc);
130 if (!in || !out)
return false;
132 ZSTD_CCtx* cctx = ZSTD_createCCtx();
133 if (!cctx)
return false;
134 ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel,
clamp_level(level, 1, 19));
136 const size_t inChunk = ZSTD_CStreamInSize();
137 const size_t outChunk = ZSTD_CStreamOutSize();
138 std::vector<char> inBuf(inChunk), outBuf(outChunk);
141 in.read(&inBuf[0], inBuf.size());
142 size_t rd =
static_cast<size_t>(in.gcount());
143 ZSTD_inBuffer zin = { &inBuf[0], rd, 0 };
144 const int last = in.eof() ? 1 : 0;
146 while (zin.pos < zin.size || last) {
147 ZSTD_outBuffer zout = { &outBuf[0], outBuf.size(), 0 };
149 ? ZSTD_compressStream2(cctx, &zout, &zin, ZSTD_e_end)
150 : ZSTD_compressStream2(cctx, &zout, &zin, ZSTD_e_continue);
151 if (ZSTD_isError(ret)) { ZSTD_freeCCtx(cctx);
return false; }
152 out.write(&outBuf[0],
static_cast<std::streamsize
>(zout.pos));
153 if (!out) { ZSTD_freeCCtx(cctx);
return false; }
154 if (last && ret == 0 && zin.pos == zin.size) {
159 if (!last && zin.pos == zin.size)
break;
163 (void)src; (void)dst_tmp; (void)level;
return false;
173 const std::string& cmd_tpl,
175 if (cmd_tpl.empty())
return false;
176 std::string cmd = cmd_tpl;
177 size_t pos = cmd.find(
"{file}");
178 if (pos != std::string::npos) cmd.replace(pos, 6,
"\"" + src +
"\"");
179 pos = cmd.find(
"{level}");
180 if (pos != std::string::npos) cmd.replace(pos, 7, std::to_string(level));
181 return std::system(cmd.c_str()) == 0;
185 const std::string& src,
187 const std::string& external_cmd) {
193 std::string tmp = dst +
".tmp";
197 if (!ok) { std::remove(tmp.c_str());
return false; }
198 if (std::rename(tmp.c_str(), dst.c_str()) != 0) { std::remove(tmp.c_str());
return false; }
199 std::remove(src.c_str());
bool compress_file(CompressType type, const std::string &src, int level, const std::string &external_cmd)
Compress a file using the specified compression type.