-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathetld.go
More file actions
75 lines (60 loc) · 1.34 KB
/
etld.go
File metadata and controls
75 lines (60 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// file: etld.go
// description: manages effective top-level domains (eTLDs)
package gotld
import (
"sort"
"sync"
)
// ETLD manages all eTLDs in lists with thread-safety
type ETLD struct {
List []string
Count int
Dots int
mu sync.RWMutex
}
// Add appends a new eTLD to the list if it doesn't already exist
func (e *ETLD) Add(s string, sortList bool) bool {
e.mu.Lock()
defer e.mu.Unlock()
// Check for duplicates
for _, item := range e.List {
if item == s {
return false
}
}
oldCount := e.Count
e.List = append(e.List, s)
e.Count = len(e.List)
if sortList {
e.Sort()
}
return e.Count > oldCount
}
// Sort will sort the list of strings
func (e *ETLD) Sort() {
e.mu.Lock()
defer e.mu.Unlock()
sort.Strings(e.List)
}
// Search will return true if found as well as the eTLD from the list
func (e *ETLD) Search(str string) (string, bool) {
e.mu.RLock()
defer e.mu.RUnlock()
if e.Count == 0 {
return "", false
}
idx := sort.Search(e.Count, func(i int) bool { return e.List[i] >= str })
if idx < e.Count && e.List[idx] == str {
return e.List[idx], true // Found (TRUE)
}
return "", false // NOT FOUND (FALSE)
}
// emptyETLD creates a new empty ETLD with the specified number of dots
func emptyETLD(dots int) *ETLD {
return &ETLD{
List: make([]string, 0),
Count: 0,
Dots: dots,
mu: sync.RWMutex{},
}
}