Line data Source code
1 : /**
2 : * @file
3 : *
4 : * @brief Functional helper.
5 : *
6 : * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
7 : */
8 :
9 : #define __STDC_FORMAT_MACROS
10 :
11 : #include <kdb.h>
12 :
13 : #include <errno.h>
14 : #include <limits.h>
15 : #include <stdio.h>
16 : #include <stdlib.h>
17 : #include <string.h>
18 :
19 : #ifdef HAVE_CTYPE_H
20 : #include <ctype.h>
21 : #endif
22 :
23 :
24 : /**
25 : * @brief return only those keys from the given
26 : * keyset that pass the supplied filter function
27 : * with the supplied argument
28 : *
29 : * @param result the keyset that should contain the filtered keys
30 : * @param input the keyset whose keys should be filtered
31 : * @param filter a function pointer to a function that will be used to
32 : * filter the keyset. A key will be taken if the function returns a value
33 : * greater than 0.
34 : * @param argument an argument that will be passed to the filter function
35 : * each time it is called
36 : * @return the number of filtered keys if the filter function always
37 : * returned a positive value, -1 otherwise
38 : * @retval NULL on NULL pointer
39 : */
40 852 : int elektraKsFilter (KeySet * result, KeySet * input, int (*filter) (const Key * k, void * argument), void * argument)
41 : {
42 852 : if (!result) return -1;
43 :
44 852 : if (!input) return -1;
45 :
46 852 : if (!filter) return -1;
47 :
48 852 : int ret = 0;
49 : Key * current;
50 :
51 852 : cursor_t cursor = ksGetCursor (input);
52 852 : ksRewind (input);
53 19044 : while ((current = ksNext (input)) != 0)
54 : {
55 17340 : int rc = filter (current, argument);
56 17340 : if (rc <= -1)
57 : return -1;
58 17340 : else if (rc > 0)
59 : {
60 632 : ++ret;
61 632 : ksAppendKey (result, current);
62 : }
63 : }
64 852 : ksSetCursor (input, cursor);
65 852 : return ret;
66 : }
|