github.com/haraldrudell/parl@v0.4.176/pfs/registry.go (about)

     1  /*
     2  © 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package pfs
     7  
     8  // Registry stores values that are accessible by index or by
     9  // absolute path
    10  type Registry[V any] struct {
    11  	// path provides O(1) access to values
    12  	//	- mappings are deleted by DeleteByIndex
    13  	paths  map[string]*V
    14  	values []*pathTuple[V]
    15  }
    16  
    17  // pathTuple holds a value and the key for that value in the paths map
    18  type pathTuple[V any] struct {
    19  	abs   string
    20  	value *V
    21  }
    22  
    23  // NewRegistry returns a registry of values by absolute path
    24  func NewRegistry[V any]() (registry *Registry[V]) { return &Registry[V]{paths: make(map[string]*V)} }
    25  
    26  // Add adds a value to the registry
    27  func (r *Registry[V]) Add(abs string, value *V) {
    28  	r.paths[abs] = value
    29  	r.values = append(r.values, &pathTuple[V]{
    30  		abs:   abs,
    31  		value: value,
    32  	})
    33  }
    34  
    35  // HasAbs check whether an absolute path is stored in the registry
    36  // as a key to a value
    37  func (r *Registry[V]) HasAbs(abs string) (hasAbs bool) {
    38  	_, hasAbs = r.paths[abs]
    39  	return
    40  }
    41  
    42  // ListLength returns the length of the value slice
    43  //   - a value can still be nil for a discarded root
    44  func (r *Registry[V]) ListLength() (length int) { return len(r.values) }
    45  
    46  // GetValue retrieves value by index
    47  //   - if index is less than 0 or too large or for a removed
    48  //     value, nil is returned
    49  func (r *Registry[V]) GetValue(index int) (value *V) {
    50  	if index >= 0 && index < len(r.values) {
    51  		if tp := r.values[index]; tp != nil {
    52  			value = tp.value
    53  		}
    54  	}
    55  	return
    56  }
    57  
    58  func (r *Registry[V]) ObsoleteIndex(index int) {
    59  	if index < 0 && index >= len(r.values) {
    60  		return
    61  	}
    62  	var tuple = r.values[index]
    63  	tuple.value = nil
    64  	delete(r.paths, tuple.abs)
    65  }