/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Diagnostics;
using SCG = System.Collections.Generic;
namespace C5
{
///
/// A bag collection based on a hash table of (item,count) pairs.
///
[Serializable]
public class HashBag : CollectionBase, ICollection
{
#region Fields
HashSet> dict;
#endregion
#region Events
///
///
///
///
public override EventTypeEnum ListenableEvents { get { return EventTypeEnum.Basic; } }
#endregion
#region Constructors
///
/// Create a hash bag with the deafult item equalityComparer.
///
public HashBag() : this(EqualityComparer.Default) { }
///
/// Create a hash bag with an external item equalityComparer.
///
/// The external item equalityComparer.
public HashBag(SCG.IEqualityComparer itemequalityComparer)
: base(itemequalityComparer)
{
dict = new HashSet>(new KeyValuePairEqualityComparer(itemequalityComparer));
}
///
/// Create a hash bag with external item equalityComparer, prescribed initial table size and default fill threshold (66%)
///
/// Initial table size (rounded to power of 2, at least 16)
/// The external item equalityComparer
public HashBag(int capacity, SCG.IEqualityComparer itemequalityComparer)
: base(itemequalityComparer)
{
dict = new HashSet>(capacity, new KeyValuePairEqualityComparer(itemequalityComparer));
}
///
/// Create a hash bag with external item equalityComparer, prescribed initial table size and fill threshold.
///
/// Initial table size (rounded to power of 2, at least 16)
/// Fill threshold (valid range 10% to 90%)
/// The external item equalityComparer
public HashBag(int capacity, double fill, SCG.IEqualityComparer itemequalityComparer)
: base(itemequalityComparer)
{
dict = new HashSet>(capacity, fill, new KeyValuePairEqualityComparer(itemequalityComparer));
}
#endregion
#region IEditableCollection Members
///
/// The complexity of the Contains operation
///
/// Always returns Speed.Constant
[Tested]
public virtual Speed ContainsSpeed { [Tested]get { return Speed.Constant; } }
///
/// Check if an item is in the bag
///
/// The item to look for
/// True if bag contains item
[Tested]
public virtual bool Contains(T item)
{ return dict.Contains(new KeyValuePair(item, 0)); }
///
/// Check if an item (collection equal to a given one) is in the bag and
/// if so report the actual item object found.
///
/// On entry, the item to look for.
/// On exit the item found, if any
/// True if bag contains item
[Tested]
public virtual bool Find(ref T item)
{
KeyValuePair p = new KeyValuePair(item, 0);
if (dict.Find(ref p))
{
item = p.Key;
return true;
}
return false;
}
///
/// Check if an item (collection equal to a given one) is in the bag and
/// if so replace the item object in the bag with the supplied one.
///
/// The item object to update with
/// True if item was found (and updated)
[Tested]
public virtual bool Update(T item)
{ T olditem = default(T); return Update(item, out olditem); }
///
///
///
///
///
///
public virtual bool Update(T item, out T olditem)
{
KeyValuePair p = new KeyValuePair(item, 0);
updatecheck();
//Note: we cannot just do dict.Update: we have to lookup the count before we
//know what to update with. There is of course a way around if we use the
//implementation of hashset -which we do not want to do.
//The hashbag is moreover mainly a proof of concept
if (dict.Find(ref p))
{
olditem = p.Key;
p.Key = item;
dict.Update(p);
if (ActiveEvents != 0)
raiseForUpdate(item, olditem, p.Value);
return true;
}
olditem = default(T);
return false;
}
///
/// Check if an item (collection equal to a given one) is in the bag.
/// If found, report the actual item object in the bag,
/// else add the supplied one.
///
/// On entry, the item to look for or add.
/// On exit the actual object found, if any.
/// True if item was found
[Tested]
public virtual bool FindOrAdd(ref T item)
{
updatecheck();
if (Find(ref item))
return true;
Add(item);
return false;
}
///
/// Check if an item (collection equal to a supplied one) is in the bag and
/// if so replace the item object in the set with the supplied one; else
/// add the supplied one.
///
/// The item to look for and update or add
/// True if item was updated
[Tested]
public virtual bool UpdateOrAdd(T item)
{
updatecheck();
if (Update(item))
return true;
Add(item);
return false;
}
///
///
///
///
///
///
public virtual bool UpdateOrAdd(T item, out T olditem)
{
updatecheck();
if (Update(item, out olditem))
return true;
Add(item);
return false;
}
///
/// Remove one copy af an item from the bag
///
/// The item to remove
/// True if item was (found and) removed
[Tested]
public virtual bool Remove(T item)
{
KeyValuePair p = new KeyValuePair(item, 0);
updatecheck();
if (dict.Find(ref p))
{
size--;
if (p.Value == 1)
dict.Remove(p);
else
{
p.Value--;
dict.Update(p);
}
if (ActiveEvents != 0)
raiseForRemove(p.Key);
return true;
}
return false;
}
///
/// Remove one copy of an item from the bag, reporting the actual matching item object.
///
/// The value to remove.
/// The removed value.
/// True if item was found.
[Tested]
public virtual bool Remove(T item, out T removeditem)
{
updatecheck();
KeyValuePair p = new KeyValuePair(item, 0);
if (dict.Find(ref p))
{
removeditem = p.Key;
size--;
if (p.Value == 1)
dict.Remove(p);
else
{
p.Value--;
dict.Update(p);
}
if (ActiveEvents != 0)
raiseForRemove(removeditem);
return true;
}
removeditem = default(T);
return false;
}
///
/// Remove all items in a supplied collection from this bag, counting multiplicities.
///
///
/// The items to remove.
[Tested]
public virtual void RemoveAll(SCG.IEnumerable items) where U : T
{
#warning Improve if items is a counting bag
updatecheck();
bool mustRaise = (ActiveEvents & (EventTypeEnum.Changed | EventTypeEnum.Removed)) != 0;
RaiseForRemoveAllHandler raiseHandler = mustRaise ? new RaiseForRemoveAllHandler(this) : null;
foreach (U item in items)
{
KeyValuePair p = new KeyValuePair(item, 0);
if (dict.Find(ref p))
{
size--;
if (p.Value == 1)
dict.Remove(p);
else
{
p.Value--;
dict.Update(p);
}
if (mustRaise)
raiseHandler.Remove(p.Key);
}
}
if (mustRaise)
raiseHandler.Raise();
}
///
/// Remove all items from the bag, resetting internal table to initial size.
///
[Tested]
public virtual void Clear()
{
updatecheck();
if (size == 0)
return;
dict.Clear();
int oldsize = size;
size = 0;
if ((ActiveEvents & EventTypeEnum.Cleared) != 0)
raiseCollectionCleared(true, oldsize);
if ((ActiveEvents & EventTypeEnum.Changed) != 0)
raiseCollectionChanged();
}
///
/// Remove all items *not* in a supplied collection from this bag,
/// counting multiplicities.
///
///
/// The items to retain
[Tested]
public virtual void RetainAll(SCG.IEnumerable items) where U : T
{
updatecheck();
HashBag res = new HashBag(itemequalityComparer);
foreach (U item in items)
{
KeyValuePair p = new KeyValuePair(item);
if (dict.Find(ref p))
{
KeyValuePair q = p;
if (res.dict.Find(ref q))
{
if (q.Value < p.Value)
{
q.Value++;
res.dict.Update(q);
res.size++;
}
}
else
{
q.Value = 1;
res.dict.Add(q);
res.size++;
}
}
}
if (size == res.size)
return;
CircularQueue wasRemoved = null;
if ((ActiveEvents & EventTypeEnum.Removed) != 0)
{
wasRemoved = new CircularQueue();
foreach (KeyValuePair p in dict)
{
int removed = p.Value - res.ContainsCount(p.Key);
if (removed > 0)
#warning We could send bag events here easily using a CircularQueue of (should?)
for (int i = 0; i < removed; i++)
wasRemoved.Enqueue(p.Key);
}
}
dict = res.dict;
size = res.size;
if ((ActiveEvents & EventTypeEnum.Removed) != 0)
raiseForRemoveAll(wasRemoved);
else if ((ActiveEvents & EventTypeEnum.Changed) != 0)
raiseCollectionChanged();
}
///
/// Check if all items in a supplied collection is in this bag
/// (counting multiplicities).
///
/// The items to look for.
///
/// True if all items are found.
[Tested]
public virtual bool ContainsAll(SCG.IEnumerable items) where U : T
{
HashBag res = new HashBag(itemequalityComparer);
foreach (T item in items)
if (res.ContainsCount(item) < ContainsCount(item))
res.Add(item);
else
return false;
return true;
}
///
/// Create an array containing all items in this bag (in enumeration order).
///
/// The array
[Tested]
public override T[] ToArray()
{
T[] res = new T[size];
int ind = 0;
foreach (KeyValuePair p in dict)
for (int i = 0; i < p.Value; i++)
res[ind++] = p.Key;
return res;
}
///
/// Count the number of times an item is in this set.
///
/// The item to look for.
/// The count
[Tested]
public virtual int ContainsCount(T item)
{
KeyValuePair p = new KeyValuePair(item, 0);
if (dict.Find(ref p))
return p.Value;
return 0;
}
///
///
///
///
public virtual ICollectionValue UniqueItems() { return new DropMultiplicity(dict); }
///
///
///
///
public virtual ICollectionValue> ItemMultiplicities()
{
return new GuardedCollectionValue>(dict);
}
///
/// Remove all copies of item from this set.
///
/// The item to remove
[Tested]
public virtual void RemoveAllCopies(T item)
{
updatecheck();
KeyValuePair p = new KeyValuePair(item, 0);
if (dict.Find(ref p))
{
size -= p.Value;
dict.Remove(p);
if ((ActiveEvents & EventTypeEnum.Removed) != 0)
raiseItemsRemoved(p.Key, p.Value);
if ((ActiveEvents & EventTypeEnum.Changed) != 0)
raiseCollectionChanged();
}
}
#endregion
#region ICollection Members
///
/// Copy the items of this bag to part of an array.
/// if i is negative.
/// if the array does not have room for the items.
///
/// The array to copy to
/// The starting index.
[Tested]
public override void CopyTo(T[] array, int index)
{
if (index < 0 || index + Count > array.Length)
throw new ArgumentOutOfRangeException();
foreach (KeyValuePair p in dict)
for (int j = 0; j < p.Value; j++)
array[index++] = p.Key;
}
#endregion
#region IExtensible Members
///
/// Report if this is a set collection.
///
/// Always true
[Tested]
public virtual bool AllowsDuplicates { [Tested] get { return true; } }
///
/// By convention this is true for any collection with set semantics.
///
/// True if only one representative of a group of equal items
/// is kept in the collection together with the total count.
public virtual bool DuplicatesByCounting { get { return true; } }
///
/// Add an item to this bag.
///
/// The item to add.
/// Always true
[Tested]
public virtual bool Add(T item)
{
updatecheck();
add(ref item);
if (ActiveEvents != 0)
raiseForAdd(item);
return true;
}
///
/// Add an item to this bag.
///
/// The item to add.
[Tested]
void SCG.ICollection.Add(T item)
{
Add(item);
}
private void add(ref T item)
{
KeyValuePair p = new KeyValuePair(item, 1);
if (dict.Find(ref p))
{
p.Value++;
dict.Update(p);
item = p.Key;
}
else
dict.Add(p);
size++;
}
///
/// Add the elements from another collection with a more specialized item type
/// to this collection.
///
/// The type of items to add
/// The items to add
public virtual void AddAll(SCG.IEnumerable items) where U : T
{
updatecheck();
#warning We could easily raise bag events
bool mustRaiseAdded = (ActiveEvents & EventTypeEnum.Added) != 0;
CircularQueue wasAdded = mustRaiseAdded ? new CircularQueue() : null;
bool wasChanged = false;
foreach (T item in items)
{
T jtem = item;
add(ref jtem);
wasChanged = true;
if (mustRaiseAdded)
wasAdded.Enqueue(jtem);
}
if (!wasChanged)
return;
if (mustRaiseAdded)
foreach (T item in wasAdded)
raiseItemsAdded(item, 1);
if ((ActiveEvents & EventTypeEnum.Changed) != 0)
raiseCollectionChanged();
}
#endregion
#region IEnumerable Members
///
/// Choose some item of this collection.
///
/// if collection is empty.
///
public override T Choose()
{
return dict.Choose().Key;
}
///
/// Create an enumerator for this bag.
///
/// The enumerator
[Tested]
public override SCG.IEnumerator GetEnumerator()
{
int left;
int mystamp = stamp;
foreach (KeyValuePair p in dict)
{
left = p.Value;
while (left > 0)
{
if (mystamp != stamp)
throw new CollectionModifiedException();
left--;
yield return p.Key;
}
}
}
#endregion
#region ICloneable Members
///
/// Make a shallow copy of this HashBag.
///
///
public virtual object Clone()
{
//TODO: make sure this
HashBag clone = new HashBag(dict.Count > 0 ? dict.Count : 1, itemequalityComparer);
//TODO: make sure this really adds in the counting bag way!
clone.AddAll(this);
return clone;
}
#endregion
#region Diagnostics
///
/// Test internal structure of data (invariants)
///
/// True if pass
[Tested]
public virtual bool Check()
{
bool retval = dict.Check();
int count = 0;
foreach (KeyValuePair p in dict)
count += p.Value;
if (count != size)
{
Console.WriteLine("count({0}) != size({1})", count, size);
retval = false;
}
return retval;
}
#endregion
}
}