code.gitea.io/gitea@v1.19.3/modules/container/set.go (about)

     1  // Copyright 2022 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package container
     5  
     6  type Set[T comparable] map[T]struct{}
     7  
     8  // SetOf creates a set and adds the specified elements to it.
     9  func SetOf[T comparable](values ...T) Set[T] {
    10  	s := make(Set[T], len(values))
    11  	s.AddMultiple(values...)
    12  	return s
    13  }
    14  
    15  // Add adds the specified element to a set.
    16  // Returns true if the element is added; false if the element is already present.
    17  func (s Set[T]) Add(value T) bool {
    18  	if _, has := s[value]; !has {
    19  		s[value] = struct{}{}
    20  		return true
    21  	}
    22  	return false
    23  }
    24  
    25  // AddMultiple adds the specified elements to a set.
    26  func (s Set[T]) AddMultiple(values ...T) {
    27  	for _, value := range values {
    28  		s.Add(value)
    29  	}
    30  }
    31  
    32  // Contains determines whether a set contains the specified element.
    33  // Returns true if the set contains the specified element; otherwise, false.
    34  func (s Set[T]) Contains(value T) bool {
    35  	_, has := s[value]
    36  	return has
    37  }
    38  
    39  // Remove removes the specified element.
    40  // Returns true if the element is successfully found and removed; otherwise, false.
    41  func (s Set[T]) Remove(value T) bool {
    42  	if _, has := s[value]; has {
    43  		delete(s, value)
    44  		return true
    45  	}
    46  	return false
    47  }
    48  
    49  // Values gets a list of all elements in the set.
    50  func (s Set[T]) Values() []T {
    51  	keys := make([]T, 0, len(s))
    52  	for k := range s {
    53  		keys = append(keys, k)
    54  	}
    55  	return keys
    56  }