Files
node/utils/bimap/bimap.go
T
Hanzo AI c3b398bc7b json: migrate every encoding/json import to json/v2 (go-json-experiment)
External (HTTP / JSON-RPC) is the only place JSON is legitimate. Every
existing encoding/json import in node/ moves to github.com/go-json-experiment/json
(v2 root, not the v1 sub-package). NewEncoder/NewDecoder rewrite to
MarshalWrite/UnmarshalRead. MarshalIndent rewrites to Marshal with
jsontext.WithIndent. json.RawMessage rewrites to jsontext.Value.
*json.SyntaxError rewrites to *jsontext.SyntacticError.

81 files migrated. LLM.md captures the rule + v1->v2 delta table.

Known v2 semantic deltas surfaced by existing tests (followups, not regressions):
- [N]byte fields with no MarshalJSON now marshal as base64 string (v1 marshalled
  as JSON array of byte numbers). Affects vms/platformvm/txs/*_test.go fixtures
  with embedded BLS proofOfPossession.
- time.Duration has no v2 default representation; configs that wire-format
  Duration as nanoseconds (vms/{xvm,platformvm}/config, config/spec) need to
  switch to string-form Duration or carry an explicit option. v2 root does not
  re-export FormatDurationAsNano.
- v2 enforces strict UTF-8 (vms/chainadapter/messaging fixture has non-UTF-8).
- json.MarshalWrite does not append a trailing '\n' (v1 NewEncoder.Encode did);
  service/auth/auth_test.go expectation updated.
- nil []byte round-trips to empty (not nil); config_test deep-equal fixtures
  surface this.

All affected sites are at the API boundary; ZAP wire envelope already covers
the internal data paths (state, P2P, consensus, MPC, threshold). Internal
JSON sites that should move to ZAP next (separate work):
- vms/da/store.go            (DA blob/cert storage as JSON)
- vms/platformvm/airdrop     (airdrop claims as JSON in db)
- vms/chainadapter/appchain  (SQLite materializer schema/data blobs)
- vms/chainadapter/messaging (conversation codec)
- staking/kms.go             (KMS HTTP client — external technically, leave)
- utils/{bimap,ips}          (small marshaler shims — low priority)
2026-06-06 22:26:02 -07:00

155 lines
3.5 KiB
Go

// Copyright (C) 2019-2025, Lux Industries Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package bimap
import (
"bytes"
"github.com/go-json-experiment/json"
"errors"
"maps"
"slices"
"github.com/luxfi/node/utils"
)
var (
_ json.Marshaler = (*BiMap[int, int])(nil)
_ json.Unmarshaler = (*BiMap[int, int])(nil)
nullBytes = []byte("null")
errNotBijective = errors.New("map not bijective")
)
type Entry[K, V any] struct {
Key K
Value V
}
// BiMap is a bi-directional map.
type BiMap[K, V comparable] struct {
keyToValue map[K]V
valueToKey map[V]K
}
// New creates a new empty bimap.
func New[K, V comparable]() *BiMap[K, V] {
return &BiMap[K, V]{
keyToValue: make(map[K]V),
valueToKey: make(map[V]K),
}
}
// Put the key value pair into the map. If either [key] or [val] was previously
// in the map, the previous entries will be removed and returned.
//
// Note: Unlike normal maps, it's possible that Put removes 0, 1, or 2 existing
// entries to ensure that mappings are one-to-one.
func (m *BiMap[K, V]) Put(key K, val V) []Entry[K, V] {
var removed []Entry[K, V]
oldVal, oldValDeleted := m.DeleteKey(key)
if oldValDeleted {
removed = append(removed, Entry[K, V]{
Key: key,
Value: oldVal,
})
}
oldKey, oldKeyDeleted := m.DeleteValue(val)
if oldKeyDeleted {
removed = append(removed, Entry[K, V]{
Key: oldKey,
Value: val,
})
}
m.keyToValue[key] = val
m.valueToKey[val] = key
return removed
}
// GetKey that maps to the provided value.
func (m *BiMap[K, V]) GetKey(val V) (K, bool) {
key, ok := m.valueToKey[val]
return key, ok
}
// GetValue that is mapped to the provided key.
func (m *BiMap[K, V]) GetValue(key K) (V, bool) {
val, ok := m.keyToValue[key]
return val, ok
}
// HasKey returns true if [key] is in the map.
func (m *BiMap[K, _]) HasKey(key K) bool {
_, ok := m.keyToValue[key]
return ok
}
// HasValue returns true if [val] is in the map.
func (m *BiMap[_, V]) HasValue(val V) bool {
_, ok := m.valueToKey[val]
return ok
}
// DeleteKey removes [key] from the map and returns the value it mapped to.
func (m *BiMap[K, V]) DeleteKey(key K) (V, bool) {
val, ok := m.keyToValue[key]
if !ok {
return utils.Zero[V](), false
}
delete(m.keyToValue, key)
delete(m.valueToKey, val)
return val, true
}
// DeleteValue removes [val] from the map and returns the key that mapped to it.
func (m *BiMap[K, V]) DeleteValue(val V) (K, bool) {
key, ok := m.valueToKey[val]
if !ok {
return utils.Zero[K](), false
}
delete(m.keyToValue, key)
delete(m.valueToKey, val)
return key, true
}
// Keys returns the keys of the map. The keys will be in an indeterminate order.
func (m *BiMap[K, _]) Keys() []K {
return slices.Collect(maps.Keys(m.keyToValue))
}
// Values returns the values of the map. The values will be in an indeterminate
// order.
func (m *BiMap[_, V]) Values() []V {
return slices.Collect(maps.Values(m.keyToValue))
}
// Len return the number of entries in this map.
func (m *BiMap[K, V]) Len() int {
return len(m.keyToValue)
}
func (m *BiMap[K, V]) MarshalJSON() ([]byte, error) {
return json.Marshal(m.keyToValue)
}
func (m *BiMap[K, V]) UnmarshalJSON(b []byte) error {
if bytes.Equal(b, nullBytes) {
return nil
}
var keyToValue map[K]V
if err := json.Unmarshal(b, &keyToValue); err != nil {
return err
}
valueToKey := make(map[V]K, len(keyToValue))
for k, v := range keyToValue {
valueToKey[v] = k
}
if len(keyToValue) != len(valueToKey) {
return errNotBijective
}
m.keyToValue = keyToValue
m.valueToKey = valueToKey
return nil
}