aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/utils/libservice/include/libservice/handle.hpp
blob: 1292090e150a23026a007cc2be3a3a718bc72c90 (plain) (blame)
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
73
74
75
76
77
78
79
80
/**
 * \file
 * \author Egor Tensin <Egor.Tensin@gmail.com>
 * \date 2015
 * \copyright This file is licensed under the terms of the MIT License.
 *            See LICENSE.txt for details.
 */

#pragma once

#include "common.hpp"

#include <Windows.h>

#include <memory>
#include <type_traits>
#include <utility>

namespace libservice
{
    class Handle
    {
    public:
        Handle() = default;

        explicit Handle(HANDLE raw)
            : m_impl(raw)
        { }

        Handle(Handle&& other) LIBSERVICE_NOEXCEPT
        {
            swap(other);
        }

        Handle& operator=(Handle other) LIBSERVICE_NOEXCEPT
        {
            swap(other);
            return *this;
        }

        explicit operator bool() const
        {
            return static_cast<bool>(m_impl);
        }

        explicit operator HANDLE() const
        {
            return m_impl.get();
        }

        void swap(Handle& other) LIBSERVICE_NOEXCEPT
        {
            using std::swap;
            swap(m_impl, other.m_impl);
        }

    private:
        struct Deleter
        {
            void operator()(HANDLE raw)
            {
                ::CloseHandle(raw);
            }
        };

        std::unique_ptr<std::remove_pointer<HANDLE>::type, Deleter> m_impl;

        Handle(const Handle&) = delete;
    };

    void swap(Handle& a, Handle& b) LIBSERVICE_NOEXCEPT;
}

namespace std
{
    template <>
    void swap<libservice::Handle>(
        libservice::Handle& a,
        libservice::Handle& b) LIBSERVICE_NOEXCEPT;
}