Skip to content

Commit

Permalink
new internal enum package
Browse files Browse the repository at this point in the history
  • Loading branch information
oxisto committed Jan 6, 2025
1 parent 8f6ccc1 commit 62ce487
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 17 deletions.
34 changes: 30 additions & 4 deletions internal/enum/valueof.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
package enum

import "fmt"
import (
"encoding/json"
"flag"
"fmt"
)

// Enum is an interface for enum types that support [flag.Value].
type Enum interface {
flag.Value
~int
}

// ValueOf returns the index of the value v in the name/index slice.
func ValueOf(v string, name string, index []uint8) int {
Expand All @@ -13,13 +23,29 @@ func ValueOf(v string, name string, index []uint8) int {
return -1
}

// Set sets the target to the value represented by v (using [ValueOf]).
func Set[T ~int](target *T, v string, name string, index []uint8) error {
// Set sets the target enum to the value represented by v (using [ValueOf]).
func Set[T Enum](enum *T, v string, name string, index []uint8) error {
i := ValueOf(v, name, index)
if i == -1 {
return fmt.Errorf("unknown value: %s", v)
} else {
*target = T(i)
*enum = T(i)
return nil
}
}

// MarshalJSON marshals the enum to JSON using the string representation.
func MarshalJSON[T Enum](enum T) ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, enum.String())), nil
}

// UnmarshalJSON unmarshals the enum from JSON. It expects a string
// representation.
func UnmarshalJSON[T Enum](enum T, data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}

return enum.Set(s)
}
18 changes: 5 additions & 13 deletions portfolio/accounts/type.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package accounts

import (
"encoding/json"
"fmt"

"github.com/oxisto/money-gopher/internal/enum"
)

Expand All @@ -27,23 +24,18 @@ func (t *AccountType) Get() any {
}

// Set implements [flag.Value].
func (t *AccountType) Set(v string) error {
return enum.Set(t, v, _AccountType_name, _AccountType_index[:])
func (t AccountType) Set(v string) error {
return enum.Set(&t, v, _AccountType_name, _AccountType_index[:])
}

// MarshalJSON marshals the account type to JSON using the string
// representation.
func (t AccountType) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, t.String())), nil
return enum.MarshalJSON(t)
}

// UnmarshalJSON unmarshals the account type from JSON. It expects a string
// representation.
func (t *AccountType) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}

return t.Set(s)
func (t AccountType) UnmarshalJSON(data []byte) error {
return enum.UnmarshalJSON(t, data)
}

0 comments on commit 62ce487

Please sign in to comment.