1 /*
2 * Copyright (C) 2015 Tobias Brunner
3 * HSR Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
16 #include "hash_algorithm_set.h"
18 #include <collections/array.h>
20 typedef struct private_hash_algorithm_set_t private_hash_algorithm_set_t;
22 struct private_hash_algorithm_set_t {
24 /**
25 * Public interface
26 */
27 hash_algorithm_set_t public;
29 /**
30 * Algorithms contained in the set
31 */
32 array_t *algorithms;
33 };
35 /**
36 * Sort hash algorithms
37 */
38 static int hash_sort(const void *a, const void *b, void *user)
39 {
40 const hash_algorithm_t *ha = a, *hb = b;
41 return *ha - *hb;
42 }
44 /**
45 * Find a hash algorithm
46 */
47 static int hash_find(const void *a, const void *b)
48 {
49 return hash_sort(a, b, NULL);
50 }
52 METHOD(hash_algorithm_set_t, contains, bool,
53 private_hash_algorithm_set_t *this, hash_algorithm_t hash)
54 {
55 return array_bsearch(this->algorithms, &hash, hash_find, NULL) != -1;
56 }
59 private_hash_algorithm_set_t *this, hash_algorithm_t hash)
60 {
61 if (!contains(this, hash))
62 {
63 array_insert(this->algorithms, ARRAY_TAIL, &hash);
64 array_sort(this->algorithms, hash_sort, NULL);
65 }
66 }
68 METHOD(hash_algorithm_set_t, count, int,
69 private_hash_algorithm_set_t *this)
70 {
71 return array_count(this->algorithms);
72 }
74 CALLBACK(hash_filter, bool,
75 void *data, enumerator_t *orig, va_list args)
76 {
77 hash_algorithm_t *algo, *out;
79 VA_ARGS_VGET(args, out);
81 if (orig->enumerate(orig, &algo))
82 {
83 *out = *algo;
84 return TRUE;
85 }
86 return FALSE;
87 }
89 METHOD(hash_algorithm_set_t, create_enumerator, enumerator_t*,
90 private_hash_algorithm_set_t *this)
91 {
92 return enumerator_create_filter(array_create_enumerator(this->algorithms),
93 hash_filter, NULL, NULL);
94 }
96 METHOD(hash_algorithm_set_t, destroy, void,
97 private_hash_algorithm_set_t *this)
98 {
99 array_destroy(this->algorithms);
100 free(this);
101 }
103 /**
105 */
106 hash_algorithm_set_t *hash_algorithm_set_create()
107 {
108 private_hash_algorithm_set_t *this;
110 INIT(this,
111 .public = {