-
Notifications
You must be signed in to change notification settings - Fork 68
/
ip.go
55 lines (46 loc) · 1.13 KB
/
ip.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
package json
import (
"net/netip"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
)
func decodeIP(d *jx.Decoder, checkVersion func(addr netip.Addr) bool) (v netip.Addr, err error) {
raw, err := d.Str()
if err != nil {
return v, err
}
v, err = netip.ParseAddr(raw)
if err != nil {
return v, errors.Wrap(err, "bad ip format")
}
if checkVersion != nil && !checkVersion(v) {
return v, errors.New("wrong ip version")
}
return v, nil
}
// DecodeIP decodes netip.Addr.
func DecodeIP(d *jx.Decoder) (netip.Addr, error) {
return decodeIP(d, nil)
}
// DecodeIPv4 decodes netip.Addr.
func DecodeIPv4(d *jx.Decoder) (netip.Addr, error) {
return decodeIP(d, netip.Addr.Is4)
}
// DecodeIPv6 decodes netip.Addr.
func DecodeIPv6(d *jx.Decoder) (netip.Addr, error) {
return decodeIP(d, netip.Addr.Is6)
}
// EncodeIP encodes netip.Addr.
func EncodeIP(s *jx.Encoder, v netip.Addr) {
b := make([]byte, 64)
b = v.AppendTo(b[:0])
s.ByteStr(b)
}
// EncodeIPv4 encodes netip.Addr.
func EncodeIPv4(s *jx.Encoder, v netip.Addr) {
EncodeIP(s, v)
}
// EncodeIPv6 encodes netip.Addr.
func EncodeIPv6(s *jx.Encoder, v netip.Addr) {
EncodeIP(s, v)
}