thashes.nim 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. discard """
  2. output: '''true'''
  3. """
  4. import tables
  5. from hashes import THash
  6. # Test with int
  7. block:
  8. var t = initTable[int,int]()
  9. t[0] = 42
  10. t[1] = t[0] + 1
  11. assert(t[0] == 42)
  12. assert(t[1] == 43)
  13. let t2 = {1: 1, 2: 2}.toTable
  14. assert(t2[2] == 2)
  15. # Test with char
  16. block:
  17. var t = initTable[char,int]()
  18. t['0'] = 42
  19. t['1'] = t['0'] + 1
  20. assert(t['0'] == 42)
  21. assert(t['1'] == 43)
  22. let t2 = {'1': 1, '2': 2}.toTable
  23. assert(t2['2'] == 2)
  24. # Test with enum
  25. block:
  26. type
  27. E = enum eA, eB, eC
  28. var t = initTable[E,int]()
  29. t[eA] = 42
  30. t[eB] = t[eA] + 1
  31. assert(t[eA] == 42)
  32. assert(t[eB] == 43)
  33. let t2 = {eA: 1, eB: 2}.toTable
  34. assert(t2[eB] == 2)
  35. # Test with range
  36. block:
  37. type
  38. R = range[1..10]
  39. var t = initTable[R,int]() # causes warning, why?
  40. t[1] = 42 # causes warning, why?
  41. t[2] = t[1] + 1
  42. assert(t[1] == 42)
  43. assert(t[2] == 43)
  44. let t2 = {1.R: 1, 2.R: 2}.toTable
  45. assert(t2[2.R] == 2)
  46. # Test which combines the generics for tuples + ordinals
  47. block:
  48. type
  49. E = enum eA, eB, eC
  50. var t = initTable[(string, E, int, char), int]()
  51. t[("a", eA, 0, '0')] = 42
  52. t[("b", eB, 1, '1')] = t[("a", eA, 0, '0')] + 1
  53. assert(t[("a", eA, 0, '0')] == 42)
  54. assert(t[("b", eB, 1, '1')] == 43)
  55. let t2 = {("a", eA, 0, '0'): 1, ("b", eB, 1, '1'): 2}.toTable
  56. assert(t2[("b", eB, 1, '1')] == 2)
  57. # Test to check if overloading is possible
  58. # Unfortunately, this does not seem to work for int
  59. # The same test with a custom hash(s: string) does
  60. # work though.
  61. block:
  62. proc hash(x: int): THash {.inline.} =
  63. echo "overloaded hash"
  64. result = x
  65. var t = initTable[int, int]()
  66. t[0] = 0
  67. # Check hashability of all integer types (issue #5429)
  68. block:
  69. let intTables = (
  70. newTable[int, string](),
  71. newTable[int8, string](),
  72. newTable[int16, string](),
  73. newTable[int32, string](),
  74. newTable[int64, string](),
  75. newTable[uint, string](),
  76. newTable[uint8, string](),
  77. newTable[uint16, string](),
  78. newTable[uint32, string](),
  79. newTable[uint64, string](),
  80. )
  81. echo "true"