github.com/tidwall/go@v0.0.0-20170415222209-6694a6888b7d/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  import "cmd/internal/src"
     8  
     9  // from http://research.swtch.com/sparse
    10  // in turn, from Briggs and Torczon
    11  
    12  type sparseEntry struct {
    13  	key ID
    14  	val int32
    15  	aux src.XPos
    16  }
    17  
    18  type sparseMap struct {
    19  	dense  []sparseEntry
    20  	sparse []int32
    21  }
    22  
    23  // newSparseMap returns a sparseMap that can map
    24  // integers between 0 and n-1 to int32s.
    25  func newSparseMap(n int) *sparseMap {
    26  	return &sparseMap{dense: nil, sparse: make([]int32, n)}
    27  }
    28  
    29  func (s *sparseMap) size() int {
    30  	return len(s.dense)
    31  }
    32  
    33  func (s *sparseMap) contains(k ID) bool {
    34  	i := s.sparse[k]
    35  	return i < int32(len(s.dense)) && s.dense[i].key == k
    36  }
    37  
    38  // get returns the value for key k, or -1 if k does
    39  // not appear in the map.
    40  func (s *sparseMap) get(k ID) int32 {
    41  	i := s.sparse[k]
    42  	if i < int32(len(s.dense)) && s.dense[i].key == k {
    43  		return s.dense[i].val
    44  	}
    45  	return -1
    46  }
    47  
    48  func (s *sparseMap) set(k ID, v int32, a src.XPos) {
    49  	i := s.sparse[k]
    50  	if i < int32(len(s.dense)) && s.dense[i].key == k {
    51  		s.dense[i].val = v
    52  		s.dense[i].aux = a
    53  		return
    54  	}
    55  	s.dense = append(s.dense, sparseEntry{k, v, a})
    56  	s.sparse[k] = int32(len(s.dense)) - 1
    57  }
    58  
    59  // setBit sets the v'th bit of k's value, where 0 <= v < 32
    60  func (s *sparseMap) setBit(k ID, v uint) {
    61  	if v >= 32 {
    62  		panic("bit index too large.")
    63  	}
    64  	i := s.sparse[k]
    65  	if i < int32(len(s.dense)) && s.dense[i].key == k {
    66  		s.dense[i].val |= 1 << v
    67  		return
    68  	}
    69  	s.dense = append(s.dense, sparseEntry{k, 1 << v, src.NoXPos})
    70  	s.sparse[k] = int32(len(s.dense)) - 1
    71  }
    72  
    73  func (s *sparseMap) remove(k ID) {
    74  	i := s.sparse[k]
    75  	if i < int32(len(s.dense)) && s.dense[i].key == k {
    76  		y := s.dense[len(s.dense)-1]
    77  		s.dense[i] = y
    78  		s.sparse[y.key] = i
    79  		s.dense = s.dense[:len(s.dense)-1]
    80  	}
    81  }
    82  
    83  func (s *sparseMap) clear() {
    84  	s.dense = s.dense[:0]
    85  }
    86  
    87  func (s *sparseMap) contents() []sparseEntry {
    88  	return s.dense
    89  }