hashmap.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package tamias
  2. // HashMap is a wrapped hash map, that uses the go map
  3. // it's an alternative for HashSet
  4. /*
  5. type HashValue int64
  6. type HashElement interface {
  7. Equals(interface {}) (bool)
  8. }
  9. */
  10. type HashMap struct {
  11. table map[HashValue] HashElement
  12. }
  13. func HashMapAlloc() (* HashMap) {
  14. return &HashMap{}
  15. }
  16. func (hash * HashMap) Init(size int) (* HashMap) {
  17. hash.table = make(map[HashValue] HashElement, size)
  18. return hash
  19. // set.buffers = nil
  20. }
  21. func HashMapNew(size int) (HashMap) {
  22. return HashSetAlloc().Init(size)
  23. }
  24. func (hash * HashSet) Insert(key HashValue, value HashElement) (HashElement) {
  25. hash.table[key] = value
  26. idx := set.hashIndex(hash)
  27. // Find the bin with the matching element.
  28. bin := set.findBin(hash, ptr)
  29. // Create it if necessary.
  30. if bin == nil {
  31. bin = set.getUnusedBin()
  32. bin.hash = hash
  33. bin.elt = ptr //XXX Transformation not called here. Is it needed?
  34. bin.next = set.table[idx]
  35. set.table[idx] = bin
  36. set.entries++
  37. // Resize the set if it's full.
  38. if set.IsFull() {
  39. set.Resize()
  40. }
  41. } else {
  42. // this is not in Chipmunk original but seems like a bug not to do it
  43. bin.elt = ptr
  44. }
  45. return bin.elt
  46. }
  47. func (set * HashSet) Remove(hash HashValue, ptr HashElement) (HashElement) {
  48. bin, prev := set.findBinPrev(hash, ptr)
  49. // Remove it if it exists.
  50. if bin != nil {
  51. // Update the previous bin next pointer to point to the next bin.
  52. if prev != nil {
  53. prev.next = bin.next
  54. }
  55. set.entries--
  56. return_value := bin.elt
  57. set.recycleBin(bin)
  58. return return_value
  59. }
  60. return nil;
  61. }
  62. func (set * HashSet) Find(hash HashValue, ptr HashElement) (HashElement) {
  63. bin := set.findBin(hash, ptr)
  64. if bin != nil {
  65. return bin.elt
  66. }
  67. return set.default_value
  68. }
  69. type HashSetIterFunc func(bin, data HashElement)
  70. func (set * HashSet) Each(fun HashSetIterFunc, data HashElement) {
  71. for i:=0 ; i<set.size ; i++ {
  72. bin := set.table[i];
  73. for bin != nil {
  74. next := bin.next;
  75. fun(bin.elt, data);
  76. bin = next;
  77. }
  78. }
  79. }
  80. type HashSetFilterFunc func(bin, data HashElement) (bool)