NVBIO
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
khash_str2int.h
Go to the documentation of this file.
1 #ifndef __KHASH_UTILS_H__
2 #define __KHASH_UTILS_H__
3 
4 #include <htslib/khash.h>
5 
6 KHASH_MAP_INIT_STR(str2int, int)
7 
8 /*
9  * Wrappers for khash dictionaries used by mpileup.
10  */
11 
12 static inline void *khash_str2int_init(void)
13 {
14  return kh_init(str2int);
15 }
16 
17 /*
18  * Destroy the hash structure, but not the keys
19  */
20 static inline void khash_str2int_destroy(void *_hash)
21 {
22  khash_t(str2int) *hash = (khash_t(str2int)*)_hash;
23  if (hash) kh_destroy(str2int, hash); // Note that strings are not freed.
24 }
25 
26 /*
27  * Destroys both the hash structure and the keys
28  */
29 static inline void khash_str2int_destroy_free(void *_hash)
30 {
31  khash_t(str2int) *hash = (khash_t(str2int)*)_hash;
32  khint_t k;
33  if (hash == 0) return;
34  for (k = 0; k < kh_end(hash); ++k)
35  if (kh_exist(hash, k)) free((char*)kh_key(hash, k));
36  kh_destroy(str2int, hash);
37 }
38 
39 /*
40  * Returns 1 if key exists or 0 if not
41  */
42 static inline int khash_str2int_has_key(void *_hash, const char *str)
43 {
44  khash_t(str2int) *hash = (khash_t(str2int)*)_hash;
45  khint_t k = kh_get(str2int, hash, str);
46  if ( k == kh_end(hash) ) return 0;
47  return 1;
48 }
49 
50 /*
51  * Returns 0 on success and -1 when the key is not present. On success,
52  * *value is set, unless NULL is passed.
53  */
54 static inline int khash_str2int_get(void *_hash, const char *str, int *value)
55 {
56  khash_t(str2int) *hash = (khash_t(str2int)*)_hash;
57  khint_t k;
58  if ( !hash ) return -1;
59  k = kh_get(str2int, hash, str);
60  if ( k == kh_end(hash) ) return -1;
61  if ( !value ) return 0;
62  *value = kh_val(hash, k);
63  return 0;
64 }
65 
66 /*
67  * Add a new string to the dictionary, auto-incrementing the value.
68  * On success returns the newly inserted integer id, on error -1
69  * is returned.
70  */
71 static inline int khash_str2int_inc(void *_hash, const char *str)
72 {
73  khint_t k;
74  int ret;
75  khash_t(str2int) *hash = (khash_t(str2int)*)_hash;
76  if ( !hash ) return -1;
77  k = kh_put(str2int, hash, str, &ret);
78  if (ret == 0) return kh_val(hash, k);
79  kh_val(hash, k) = kh_size(hash) - 1;
80  return kh_val(hash, k);
81 }
82 
83 /*
84  * Set a new key,value pair. On success returns the bin index, on
85  * error -1 is returned.
86  */
87 static inline int khash_str2int_set(void *_hash, const char *str, int value)
88 {
89  khint_t k;
90  int ret;
91  khash_t(str2int) *hash = (khash_t(str2int)*)_hash;
92  if ( !hash ) return -1;
93  k = kh_put(str2int, hash, str, &ret);
94  kh_val(hash,k) = value;
95  return k;
96 }
97 
98 #endif