2 * lib/object.c Generic Cacheable Object
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation version 2.1
9 * Copyright (c) 2003-2008 Thomas Graf <tgraf@suug.ch>
14 * @defgroup object Object
18 #include <netlink-local.h>
19 #include <netlink/netlink.h>
20 #include <netlink/cache.h>
21 #include <netlink/object.h>
22 #include <netlink/utils.h>
24 static inline struct nl_object_ops *obj_ops(struct nl_object *obj)
33 * @name Object Creation/Deletion
38 * Allocate a new object of kind specified by the operations handle
39 * @arg ops cache operations handle
40 * @return The new object or NULL
42 struct nl_object *nl_object_alloc(struct nl_object_ops *ops)
44 struct nl_object *new;
46 if (ops->oo_size < sizeof(*new))
49 new = calloc(1, ops->oo_size);
54 nl_init_list_head(&new->ce_list);
57 if (ops->oo_constructor)
58 ops->oo_constructor(new);
60 NL_DBG(4, "Allocated new object %p\n", new);
65 struct nl_derived_object {
71 * Allocate a new object and copy all data from an existing object
72 * @arg obj object to inherite data from
73 * @return The new object or NULL.
75 struct nl_object *nl_object_clone(struct nl_object *obj)
77 struct nl_object *new;
78 struct nl_object_ops *ops = obj_ops(obj);
79 int doff = offsetof(struct nl_derived_object, data);
82 new = nl_object_alloc(ops);
86 size = ops->oo_size - doff;
90 new->ce_ops = obj->ce_ops;
91 new->ce_msgtype = obj->ce_msgtype;
94 memcpy((void *)new + doff, (void *)obj + doff, size);
97 if (ops->oo_clone(new, obj) < 0) {
101 } else if (size && ops->oo_free_data)
108 * Free a cacheable object
109 * @arg obj object to free
111 * @return 0 or a negative error code.
113 void nl_object_free(struct nl_object *obj)
115 struct nl_object_ops *ops = obj_ops(obj);
117 if (obj->ce_refcnt > 0)
118 NL_DBG(1, "Warning: Freeing object in use...\n");
121 nl_cache_remove(obj);
123 if (ops->oo_free_data)
124 ops->oo_free_data(obj);
128 NL_DBG(4, "Freed object %p\n", obj);
134 * @name Reference Management