Skip to content
Snippets Groups Projects
vino.go 1.36 KiB
Newer Older
gbe's avatar
gbe committed
package vino

import (
	"database/sql/driver"
	"errors"
	"fmt"
gbe's avatar
gbe committed
	"strings"
gbe's avatar
gbe committed

	// Imported for side effects to register format handlers
	_ "image/jpeg"
	_ "image/png"
)

type ISO2CountryCode [2]byte

gbe's avatar
gbe committed
var UnknownCountry = ISO2CountryCode{'X', 'X'} //nolint:gochecknoglobals
gbe's avatar
gbe committed

func ISO2CountryCodeFromString(s string) (ISO2CountryCode, error) {
	if len(s) == 0 {
		return UnknownCountry, nil
	}

gbe's avatar
gbe committed
	if len(s) != len(UnknownCountry) {
gbe's avatar
gbe committed
		return UnknownCountry, errors.New("invalid length")
	}

gbe's avatar
gbe committed
	s = strings.ToUpper(s)

gbe's avatar
gbe committed
	return ISO2CountryCode{s[0], s[1]}, nil
}

func (i ISO2CountryCode) String() string {
	if i[0] == 0 || i[1] == 0 {
		return "XX"
	}

	return fmt.Sprintf("%c%c", i[0], i[1])
}

gbe's avatar
gbe committed
func (i ISO2CountryCode) Valid() bool {
	return i.String() != "XX"
}

gbe's avatar
gbe committed
func (i *ISO2CountryCode) UnmarshalBinary(d []byte) error {
	if len(d) == 0 {
		*i = UnknownCountry
		return nil
	}

gbe's avatar
gbe committed
	if len(d) != len(UnknownCountry) {
gbe's avatar
gbe committed
		*i = UnknownCountry
		return nil
	}

	copy(i[:], d)

	return nil
}

func (i ISO2CountryCode) Value() (driver.Value, error) {
	return i.String(), nil
}

func (i *ISO2CountryCode) Scan(data interface{}) error {
	var raw string

	switch data := data.(type) {
	case string:
		raw = data
	case []byte:
		raw = string(data)
	default:
		return fmt.Errorf("can't convert from %T", data)
	}

	c, err := ISO2CountryCodeFromString(raw)
	if err != nil {
		return err
	}

	*i = c

	return nil
}