Skip to content

Commit

Permalink
Support Inet from encoding.TextMarshaler
Browse files Browse the repository at this point in the history
  • Loading branch information
scop authored and jackc committed Jul 30, 2022
1 parent ee454a1 commit 20ff3fe
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
8 changes: 8 additions & 0 deletions inet.go
Expand Up @@ -2,6 +2,7 @@ package pgtype

import (
"database/sql/driver"
"encoding"
"fmt"
"net"
"strings"
Expand Down Expand Up @@ -88,6 +89,13 @@ func (dst *Inet) Set(src interface{}) error {
return dst.Set(*value)
}
default:
if tv, ok := src.(encoding.TextMarshaler); ok {
text, err := tv.MarshalText()
if err != nil {
return fmt.Errorf("cannot marshal %v: %w", value, err)
}
return dst.Set(string(text))
}
if sv, ok := src.(fmt.Stringer); ok {
return dst.Set(sv.String())
}
Expand Down
9 changes: 9 additions & 0 deletions inet_test.go
Expand Up @@ -46,6 +46,14 @@ func TestCidrTranscode(t *testing.T) {
})
}

type textMarshaler struct {
Text string
}

func (t textMarshaler) MarshalText() (text []byte, err error) {
return []byte(t.Text), err
}

func TestInetSet(t *testing.T) {
successfulTests := []struct {
source interface{}
Expand All @@ -60,6 +68,7 @@ func TestInetSet(t *testing.T) {
{source: net.ParseIP(""), result: pgtype.Inet{Status: pgtype.Null}},
{source: "0.0.0.0/8", result: pgtype.Inet{IPNet: mustParseInet(t, "0.0.0.0/8"), Status: pgtype.Present}},
{source: "::ffff:0.0.0.0/104", result: pgtype.Inet{IPNet: &net.IPNet{IP: net.ParseIP("::ffff:0.0.0.0"), Mask: net.CIDRMask(104, 128)}, Status: pgtype.Present}},
{source: textMarshaler{"127.0.0.1"}, result: pgtype.Inet{IPNet: mustParseInet(t, "127.0.0.1"), Status: pgtype.Present}},
{source: func(s string) fmt.Stringer {
var b strings.Builder
b.WriteString(s)
Expand Down

0 comments on commit 20ff3fe

Please sign in to comment.