package vino import ( "database/sql/driver" "errors" "fmt" "strings" // Imported for side effects to register format handlers _ "image/jpeg" _ "image/png" ) type ISO2CountryCode [2]byte var UnknownCountry = ISO2CountryCode{'X', 'X'} func ISO2CountryCodeFromString(s string) (ISO2CountryCode, error) { if len(s) == 0 { return UnknownCountry, nil } if len(s) != 2 { return UnknownCountry, errors.New("invalid length") } s = strings.ToUpper(s) 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]) } func (i ISO2CountryCode) Valid() bool { return i.String() != "XX" } func (i *ISO2CountryCode) UnmarshalBinary(d []byte) error { if len(d) == 0 { *i = UnknownCountry return nil } if len(d) != 2 { *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 }