Source file src/cmd/compile/internal/ssa/sparsemap.go

     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 https://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) cap() int {
    27  	return len(s.sparse)
    28  }
    29  
    30  func (s *sparseMap) size() int {
    31  	return len(s.dense)
    32  }
    33  
    34  func (s *sparseMap) contains(k ID) bool {
    35  	i := s.sparse[k]
    36  	return i < int32(len(s.dense)) && s.dense[i].key == k
    37  }
    38  
    39  // get returns the value for key k, or -1 if k does
    40  // not appear in the map.
    41  func (s *sparseMap) get(k ID) int32 {
    42  	i := s.sparse[k]
    43  	if i < int32(len(s.dense)) && s.dense[i].key == k {
    44  		return s.dense[i].val
    45  	}
    46  	return -1
    47  }
    48  
    49  func (s *sparseMap) set(k ID, v int32) {
    50  	i := s.sparse[k]
    51  	if i < int32(len(s.dense)) && s.dense[i].key == k {
    52  		s.dense[i].val = v
    53  		return
    54  	}
    55  	s.dense = append(s.dense, sparseEntry{k, v})
    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})
    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  }
    90  

View as plain text