home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 1998 May / Pcwk5b98.iso / Borland / Cplus45 / BC45 / BOCOLE.PAK / HASHTBL.H < prev    next >
C/C++ Source or Header  |  1995-08-29  |  2KB  |  88 lines

  1. //
  2.  
  3. #ifndef _HASHTBL_H
  4. #define        _HASHTBL_H
  5.  
  6.  
  7. #include <bole.h>
  8.  
  9. //------------------------------ IHashable -------------------------
  10. // An ABC for objects which can be linked into a hash table
  11.  
  12. typedef unsigned int HashIndex;
  13.  
  14. template <class T> class _ICLASS IHashable : public IUnknown {
  15. public:
  16.     virtual HashIndex Hash(HashIndex modulo) const = 0;
  17.     virtual BOOL operator==(const T *) const =0;
  18.     virtual BOOL operator!=(const T *) const =0;
  19.     virtual IHashable<T> *&Next() = 0;
  20. };
  21.  
  22.  
  23. template <class T, HashIndex SIZE> class    _ICLASS HashTable {
  24. protected:
  25.     IHashable<T> *    aBuckets[SIZE];
  26.     IHashable<T> *&    Insert(IHashable<T> *&rpFound, IHashable<T> *pKey);
  27.     IHashable<T> *&    Delete(IHashable<T> *&rpFound);
  28.     IHashable<T> *&    Find(IHashable<T> *hashKey);
  29.  
  30. public:
  31.     ~HashTable();
  32.     // Add  returns existing instance or adds
  33.     BOOL    Add(IHashable<T> **pPat);
  34.     // Remove takes key out of HashTable
  35.     void    Remove(IHashable<T> *pKey);
  36. };
  37.  
  38.  
  39. template <class T, HashIndex SIZE> IHashable<T> *& HashTable<T, SIZE>::
  40.     Insert(IHashable<T> *&rpFound, IHashable<T> *pKey)
  41. {
  42.     pKey->Next()=rpFound,
  43.     pKey->AddRef(),
  44.     rpFound=pKey;
  45.     return rpFound;
  46. }
  47.  
  48. template <class T, HashIndex SIZE> IHashable<T> *& HashTable<T, SIZE>::
  49.     Delete(IHashable<T> *&rpFound)
  50. {
  51.     assert(rpFound != 0L);
  52.     IHashable<T> **ppFoundNext = &rpFound->Next();
  53.     IHashable<T> *pFoundNext = *ppFoundNext;
  54.     *ppFoundNext=0L;
  55.     rpFound->Release();
  56.     return rpFound = pFoundNext;
  57. }
  58.  
  59. template <class T, HashIndex SIZE>
  60. BOOL    HashTable<T, SIZE>::Add(IHashable<T> **ppPat)
  61. {
  62.     IHashable<T> *&pSrc = Find(*ppPat);
  63.     if (pSrc) {
  64.         (*ppPat)->Release();
  65.         *ppPat = pSrc;
  66.     }
  67.     else
  68.         Insert(pSrc, *ppPat) ;
  69.     
  70.     (*ppPat) ->AddRef();
  71.     return TRUE;
  72. }
  73.  
  74. //    (pSrc) ?
  75. //        pPat->Release(),
  76. //            pPat = pSrc :
  77. //        Insert(pSrc, pPat) ;
  78.  
  79. template <class T, HashIndex SIZE>
  80. void    HashTable<T, SIZE>::Remove(IHashable<T> *pKey)
  81. {
  82.     IHashable<T> *&pFound =Find(pKey);
  83.     pFound ? Delete(pFound) : 0L;
  84. }
  85.  
  86. #endif
  87.  
  88.