lib.mx raw

   1  package lib
   2  
   3  // Regression: sovereign (self-mutating) receivers own an arena. Mutations
   4  // through maps, slices and linked pointers must persist across method calls,
   5  // and a map's internal owner arena must survive the receiver.
   6  
   7  type Node struct {
   8  	next *Node
   9  	val  int32
  10  }
  11  
  12  type Obj interface {
  13  	Key() (s string)
  14  }
  15  
  16  type Named struct {
  17  	name string
  18  }
  19  
  20  func NewNamed(name string) (n *Named) {
  21  	return &Named{name: name}
  22  }
  23  
  24  func (n *Named) Key() (s string) { return n.name }
  25  
  26  type Store struct {
  27  	head  *Node
  28  	items []*Node
  29  	byKey map[string]Obj
  30  }
  31  
  32  func (s *Store) Add(k string, v int32) {
  33  	n := &Node{val: v}
  34  	n.next = s.head
  35  	s.head = n
  36  	s.items = push(s.items, n)
  37  	if s.byKey == nil {
  38  		s.byKey = map[string]Obj{}
  39  	}
  40  	s.byKey[k] = NewNamed(k)
  41  }
  42  
  43  func (s *Store) Sum() (n int32) {
  44  	p := s.head
  45  	for p != nil {
  46  		n += p.val
  47  		p = p.next
  48  	}
  49  	for _, q := range s.items {
  50  		n += q.val
  51  	}
  52  	return n
  53  }
  54  
  55  func (s *Store) KeyName(k string) (name string) {
  56  	o := s.byKey[k]
  57  	if o == nil {
  58  		return ""
  59  	}
  60  	return o.Key()
  61  }
  62