forked from schollz/find
-
Notifications
You must be signed in to change notification settings - Fork 0
/
network.go
114 lines (101 loc) · 2.53 KB
/
network.go
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.
// network.go contains structures and functions for creating networks from slices.
package main
import (
"encoding/json"
"strconv"
)
func hasNetwork(network map[string]map[string]bool, macs []string) (string, bool) {
for n := range network {
for _, val := range macs {
if network[n][val] {
return n, true
}
}
}
return "none", false
}
func buildNetwork(network map[string]map[string]bool, macs []string) map[string]map[string]bool {
if len(network) == 0 {
network["0"] = make(map[string]bool)
for _, val := range macs {
network["0"][val] = true
}
return network
}
networkName, inNetworkAlready := hasNetwork(network, macs)
if inNetworkAlready {
for _, val := range macs {
network[networkName][val] = true
}
} else {
// Iterate network to get new name
curVal := 0
for n := range network {
num, _ := strconv.Atoi(n)
if num > curVal {
curVal = num
}
}
curVal++
networkName := strconv.Itoa(curVal)
network[networkName] = make(map[string]bool)
for _, val := range macs {
network[networkName][val] = true
}
}
return network
}
func mergeNetwork(network map[string]map[string]bool) map[string]map[string]bool {
for {
n, m, canMerge := hasMerge(network)
if canMerge {
for k := range network[m] {
network[n][k] = true
}
delete(network, m)
} else {
break
}
}
return network
}
func hasMerge(network map[string]map[string]bool) (string, string, bool) {
for n := range network {
for m := range network {
if m != n {
for j := range network[n] {
for k := range network[m] {
if j == k {
return n, m, true
}
}
}
}
}
}
return "none", "none", false
}
func dumpNetwork(network map[string]map[string]bool) []byte {
jsonByte, _ := json.Marshal(network)
return jsonByte
}
func loadNetwork(jsonByte []byte) map[string]map[string]bool {
res2 := make(map[string]map[string]bool)
json.Unmarshal(jsonByte, &res2)
return res2
}
// network := make(map[string]map[string]bool)
// macs := []string{"test", "test2", "test3", "test4"}
// fmt.Println(buildNetwork(network, macs))
// macs = []string{"test6", "test5", "test7"}
// fmt.Println(buildNetwork(network, macs))
// macs = []string{"test6", "test9", "test10"}
// fmt.Println(buildNetwork(network, macs))
// fmt.Println(mergeNetwork(network))
// n2 := dumpNetwork(network)
// fmt.Println(string(n2))
// n2a := loadNetwork(n2)
// fmt.Println(n2a)