blob: e9e2a0ca907ed08d1e19480731393f2e98924095 [file] [log] [blame]
Brad Bishop14631dc2017-06-14 22:34:03 -04001#pragma once
2
3#include <memory>
4#include <systemd/sd-event.h>
5
6// TODO: openbmc/openbmc#1720 - add error handling for sd_event API failures
7
8namespace sdevent
9{
10namespace source
11{
12
13using SourcePtr = sd_event_source*;
14
15namespace details
16{
17
18/** @brief unique_ptr functor to release a source reference. */
19struct SourceDeleter
20{
21 void operator()(sd_event_source* ptr) const
22 {
23 deleter(ptr);
24 }
25
26 decltype(&sd_event_source_unref) deleter = sd_event_source_unref;
27};
28
29/* @brief Alias 'source' to a unique_ptr type for auto-release. */
30using source = std::unique_ptr<sd_event_source, SourceDeleter>;
31
32} // namespace details
33
34/** @class Source
35 * @brief Provides C++ bindings to the sd_event_source* functions.
36 */
37class Source
38{
39 public:
40 /* Define all of the basic class operations:
41 * Not allowed:
42 * - Default constructor to avoid nullptrs.
43 * - Copy operations due to internal unique_ptr.
44 * Allowed:
45 * - Move operations.
46 * - Destructor.
47 */
48 Source() = delete;
49 Source(const Source&) = delete;
50 Source& operator=(const Source&) = delete;
51 Source(Source&&) = default;
52 Source& operator=(Source&&) = default;
53 ~Source() = default;
54
55 /** @brief Conversion constructor from 'SourcePtr'.
56 *
57 * Increments ref-count of the source-pointer and releases it
58 * when done.
59 */
60 explicit Source(SourcePtr s) : src(sd_event_source_ref(s)) {}
61
62 /** @brief Constructor for 'source'.
63 *
64 * Takes ownership of the source-pointer and releases it when done.
65 */
66 Source(SourcePtr s, std::false_type) : src(s) {}
67
68 /** @brief Check if source contains a real pointer. (non-nullptr). */
69 explicit operator bool() const
70 {
71 return bool(src);
72 }
73
74 /** @brief Test whether or not the source can generate events. */
75 auto enabled()
76 {
77 int enabled;
78 sd_event_source_get_enabled(src.get(), &enabled);
79 return enabled;
80 }
81
82 /** @brief Allow the source to generate events. */
83 void enable(int enable)
84 {
85 sd_event_source_set_enabled(src.get(), enable);
86 }
87
88 private:
89 details::source src;
90};
91} // namespace source
92} // namespace sdevent