Fixed a nasty bug in HashDictionary that could cause heap corruption after removing a value. Added a test case to catch that bug. A few tweaks to Hash.
5 * Created by Jens Alfke on 8/20/09.
6 * Copyright 2009 Jens Alfke. All rights reserved.
7 * BSD-Licensed: See the file "LICENSE.txt" for details.
10 #ifndef _MOOSEYARD_HASH_
11 #define _MOOSEYARD_HASH_
13 #include "Dictionary.h"
17 /** A fairly low-level hash-table class whose keys and values are arbitrary data blobs.
18 This class does no memory management of the keys and values: the memory ranges
19 pointed to by the key and value parameters to put() must remain valid as long as
20 that key or value remains in the hash-table. */
26 /** Creates a new, empty Hash. */
27 explicit Hash (int capacity = 50);
31 /** Gets the value associated with the given key. */
33 Value operator[] (Key key) const {return get(key);}
35 /** Returns the number of values in the Hash. */
36 int count() const {return _count;}
38 /** Sets the given value for the given key, replacing any existing value. */
41 /** Removes the value with the given key. Returns the former value, or NULL if not found. */
44 /** Removes all values. */
53 Iterator (const Hash *h);
54 Iterator (const Hash &h);
55 operator bool() const {return hasValue();}
56 Value operator*() const {return value();}
57 Iterator& operator++() {next(); return *this;}
61 bool hasValue() const {return _entry < _end;}
64 Iterator (IndexEntry *start, IndexEntry*end);
66 IndexEntry* const _end;
71 IndexEntry& _find (Key key) const;
72 IndexEntry& _findForPut (const IndexEntry &newEntry);
73 void _resize(int newSize);
81 friend class Iterator;
86 /** A concrete Dictionary implemented with a Hash. */
87 class HashDictionary :public MutableDictionary {
89 explicit HashDictionary (int capacity =50) :_hash(capacity) { }
90 virtual ~HashDictionary();
91 virtual int count() const {return _hash.count();}
92 virtual bool contains (Key) const;
93 virtual Blob get (Key key) const {return _convertValue(_hash.get(key));}
94 virtual void put (Key, Blob value);
95 virtual bool remove (Key);
96 virtual void removeAll();
97 virtual Iterator* iterate() const {return new Iterator(*this);}
99 class Iterator :public Dictionary::Iterator {
101 explicit Iterator (const HashDictionary &d) :_it(d._hash) { }
102 virtual Key key() const {return _it.key();}
103 virtual Blob value() const {return _convertValue(_it.value());}
104 virtual bool hasValue() const {return _it.hasValue();}
105 virtual bool next() {return _it.next();}
111 static Blob _convertValue (void*);
113 friend class Iterator;
119 #endif _MOOSEYARD_HASH_