2 * lib/data.c Abstract Data
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-2006 Thomas Graf <tgraf@suug.ch>
14 * @defgroup data Abstract Data
18 #include <netlink-local.h>
19 #include <netlink/netlink.h>
20 #include <netlink/utils.h>
21 #include <linux/socket.h>
29 * Allocate a new abstract data object.
30 * @arg buf Data buffer containing the actual data.
31 * @arg size Size of data buffer.
33 * Allocates a new abstract data and copies the specified data
34 * buffer into the new handle.
36 * @return Newly allocated data handle or NULL
38 struct nl_data *nl_data_alloc(void *buf, size_t size)
42 data = calloc(1, sizeof(*data));
46 data->d_data = calloc(1, size);
55 memcpy(data->d_data, buf, size);
64 * Clone an abstract data object.
65 * @arg src Abstract data object
67 * @return Cloned object or NULL
69 struct nl_data *nl_data_clone(struct nl_data *src)
71 return nl_data_alloc(src->d_data, src->d_size);
75 * Append data to an abstract data object.
76 * @arg data Abstract data object.
77 * @arg buf Data buffer containing the data to be appended.
78 * @arg size Size of data to be apppended.
80 * Reallocates an abstract data and copies the specified data
81 * buffer into the new handle.
83 * @return 0 on success or a negative error code
85 int nl_data_append(struct nl_data *data, void *buf, size_t size)
91 data->d_data = realloc(data->d_data, data->d_size + size);
93 return nl_errno(ENOMEM);
96 memcpy(data->d_data + data->d_size, buf, size);
98 memset(data->d_data + data->d_size, 0, size);
100 data->d_size += size;
107 * Free an abstract data object.
108 * @arg data Abstract data object.
110 void nl_data_free(struct nl_data *data)
121 * @name Attribute Access
126 * Get data buffer of abstract data object.
127 * @arg data Abstract data object.
128 * @return Data buffer or NULL if empty.
130 void *nl_data_get(struct nl_data *data)
132 return data->d_size > 0 ? data->d_data : NULL;
136 * Get size of data buffer of abstract data object.
137 * @arg data Abstract data object.
138 * @return Size of data buffer.
140 size_t nl_data_get_size(struct nl_data *data)
153 * Compare two abstract data objects.
154 * @arg a Abstract data object.
155 * @arg b Another abstract data object.
156 * @return An integer less than, equal to, or greater than zero if
157 * a is found, respectively, to be less than, to match, or
160 int nl_data_cmp(struct nl_data *a, struct nl_data *b)
162 void *a_ = nl_data_get(a);
163 void *b_ = nl_data_get(b);
166 return memcmp(a_, b_, nl_data_get_size(a));