Merge pull request #67 from tripzero/trip
[profile/ivi/automotive-message-broker.git] / lib / superptr.hpp
1 #ifndef SUPERPTR_H_
2 #define SUPERPTR_H_
3
4 #include <glib.h>
5 #include <gio/gio.h>
6
7 #include <memory>
8
9 namespace amb {
10
11 template<typename T> struct traits;
12
13 template<>
14 struct traits<GVariant> {
15   struct delete_functor {
16         void operator()(GVariant * p) const {
17           if (p != nullptr)
18                 g_variant_unref(p);
19         }
20   };
21 };
22
23 template<>
24 struct traits<GError> {
25   struct delete_functor {
26         void operator()(GError * p) const {
27           if (p != nullptr)
28                 g_error_free(p);
29         }
30   };
31 };
32
33 template<>
34 struct traits<GDBusProxy> {
35   struct delete_functor {
36         void operator()(GDBusProxy * p) const {
37           if (p != nullptr)
38                 g_object_unref(p);
39         }
40   };
41 };
42
43 template<>
44 struct traits<GVariantIter> {
45   struct delete_functor {
46         void operator()(GVariantIter * p) const {
47           if (p != nullptr)
48                 g_variant_iter_free(p);
49         }
50   };
51 };
52
53 template<>
54 struct traits<gchar> {
55   struct delete_functor {
56         void operator()(gchar * p) const {
57           if (p != nullptr)
58                 g_free(p);
59         }
60   };
61 };
62
63 template <>
64 struct traits<GDBusConnection> {
65   struct delete_functor {
66         void operator()(GDBusConnection* p) const {
67           if (p != nullptr)
68                 g_dbus_connection_close_sync(p, nullptr, nullptr);
69         }
70   };
71 };
72
73 template<typename T> using super_ptr =
74                  ::std::unique_ptr<T, typename traits<T>::delete_functor>;
75
76 template<typename T> using gobject_ptr =
77                  ::std::unique_ptr<T , std::function<void(T*)> >;
78
79 template<typename T> super_ptr<T> make_super(T* t)
80 {
81   return super_ptr<T>(t);
82 }
83
84 template<typename T> ::std::unique_ptr<T> make_unique(T* t)
85 {
86   return ::std::unique_ptr<T>(t);
87 }
88
89 template<typename T> ::std::shared_ptr<T> make_shared(T* t)
90 {
91         return ::std::shared_ptr<T>(t);
92 }
93
94 template<typename T> gobject_ptr<T> make_gobject(T* t)
95 {
96         return gobject_ptr<T>(t, [](T *ptr) { if(ptr) g_object_unref(ptr);});
97 }
98
99 }
100 #endif