11package orderedmap
22
33import (
4+ "bytes"
5+ "errors"
46 "fmt"
7+ "reflect"
58
69 "gopkg.in/yaml.v3"
710)
1417// MarshalYAML implements the yaml.Marshaler interface.
1518func (om * OrderedMap [K , V ]) MarshalYAML () (interface {}, error ) {
1619 if om == nil {
17- return [] byte ( "null" ), nil
20+ return JSONNullBytes ( ), nil
1821 }
1922
2023 node := yaml.Node {
@@ -55,11 +58,30 @@ func (om *OrderedMap[K, V]) UnmarshalYAML(value *yaml.Node) error {
5558
5659 for index := 0 ; index < len (value .Content ); index += 2 {
5760 var key K
58- var val V
59-
6061 if err := value .Content [index ].Decode (& key ); err != nil {
6162 return err
6263 }
64+
65+ tValue := reflect .TypeFor [V ]()
66+ tValueKind := tValue .Kind ()
67+
68+ fmt .Printf ("tValueKind: %s\n " , tValueKind )
69+ var val V
70+
71+ if tValueKind == reflect .Interface {
72+ valueNode := value .Content [index + 1 ]
73+ if bytes .Equal ([]byte (valueNode .Value ), JSONNullBytes ()) {
74+ om .Set (key , val )
75+ continue
76+ }
77+
78+ om1 , err := tryDecodeToOrderedMap (value .Content [index + 1 ].Decode )
79+ if err == nil {
80+ om .Set (key , om1 .(V ))
81+ continue
82+ }
83+ }
84+
6385 if err := value .Content [index + 1 ].Decode (& val ); err != nil {
6486 return err
6587 }
@@ -69,3 +91,27 @@ func (om *OrderedMap[K, V]) UnmarshalYAML(value *yaml.Node) error {
6991
7092 return nil
7193}
94+
95+ // since yaml supports integers and strings as map keys, we need to try both
96+ func tryDecodeToOrderedMap (decoderFunc func (v any ) (err error )) (any , error ) {
97+ type newFunc func () any
98+
99+ possibilities := []newFunc {
100+ func () any { return New [int , any ]() },
101+ func () any { return New [int32 , any ]() },
102+ func () any { return New [int64 , any ]() },
103+ func () any { return New [uint , any ]() },
104+ func () any { return New [uint32 , any ]() },
105+ func () any { return New [uint64 , any ]() },
106+ func () any { return New [string , any ]() },
107+ }
108+
109+ for _ , possibilityFunc := range possibilities {
110+ possibility := possibilityFunc ()
111+ if err := decoderFunc (possibility ); err == nil {
112+ return possibility , nil
113+ }
114+ }
115+
116+ return nil , errors .New ("could not decode to an ordered map" )
117+ }
0 commit comments