github.com/emcfarlane/larking@v0.0.0-20220605172417-1704b45ee6c3/starlib/starext/conv.go (about)

     1  package starext
     2  
     3  import (
     4  	"fmt"
     5  	"sort"
     6  
     7  	"go.starlark.net/starlark"
     8  )
     9  
    10  type Key interface {
    11  	string | int | float64
    12  }
    13  
    14  type Value interface {
    15  	string | int | float64 | bool
    16  }
    17  
    18  func toValue(v any) starlark.Value {
    19  	switch t := v.(type) {
    20  	case string:
    21  		return starlark.String(t)
    22  	case int:
    23  		return starlark.MakeInt(t)
    24  	case float64:
    25  		return starlark.Float(t)
    26  	case bool:
    27  		return starlark.Bool(t)
    28  	default:
    29  		panic(fmt.Errorf("unhandled type %T", v))
    30  	}
    31  }
    32  
    33  func ToDict[K Key, V Value](v map[K]V) *starlark.Dict {
    34  	// Sort keys, create dict.
    35  
    36  	keys := make([]K, 0, len(v))
    37  	for key := range v {
    38  		keys = append(keys, key)
    39  	}
    40  	sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
    41  
    42  	d := starlark.NewDict(len(v))
    43  	for _, key := range keys {
    44  		d.SetKey(toValue(key), toValue(v[key])) //nolint
    45  	}
    46  	return d
    47  }