aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/ClickHouse/clickhouse-go/lib/column/ipv4.go
blob: eaac52c6da49fedc608c09a25fa459abd0437a06 (plain) (blame)
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
package column

import (
	"net"

	"github.com/ClickHouse/clickhouse-go/lib/binary"
)

type IPv4 struct {
	base
}

func (*IPv4) Read(decoder *binary.Decoder, isNull bool) (interface{}, error) {
	v, err := decoder.Fixed(4)
	if err != nil {
		return nil, err
	}
	return net.IPv4(v[3], v[2], v[1], v[0]), nil
}

func (ip *IPv4) Write(encoder *binary.Encoder, v interface{}) error {
	var netIP net.IP
	switch v.(type) {
	case string:
		netIP = net.ParseIP(v.(string))
	case net.IP:
		netIP = v.(net.IP)
	case *net.IP:
		netIP = *(v.(*net.IP))
	default:
		return &ErrUnexpectedType{
			T:      v,
			Column: ip,
		}
	}

	if netIP == nil {
		return &ErrUnexpectedType{
			T:      v,
			Column: ip,
		}
	}
	ip4 := netIP.To4()
	if ip4 == nil {
		return &ErrUnexpectedType{
			T:      v,
			Column: ip,
		}
	}
	if _, err := encoder.Write([]byte{ip4[3], ip4[2], ip4[1], ip4[0]}); err != nil {
		return err
	}
	return nil
}