Skip to content

Commit

Permalink
Allow Locale to be marshalled to/from text.
Browse files Browse the repository at this point in the history
This simplifies JSON usage.
  • Loading branch information
bojanz committed Oct 29, 2020
1 parent 018f04a commit 2a5df4a
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
15 changes: 15 additions & 0 deletions locale.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,21 @@ func (l Locale) String() string {
return b.String()
}

// MarshalText implements the encoding.TextMarshaler interface.
func (l Locale) MarshalText() ([]byte, error) {
return []byte(l.String()), nil
}

// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (l *Locale) UnmarshalText(b []byte) error {
aux := NewLocale(string(b))
l.Language = aux.Language
l.Script = aux.Script
l.Territory = aux.Territory

return nil
}

// IsEmpty returns whether l is empty.
func (l Locale) IsEmpty() bool {
return l.Language == "" && l.Script == "" && l.Territory == ""
Expand Down
48 changes: 48 additions & 0 deletions locale_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,54 @@ func TestLocale_String(t *testing.T) {
}
}

func TestLocale_MarshalText(t *testing.T) {
tests := []struct {
locale currency.Locale
want string
}{
{currency.Locale{}, ""},
{currency.Locale{Language: "de"}, "de"},
{currency.Locale{Language: "de", Territory: "CH"}, "de-CH"},
{currency.Locale{Language: "sr", Script: "Cyrl"}, "sr-Cyrl"},
{currency.Locale{Language: "sr", Script: "Latn", Territory: "RS"}, "sr-Latn-RS"},
}
for _, tt := range tests {
t.Run("", func(t *testing.T) {
b, _ := tt.locale.MarshalText()
got := string(b)
if got != tt.want {
t.Errorf("got %v, want %v", got, tt.want)
}
})
}
}

func TestLocale_UnmarshalText(t *testing.T) {
tests := []struct {
id string
want currency.Locale
}{
{"", currency.Locale{}},
{"de", currency.Locale{Language: "de"}},
{"de-CH", currency.Locale{Language: "de", Territory: "CH"}},
{"sr-Cyrl", currency.Locale{Language: "sr", Script: "Cyrl"}},
{"sr-Latn-RS", currency.Locale{Language: "sr", Script: "Latn", Territory: "RS"}},
// ID with the wrong case, ordering, delimeter.
{"SR_rs_LATN", currency.Locale{Language: "sr", Script: "Latn", Territory: "RS"}},
// ID with a variant. Variants are unsupported and ignored.
{"ca-ES-VALENCIA", currency.Locale{Language: "ca", Territory: "ES"}},
}
for _, tt := range tests {
t.Run(tt.id, func(t *testing.T) {
l := currency.Locale{}
l.UnmarshalText([]byte(tt.id))
if l != tt.want {
t.Errorf("got %v, want %v", l, tt.want)
}
})
}
}

func TestLocale_IsEmpty(t *testing.T) {
tests := []struct {
locale currency.Locale
Expand Down

0 comments on commit 2a5df4a

Please sign in to comment.