Skip to content

Commit

Permalink
badjson: Refactor TypedMap to handle multiple key types
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Dec 21, 2023
1 parent 9cc051c commit a0cd94b
Showing 1 changed file with 8 additions and 9 deletions.
17 changes: 8 additions & 9 deletions common/json/badjson/typed.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import (
"github.com/sagernet/sing/common/x/linkedhashmap"
)

type TypedMap[T any] struct {
linkedhashmap.Map[string, T]
type TypedMap[K comparable, V any] struct {
linkedhashmap.Map[K, V]
}

func (m TypedMap[T]) MarshalJSON() ([]byte, error) {
func (m TypedMap[K, V]) MarshalJSON() ([]byte, error) {
buffer := new(bytes.Buffer)
buffer.WriteString("{")
items := m.Entries()
Expand All @@ -38,7 +38,7 @@ func (m TypedMap[T]) MarshalJSON() ([]byte, error) {
return buffer.Bytes(), nil
}

func (m *TypedMap[T]) UnmarshalJSON(content []byte) error {
func (m *TypedMap[K, V]) UnmarshalJSON(content []byte) error {
decoder := json.NewDecoder(bytes.NewReader(content))
m.Clear()
objectStart, err := decoder.Token()
Expand All @@ -60,15 +60,14 @@ func (m *TypedMap[T]) UnmarshalJSON(content []byte) error {
return nil
}

func (m *TypedMap[T]) decodeJSON(decoder *json.Decoder) error {
func (m *TypedMap[K, V]) decodeJSON(decoder *json.Decoder) error {
for decoder.More() {
var entryKey string
keyToken, err := decoder.Token()
var entryKey K
err := decoder.Decode(&entryKey)
if err != nil {
return err
}
entryKey = keyToken.(string)
var entryValue T
var entryValue V
err = decoder.Decode(&entryValue)
if err != nil {
return err
Expand Down

0 comments on commit a0cd94b

Please sign in to comment.