github.com/miolini/go@v0.0.0-20160405192216-fca68c8cb408/src/cmd/compile/internal/ssa/sparsemap.go (about)

     1  // Copyright 2015 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package ssa
     6  
     7  // from http://research.swtch.com/sparse
     8  // in turn, from Briggs and Torczon
     9  
    10  type sparseEntry struct {
    11  	key ID
    12  	val int32
    13  }
    14  
    15  type sparseMap struct {
    16  	dense  []sparseEntry
    17  	sparse []int
    18  }
    19  
    20  // newSparseMap returns a sparseMap that can map
    21  // integers between 0 and n-1 to int32s.
    22  func newSparseMap(n int) *sparseMap {
    23  	return &sparseMap{nil, make([]int, n)}
    24  }
    25  
    26  func (s *sparseMap) size() int {
    27  	return len(s.dense)
    28  }
    29  
    30  func (s *sparseMap) contains(k ID) bool {
    31  	i := s.sparse[k]
    32  	return i < len(s.dense) && s.dense[i].key == k
    33  }
    34  
    35  func (s *sparseMap) get(k ID) int32 {
    36  	i := s.sparse[k]
    37  	if i < len(s.dense) && s.dense[i].key == k {
    38  		return s.dense[i].val
    39  	}
    40  	return -1
    41  }
    42  
    43  func (s *sparseMap) set(k ID, v int32) {
    44  	i := s.sparse[k]
    45  	if i < len(s.dense) && s.dense[i].key == k {
    46  		s.dense[i].val = v
    47  		return
    48  	}
    49  	s.dense = append(s.dense, sparseEntry{k, v})
    50  	s.sparse[k] = len(s.dense) - 1
    51  }
    52  
    53  func (s *sparseMap) remove(k ID) {
    54  	i := s.sparse[k]
    55  	if i < len(s.dense) && s.dense[i].key == k {
    56  		y := s.dense[len(s.dense)-1]
    57  		s.dense[i] = y
    58  		s.sparse[y.key] = i
    59  		s.dense = s.dense[:len(s.dense)-1]
    60  	}
    61  }
    62  
    63  func (s *sparseMap) clear() {
    64  	s.dense = s.dense[:0]
    65  }
    66  
    67  func (s *sparseMap) contents() []sparseEntry {
    68  	return s.dense
    69  }