make Finally more local

no need for function<> with c++17 deduction. this saves allocations and virtual
calls, but has the same semantics otherwise. not going through function has the
side effect of giving compilers more insight into the cleanup code, so we need a
few local warning disables.
This commit is contained in:
pennae 2021-12-31 00:50:23 +01:00
parent 47baa9d43c
commit 8e2eaaaf69
2 changed files with 11 additions and 11 deletions

View file

@ -1,14 +1,13 @@
#pragma once
#include <functional>
/* A trivial class to run a function at the end of a scope. */
template<typename Fn>
class Finally
{
private:
std::function<void()> fun;
Fn fun;
public:
Finally(std::function<void()> fun) : fun(fun) { }
Finally(Fn fun) : fun(std::move(fun)) { }
~Finally() { fun(); }
};

View file

@ -682,7 +682,14 @@ std::string drainFD(int fd, bool block, const size_t reserveSize)
void drainFD(int fd, Sink & sink, bool block)
{
int saved;
// silence GCC maybe-uninitialized warning in finally
int saved = 0;
if (!block) {
saved = fcntl(fd, F_GETFL);
if (fcntl(fd, F_SETFL, saved | O_NONBLOCK) == -1)
throw SysError("making file descriptor non-blocking");
}
Finally finally([&]() {
if (!block) {
@ -691,12 +698,6 @@ void drainFD(int fd, Sink & sink, bool block)
}
});
if (!block) {
saved = fcntl(fd, F_GETFL);
if (fcntl(fd, F_SETFL, saved | O_NONBLOCK) == -1)
throw SysError("making file descriptor non-blocking");
}
std::vector<unsigned char> buf(64 * 1024);
while (1) {
checkInterrupt();