ebiten: add Key.MarshalText and Key.UnmarshalText

Closes #2133
This commit is contained in:
Hajime Hoshi 2022-06-24 03:12:53 +09:00
parent 7f26562531
commit a4d782da5b
2 changed files with 32 additions and 0 deletions

View File

@ -469,6 +469,7 @@ const ebitenKeysTmpl = `{{.License}}
package ebiten package ebiten
import ( import (
"fmt"
"strings" "strings"
"github.com/hajimehoshi/ebiten/v2/internal/ui" "github.com/hajimehoshi/ebiten/v2/internal/ui"
@ -522,6 +523,21 @@ func keyNameToKeyCode(name string) (Key, bool) {
{{end}}} {{end}}}
return 0, false 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}} const uiKeysTmpl = `{{.License}}

16
keys.go
View File

@ -17,6 +17,7 @@
package ebiten package ebiten
import ( import (
"fmt"
"strings" "strings"
"github.com/hajimehoshi/ebiten/v2/internal/ui" "github.com/hajimehoshi/ebiten/v2/internal/ui"
@ -928,3 +929,18 @@ func keyNameToKeyCode(name string) (Key, bool) {
} }
return 0, false 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
}