cuelang.org/go@v0.13.0/encoding/jsonschema/valuemap.go (about)

     1  package jsonschema
     2  
     3  import (
     4  	"cuelang.org/go/cue"
     5  	"cuelang.org/go/cue/token"
     6  )
     7  
     8  // valueMap holds a map of values indexed by schema position
     9  // (a.k.a. JSON Pointer).
    10  //
    11  // It's designed so that it's cheap in the common case that a lookup
    12  // returns false and that there are many more lookups than
    13  // entries in the map.
    14  //
    15  // It does that by using the source position of the
    16  // schema as a first probe. Determining the source location of a value
    17  // is very cheap, and in most practical cases, JSON Schema is being
    18  // extracted from concrete JSON where there will be a bijective mapping
    19  // between source location and path.
    20  type valueMap[T any] struct {
    21  	byPos  map[token.Pos]bool
    22  	byPath map[string]T
    23  }
    24  
    25  func newValueMap[T any]() *valueMap[T] {
    26  	return &valueMap[T]{
    27  		byPos:  make(map[token.Pos]bool),
    28  		byPath: make(map[string]T),
    29  	}
    30  }
    31  
    32  func (m *valueMap[T]) len() int {
    33  	return len(m.byPath)
    34  }
    35  
    36  func (m *valueMap[T]) set(key cue.Value, v T) {
    37  	m.byPos[key.Pos()] = true
    38  	m.byPath[key.Path().String()] = v
    39  }
    40  
    41  func (m *valueMap[T]) get(key cue.Value) T {
    42  	if !m.byPos[key.Pos()] {
    43  		return *new(T)
    44  	}
    45  	return m.byPath[key.Path().String()]
    46  }
    47  
    48  func (m *valueMap[T]) lookup(key cue.Value) (T, bool) {
    49  	if !m.byPos[key.Pos()] {
    50  		return *new(T), false
    51  	}
    52  	v, ok := m.byPath[key.Path().String()]
    53  	return v, ok
    54  }