-
Notifications
You must be signed in to change notification settings - Fork 15
/
IP_type.go
56 lines (45 loc) · 1.15 KB
/
IP_type.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
/* IP_type.go: define methods to make a CustomType that stores IP addresses
*
* Author: J. Lowell Wofford <lowell@lanl.gov>
*
* This software is open source software available under the BSD-3 license.
* Copyright (c) 2018-2021, Triad National Security, LLC
* See LICENSE file for details.
*/
package customtypes
import (
fmt "fmt"
"net"
"strconv"
"strings"
"github.com/kraken-hpc/kraken/lib/types"
)
var _ (types.ExtensionCustomType) = IP{}
var _ (types.ExtensionCustomTypePtr) = (*IP)(nil)
type IP struct {
net.IP
}
func (i IP) Marshal() ([]byte, error) {
return []byte(i.To4()), nil
}
func (i *IP) MarshalTo(data []byte) (int, error) {
copy(data, []byte(i.To4()))
return 4, nil
}
func (i *IP) Unmarshal(data []byte) error {
if len(data) != 4 {
return fmt.Errorf("incorrect IP address lenght: %d != 4", len(data))
}
i.IP = net.IPv4(data[0], data[1], data[2], data[3])
return nil
}
func (i *IP) Size() int {
return 4
}
func (i IP) MarshalJSON() (j []byte, e error) {
return []byte(strconv.Quote(i.String())), nil
}
func (i *IP) UnmarshalJSON(data []byte) error {
s := strings.Trim(string(data), "\"'")
return i.UnmarshalText([]byte(s))
}