summaryrefslogtreecommitdiff
path: root/src/sockutils.hh
blob: 9ad85ab07adc84471640099ec1130e3fb8b69ea9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#ifndef SOCKUTILS_HH
#define SOCKUTILS_HH

namespace stuff {

bool make_nonblocking(int sock);

bool calc_timeout(const struct timeval* target, struct timeval* timeout);

class sockguard {
public:
    sockguard()
        : sock_(-1) {
    }
    explicit sockguard(int sock)
        : sock_(sock) {
    }
    sockguard(sockguard&& sock)
        : sock_(sock.sock_) {
    }
    ~sockguard() {
        reset();
    }
    sockguard& operator=(sockguard&& sock) {
        reset(sock.sock_);
        return *this;
    }
    void reset() {
        if (sock_ != -1) {
            close(sock_);
            sock_ = -1;
        }
    }
    void reset(int sock) {
        if (sock_ != -1 && sock_ != sock) {
            close(sock_);
        }
        sock_ = sock;
    }
    void swap(sockguard& sock) {
        auto tmp = sock.sock_;
        sock.sock_ = sock_;
        sock_ = tmp;
    }
    operator bool() const {
        return sock_ != -1;
    }
    int get() const {
        return sock_;
    }
    int release() {
        auto ret = sock_;
        sock_ = -1;
        return ret;
    }

protected:
    sockguard(const sockguard&) = delete;
    sockguard& operator=(const sockguard&) = delete;
    static void close(int sock);

private:
    int sock_;
};

}  // namespace stuff

namespace std {
void swap(stuff::sockguard& s1, stuff::sockguard& s2) noexcept;
}  // namespace std

#endif /* SOCKUTILS_HH */