github.com/anacrolix/torrent@v1.61.0/internal/nestedmaps/nestedmaps.go (about)

     1  package nestedmaps
     2  
     3  type next[NK comparable, M ~map[NK]NV, NV any] struct {
     4  	last Path[M]
     5  	key  NK
     6  }
     7  
     8  func (me next[NK, CV, NV]) Exists() bool {
     9  	_, ok := me.last.Get()[me.key]
    10  	return ok
    11  }
    12  
    13  func (me next[NK, CV, NV]) Get() NV {
    14  	return me.last.Get()[me.key]
    15  }
    16  
    17  func (me next[NK, CV, NV]) Set(value NV) {
    18  	if me.last.Get() == nil {
    19  		me.last.Set(make(CV))
    20  	}
    21  	me.last.Get()[me.key] = value
    22  }
    23  
    24  func (me next[NK, CV, NV]) Delete() {
    25  	m := me.last.Get()
    26  	delete(m, me.key)
    27  	if len(m) == 0 {
    28  		me.last.Delete()
    29  	}
    30  }
    31  
    32  func Next[K comparable, M ~map[K]V, V any](
    33  	last Path[M],
    34  	key K,
    35  ) Path[V] {
    36  	ret := next[K, M, V]{}
    37  	ret.last = last
    38  	ret.key = key
    39  	return ret
    40  }
    41  
    42  type root[K comparable, V any, M ~map[K]V] struct {
    43  	m *M
    44  }
    45  
    46  func (me root[K, V, M]) Exists() bool {
    47  	return *me.m != nil
    48  }
    49  
    50  func (me root[K, V, M]) Get() M {
    51  	return *me.m
    52  }
    53  
    54  func (me root[K, V, M]) Set(value M) {
    55  	*me.m = value
    56  }
    57  
    58  func (me root[K, V, M]) Delete() {
    59  	*me.m = nil
    60  }
    61  
    62  func Begin[K comparable, M ~map[K]V, V any](m *M) Path[M] {
    63  	ret := root[K, V, M]{}
    64  	ret.m = m
    65  	return ret
    66  }
    67  
    68  type Path[V any] interface {
    69  	Set(V)
    70  	Get() V
    71  	Exists() bool
    72  	Delete()
    73  }