From a4d782da5b9c23f63e4ca0b80ac325b3967fed96 Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Fri, 24 Jun 2022 03:12:53 +0900 Subject: [PATCH] ebiten: add Key.MarshalText and Key.UnmarshalText Closes #2133 --- genkeys.go | 16 ++++++++++++++++ keys.go | 16 ++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/genkeys.go b/genkeys.go index e252ab943..fb93a82df 100644 --- a/genkeys.go +++ b/genkeys.go @@ -469,6 +469,7 @@ const ebitenKeysTmpl = `{{.License}} package ebiten import ( + "fmt" "strings" "github.com/hajimehoshi/ebiten/v2/internal/ui" @@ -522,6 +523,21 @@ func keyNameToKeyCode(name string) (Key, bool) { {{end}}} return 0, false } + +// MarshalText implements encoding.TextMarshaler. +func (k Key) MarshalText() ([]byte, error) { + return []byte(k.String()), nil +} + +// UnmarshalText implements encoding.TextUnmarshaler +func (k *Key) UnmarshalText(text []byte) error { + key, ok := keyNameToKeyCode(string(text)) + if !ok { + return fmt.Errorf("ebiten: unexpected key name: %s", string(text)) + } + *k = key + return nil +} ` const uiKeysTmpl = `{{.License}} diff --git a/keys.go b/keys.go index 4a8bb1399..02e992445 100644 --- a/keys.go +++ b/keys.go @@ -17,6 +17,7 @@ package ebiten import ( + "fmt" "strings" "github.com/hajimehoshi/ebiten/v2/internal/ui" @@ -928,3 +929,18 @@ func keyNameToKeyCode(name string) (Key, bool) { } return 0, false } + +// MarshalText implements encoding.TextMarshaler. +func (k Key) MarshalText() ([]byte, error) { + return []byte(k.String()), nil +} + +// UnmarshalText implements encoding.TextUnmarshaler +func (k *Key) UnmarshalText(text []byte) error { + key, ok := keyNameToKeyCode(string(text)) + if !ok { + return fmt.Errorf("ebiten: unexpected key name: %s", string(text)) + } + *k = key + return nil +}