-
Notifications
You must be signed in to change notification settings - Fork 6
/
target.go
77 lines (67 loc) · 1.53 KB
/
target.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
package lifxlan
import (
"encoding/binary"
"flag"
"fmt"
"net"
"strings"
)
// Target defines a target by its MAC address.
type Target uint64
var _ flag.Getter = (*Target)(nil)
// AllDevices is the special Target value means all devices.
const AllDevices Target = 0
func (t Target) String() string {
buf := make([]byte, 8)
binary.LittleEndian.PutUint64(buf, uint64(t))
strs := make([]string, 6)
for i, b := range buf[:6] {
strs[i] = fmt.Sprintf("%02x", b)
}
return strings.Join(strs, ":")
}
// Set implements flag.Value interface.
//
// It calls ParseTarget to parse the string.
// Refer to the doc of ParseTarget for more details.
func (t *Target) Set(s string) (err error) {
*t, err = ParseTarget(s)
return
}
// Get implements flag.Getter interface.
func (t Target) Get() interface{} {
return t
}
// Matches returns true if either target is AllDevices,
// or both targets have the same value.
func (t Target) Matches(other Target) bool {
if t == other {
return true
}
if t == AllDevices {
return true
}
if other == AllDevices {
return true
}
return false
}
// ParseTarget parses s into a Target.
//
// s should be in the format of a MAC address, e.g. "01:23:45:67:89:ab",
// or the special values for AllDevices: "00:00:00:00:00:00" and "".
func ParseTarget(s string) (t Target, err error) {
// Special case.
if s == "" {
return AllDevices, nil
}
var mac net.HardwareAddr
mac, err = net.ParseMAC(s)
if err != nil {
return
}
buf := make([]byte, 8)
copy(buf, mac)
t = Target(binary.LittleEndian.Uint64(buf))
return
}