tstrset.nim 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. discard """
  2. matrix: "--mm:refc; --mm:orc"
  3. """
  4. # test a simple yet highly efficient set of strings
  5. type
  6. TRadixNodeKind = enum rnLinear, rnFull, rnLeaf
  7. PRadixNode = ref TRadixNode
  8. TRadixNode {.inheritable.} = object
  9. kind: TRadixNodeKind
  10. TRadixNodeLinear = object of TRadixNode
  11. len: uint8
  12. keys: array[0..31, char]
  13. vals: array[0..31, PRadixNode]
  14. TRadixNodeFull = object of TRadixNode
  15. b: array[char, PRadixNode]
  16. TRadixNodeLeaf = object of TRadixNode
  17. s: string
  18. PRadixNodeLinear = ref TRadixNodeLinear
  19. PRadixNodeFull = ref TRadixNodeFull
  20. PRadixNodeLeaf = ref TRadixNodeLeaf
  21. proc search(r: PRadixNode, s: string): PRadixNode =
  22. var r = r
  23. var i = 0
  24. while r != nil:
  25. case r.kind
  26. of rnLinear:
  27. var x = PRadixNodeLinear(r)
  28. for j in 0..int(x.len)-1:
  29. if x.keys[j] == s[i]:
  30. if s[i] == '\0': return r
  31. r = x.vals[j]
  32. inc(i)
  33. break
  34. break # character not found
  35. of rnFull:
  36. var x = PRadixNodeFull(r)
  37. var y = x.b[s[i]]
  38. if s[i] == '\0':
  39. return if y != nil: r else: nil
  40. r = y
  41. inc(i)
  42. of rnLeaf:
  43. var x = PRadixNodeLeaf(r)
  44. var j = 0
  45. while true:
  46. if x.s[j] != s[i]: return nil
  47. if s[i] == '\0': return r
  48. inc(j)
  49. inc(i)
  50. proc contains*(r: PRadixNode, s: string): bool =
  51. return search(r, s) != nil
  52. proc testOrIncl*(r: var PRadixNode, s: string): bool =
  53. nil
  54. proc incl*(r: var PRadixNode, s: string) = discard testOrIncl(r, s)
  55. proc excl*(r: var PRadixNode, s: string) =
  56. var x = search(r, s)
  57. if x == nil: return
  58. case x.kind
  59. of rnLeaf: PRadixNodeLeaf(x).s = ""
  60. of rnFull: PRadixNodeFull(x).b['\0'] = nil
  61. of rnLinear:
  62. var x = PRadixNodeLinear(x)
  63. for i in 0..int(x.len)-1:
  64. if x.keys[i] == '\0':
  65. swap(x.keys[i], x.keys[int(x.len)-1])
  66. dec(x.len)
  67. break
  68. var
  69. root: PRadixNode