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
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}}

16
keys.go
View File

@ -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
}