Add reference counting helper
authorKrzysztof Opasiak <k.opasiak@samsung.com>
Mon, 8 May 2017 20:39:28 +0000 (22:39 +0200)
committerKrzysztof Opasiak <k.opasiak@samsung.com>
Tue, 9 May 2017 11:40:23 +0000 (13:40 +0200)
Add a helper structure based on kref to simplify memory management.

Signed-off-by: Krzysztof Opasiak <k.opasiak@samsung.com>
src/util/uref.h [new file with mode: 0644]

diff --git a/src/util/uref.h b/src/util/uref.h
new file mode 100644 (file)
index 0000000..536b9e3
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef FAULTD_UREF_H
+#define FAULTD_UREF_H
+
+#include <assert.h>
+
+/* This is not thread safe! */
+struct uref {
+       unsigned refcnt;
+       void (*release)(struct uref *);
+};
+
+static inline void uref_init(struct uref *uref, void (*release)(struct uref *))
+{
+       uref->refcnt = 1;
+       uref->release = release;
+}
+
+static inline void uref_set_release(struct uref *uref,
+                                   void (*release)(struct uref *))
+{
+       assert(uref->refcnt > 0);
+       uref->release = release;
+}
+
+static inline void uref_get(struct uref *uref)
+{
+       assert(uref->refcnt > 0);
+       uref->refcnt++;
+}
+
+static inline void uref_sub(struct uref *uref, unsigned count)
+{
+       assert(uref->refcnt >= count);
+       uref->refcnt -= count;
+       if (uref->refcnt == 0 && uref->release)
+               uref->release(uref);
+}
+
+static inline void uref_put(struct uref *uref)
+{
+       uref_sub(uref, 1);
+}
+
+#endif /* FAULTD_UREF_H */