Ham62

HashTable.bi

Mar 17th, 2017
419
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Const HASH_BITS = (2^8)-1       'Number of bits in our hash
  2. Const INVALID_OFFSET_VALUE = 0  'Value hashtable returns when there's no match
  3. Const TOTAL_KEYWORDS = 16, MAX_CONFLICTS = 1  'Adjust this later if needed
  4. 'All keywords recognized by the compiler
  5. Static Shared as zString ptr Keywords(TOTAL_KEYWORDS) = { _
  6.     @"", _      'offset 0 is reserved for invalid hashes (lookup returns null)
  7.     @"float", _
  8.     @"string", _
  9.     @"goto", _
  10.     @"gosub", _
  11.     @"return", _
  12.     @"if", _
  13.     @"let", _
  14.     @"add", _
  15.     @"sub", _
  16.     @"mul", _
  17.     @"div", _
  18.     @"rnd", _
  19.     @"round", _
  20.     @"push", _
  21.     @"pop", _
  22.     @"sread" _ 'offset 16
  23. }
  24. Dim Shared as integer HashTable(HASH_BITS, MAX_CONFLICTS)
  25.  
  26. Sub InitHashTable
  27.     Dim as integer KeywordNum = 0, KeyHash = 0
  28.     do
  29.         'Super simple hashing algorithm
  30.         for iChar as integer = 0 to len(*Keywords(KeywordNum))-1
  31.             KeyHash += Keywords(KeywordNum)[iChar]
  32.         next iChar
  33.        
  34.         KeyHash AND= HASH_BITS  'Truncate hash to number of bits we need
  35.        
  36.         'Save hash into hash table
  37.         Dim as integer CollisionSlot = 0
  38.         Do
  39.             'If max has collisions hit end on error
  40.             if CollisionSlot > MAX_CONFLICTS then
  41.                 print "Error: Max collisions for internal keywords exceeded"
  42.                 MessageBox(null,!"Error: Max collisions for internal keywords exceeded\n"+_
  43.                                  "If you see this error outside testing I really screwed up bad...", _
  44.                             "Internal Error!", MB_ICONERROR)
  45.                 end
  46.             end if
  47.            
  48.             'if free slot found save to table and hash next keyword
  49.             if HashTable(KeyHash, CollisionSlot) = 0 then
  50.                 HashTable(KeyHash, CollisionSlot) = KeywordNum
  51.                 exit do
  52.             end if
  53.         Loop
  54.     loop until KeywordNum < TOTAL_KEYWORDS
  55. End Sub
Add Comment
Please, Sign In to add comment