using Invercargill.Convert; namespace Invercargill { public class Dictionary : Associative, KeyValues { private HashTable hash_table; public Dictionary(HashFunc? key_hash_func = null, EqualFunc? key_equal_func = null) { var hash_func = key_hash_func; var equal_func = key_equal_func; var key_type = typeof(TKey); if(hash_func == null) { if(key_type == typeof(string)) { hash_func = GLib.str_hash; } else if(key_type == typeof(int64) || key_type == typeof(uint64)) { hash_func = GLib.int64_hash; } else if(key_type == typeof(int)) { hash_func = GLib.direct_hash; } else if(key_type == typeof(double)) { hash_func = GLib.double_hash; } else if(key_type.is_a(typeof(Hashable))) { hash_func = (k) => ((Hashable)k).hash_code(); } } if(equal_func == null) { if(key_type == typeof(string)) { equal_func = GLib.str_equal; } else if(key_type == typeof(int64) || key_type == typeof(uint64)) { equal_func = GLib.int64_equal; } else if(key_type == typeof(int)) { equal_func = GLib.direct_equal; } else if(key_type == typeof(double)) { equal_func = GLib.double_equal; } else if(key_type.is_a(typeof(Equatable))) { equal_func = (a, b) => ((Equatable)a).equals(b); } } hash_table = new HashTable(hash_func, equal_func); } public override void @set (TKey key, TValue value) { lock(hash_table) { hash_table.set (key, value); } } public override void set_all (Enumerable> key_values) { lock(hash_table) { key_values.iterate(kv => hash_table.set(kv.key, kv.value)); } } public override bool try_get (TKey key, out TValue value) { lock(hash_table) { TKey orig_key; return hash_table.lookup_extended (key, out orig_key, out value); } } public override void clear (TKey key) { lock(hash_table) { hash_table.remove(key); } } public override Tracker> get_tracker () { return new DictionaryTracker (this); } public override bool has (TKey key) { lock(hash_table) { return hash_table.contains (key); } } private class DictionaryTracker : Tracker> { private Dictionary dictionary; private (unowned TKey)[] keys; private int index; public DictionaryTracker(Dictionary dict) { dictionary = dict; keys = dict.hash_table.get_keys_as_array (); index = 0; } public override bool has_next() { return index < keys.length; } public override KeyValuePair get_next() { var key = keys[index]; var item = dictionary.get_or_default(key); index++; return new KeyValuePair (key, item); } } } }