github.com/euank/go@v0.0.0-20160829210321-495514729181/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 []int32
    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{dense: nil, sparse: make([]int32, 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 < int32(len(s.dense)) && s.dense[i].key == k
    33  }
    34  
    35  // get returns the value for key k, or -1 if k does
    36  // not appear in the map.
    37  func (s *sparseMap) get(k ID) int32 {
    38  	i := s.sparse[k]
    39  	if i < int32(len(s.dense)) && s.dense[i].key == k {
    40  		return s.dense[i].val
    41  	}
    42  	return -1
    43  }
    44  
    45  func (s *sparseMap) set(k ID, v int32) {
    46  	i := s.sparse[k]
    47  	if i < int32(len(s.dense)) && s.dense[i].key == k {
    48  		s.dense[i].val = v
    49  		return
    50  	}
    51  	s.dense = append(s.dense, sparseEntry{k, v})
    52  	s.sparse[k] = int32(len(s.dense)) - 1
    53  }
    54  
    55  // setBit sets the v'th bit of k's value, where 0 <= v < 32
    56  func (s *sparseMap) setBit(k ID, v uint) {
    57  	if v >= 32 {
    58  		panic("bit index too large.")
    59  	}
    60  	i := s.sparse[k]
    61  	if i < int32(len(s.dense)) && s.dense[i].key == k {
    62  		s.dense[i].val |= 1 << v
    63  		return
    64  	}
    65  	s.dense = append(s.dense, sparseEntry{k, 1 << v})
    66  	s.sparse[k] = int32(len(s.dense)) - 1
    67  }
    68  
    69  func (s *sparseMap) remove(k ID) {
    70  	i := s.sparse[k]
    71  	if i < int32(len(s.dense)) && s.dense[i].key == k {
    72  		y := s.dense[len(s.dense)-1]
    73  		s.dense[i] = y
    74  		s.sparse[y.key] = i
    75  		s.dense = s.dense[:len(s.dense)-1]
    76  	}
    77  }
    78  
    79  func (s *sparseMap) clear() {
    80  	s.dense = s.dense[:0]
    81  }
    82  
    83  func (s *sparseMap) contents() []sparseEntry {
    84  	return s.dense
    85  }