1
0

trie.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package geodb
  2. import (
  3. "net"
  4. )
  5. type trie_Node struct {
  6. childrens [2]*trie_Node
  7. cc string
  8. }
  9. // Initializing the root of the trie
  10. type trie struct {
  11. root *trie_Node
  12. }
  13. func ipToBytes(ip string) []byte {
  14. // Parse the IP address string into a net.IP object
  15. parsedIP := net.ParseIP(ip)
  16. // Convert the IP address to a 4-byte slice
  17. ipBytes := parsedIP.To4()
  18. if ipBytes == nil {
  19. //This is an IPv6 address
  20. ipBytes = parsedIP.To16()
  21. }
  22. return ipBytes
  23. }
  24. // inititlaizing a new trie
  25. func newTrie() *trie {
  26. t := new(trie)
  27. t.root = new(trie_Node)
  28. return t
  29. }
  30. // Passing words to trie
  31. func (t *trie) insert(ipAddr string, cc string) {
  32. ipBytes := ipToBytes(ipAddr)
  33. current := t.root
  34. for _, b := range ipBytes {
  35. //For each byte in the ip address (4 / 16 bytes)
  36. //each byte is 8 bit
  37. for j := 7; j >= 0; j-- {
  38. bit := int(b >> j & 1)
  39. if current.childrens[bit] == nil {
  40. current.childrens[bit] = &trie_Node{
  41. childrens: [2]*trie_Node{},
  42. cc: cc,
  43. }
  44. }
  45. current = current.childrens[bit]
  46. }
  47. }
  48. }
  49. // isReservedIP check if the given ip address is NOT a public ip address
  50. func isReservedIP(ip string) bool {
  51. parsedIP := net.ParseIP(ip)
  52. if parsedIP == nil {
  53. return false
  54. }
  55. // Check if the IP address is a loopback address
  56. if parsedIP.IsLoopback() {
  57. return true
  58. }
  59. // Check if the IP address is in the link-local address range
  60. if parsedIP.IsLinkLocalUnicast() || parsedIP.IsLinkLocalMulticast() {
  61. return true
  62. }
  63. //Check if the IP is in the reserved private range
  64. if parsedIP.IsPrivate() {
  65. return true
  66. }
  67. return false
  68. }
  69. // Initializing the search for word in node
  70. func (t *trie) search(ipAddr string) string {
  71. if isReservedIP(ipAddr) {
  72. return ""
  73. }
  74. ipBytes := ipToBytes(ipAddr)
  75. current := t.root
  76. for _, b := range ipBytes {
  77. //For each byte in the ip address
  78. //each byte is 8 bit
  79. for j := 7; j >= 0; j-- {
  80. bit := int(b >> j & 1)
  81. if current.childrens[bit] == nil {
  82. return current.cc
  83. }
  84. current = current.childrens[bit]
  85. }
  86. }
  87. if len(current.childrens) == 0 {
  88. return current.cc
  89. }
  90. //Not found
  91. return ""
  92. }