#ifndef __LIBUTILPP_HH__
#define __LIBUTILPP_HH__
#include <sys/nv.h>
#include <libutil.h>
#include <netdb.h>
#include <unistd.h>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <memory>
namespace freebsd {
struct fclose_deleter {
void operator() (std::FILE *fp) const
{
std::fclose(fp);
}
};
using FILE_up = std::unique_ptr<std::FILE, fclose_deleter>;
struct freeaddrinfo_deleter {
void operator() (struct addrinfo *ai) const
{
freeaddrinfo(ai);
}
};
using addrinfo_up = std::unique_ptr<addrinfo, freeaddrinfo_deleter>;
class fd_up {
public:
fd_up() : fd(-1) {}
fd_up(int _fd) : fd(_fd) {}
fd_up(fd_up &&other) : fd(other.release()) {}
fd_up(fd_up const &) = delete;
~fd_up() { reset(); }
int get() const { return (fd); }
int release()
{
int oldfd = fd;
fd = -1;
return (oldfd);
}
void reset(int newfd = -1)
{
if (fd >= 0)
close(fd);
fd = newfd;
}
fd_up &operator=(fd_up &&other) noexcept
{
if (this == &other)
return *this;
reset(other.release());
return *this;
}
fd_up &operator=(fd_up const &) = delete;
fd_up &operator=(int newfd)
{
reset(newfd);
return *this;
}
explicit operator bool() const { return fd >= 0; }
operator int() const { return fd; }
private:
int fd;
};
template <class T>
struct free_deleter {
void operator() (T *p) const
{
std::free(p);
}
};
template <class T>
using malloc_up = std::unique_ptr<T, free_deleter<T>>;
struct nvlist_deleter {
void operator() (nvlist_t *nvl) const
{
nvlist_destroy(nvl);
}
};
using nvlist_up = std::unique_ptr<nvlist_t, nvlist_deleter>;
class pidfile {
public:
pidfile() = default;
pidfile(struct pidfh *_pfh) : pfh(_pfh) {}
pidfile(pidfile &&other) : pfh(other.release()) {}
pidfile(pidfile const &) = delete;
~pidfile() { reset(); }
struct pidfh *release()
{
struct pidfh *oldpfh = pfh;
pfh = nullptr;
return (oldpfh);
}
void reset(struct pidfh *newpfh = nullptr)
{
if (pfh != nullptr)
pidfile_remove(pfh);
pfh = newpfh;
}
int write()
{
return (pidfile_write(pfh));
}
int close()
{
int rv = pidfile_close(pfh);
if (rv == 0)
pfh = nullptr;
return (rv);
}
int fileno()
{
return (pidfile_fileno(pfh));
}
pidfile &operator=(pidfile &&other) noexcept
{
if (this == &other)
return *this;
reset(other.release());
return *this;
}
pidfile &operator=(pidfile const &) = delete;
pidfile &operator=(struct pidfh *newpfh)
{
reset(newpfh);
return *this;
}
explicit operator bool() const { return pfh != nullptr; }
private:
struct pidfh *pfh = nullptr;
};
std::string stringf(const char *fmt, ...) __printflike(1, 2);
std::string stringf(const char *fmt, std::va_list ap);
}
#endif