github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/utils/set/uint64set.go (about)

     1  // Copyright 2020 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package set
    16  
    17  import "sort"
    18  
    19  type Uint64Set struct {
    20  	uints map[uint64]bool
    21  }
    22  
    23  func NewUint64Set(uints []uint64) *Uint64Set {
    24  	l := len(uints)
    25  	if l < 16 {
    26  		l = 16
    27  	}
    28  
    29  	s := &Uint64Set{make(map[uint64]bool, l)}
    30  
    31  	for _, b := range uints {
    32  		s.uints[b] = true
    33  	}
    34  
    35  	return s
    36  }
    37  
    38  func (us *Uint64Set) Contains(i uint64) bool {
    39  	_, present := us.uints[i]
    40  	return present
    41  }
    42  
    43  func (us *Uint64Set) ContainsAll(uints []uint64) bool {
    44  	for _, b := range uints {
    45  		if _, present := us.uints[b]; !present {
    46  			return false
    47  		}
    48  	}
    49  
    50  	return true
    51  }
    52  
    53  func (us *Uint64Set) Add(vals ...uint64) {
    54  	for _, val := range vals {
    55  		us.uints[val] = true
    56  	}
    57  }
    58  
    59  func (us *Uint64Set) Remove(i uint64) {
    60  	delete(us.uints, i)
    61  }
    62  
    63  func (us *Uint64Set) Intersection(other *Uint64Set) *Uint64Set {
    64  	inter := &Uint64Set{uints: make(map[uint64]bool)}
    65  	for member := range us.uints {
    66  		if other.Contains(member) {
    67  			inter.Add(member)
    68  		}
    69  	}
    70  	return inter
    71  }
    72  
    73  func (us *Uint64Set) AsSlice() []uint64 {
    74  	sl := make([]uint64, 0, us.Size())
    75  	for k := range us.uints {
    76  		sl = append(sl, k)
    77  	}
    78  	sort.Slice(sl, func(i, j int) bool { return sl[i] < sl[j] })
    79  	return sl
    80  }
    81  
    82  func (us *Uint64Set) Size() int {
    83  	return len(us.uints)
    84  }
    85  
    86  func (us *Uint64Set) Iter(fn func(uint64)) {
    87  	for n := range us.uints {
    88  		fn(n)
    89  	}
    90  }