github.com/niubaoshu/goutils@v0.0.0-20180828035119-e8e576f66c2b/set.go (about)

     1  package goutils
     2  
     3  import (
     4  	"strconv"
     5  	"strings"
     6  	"sync"
     7  )
     8  
     9  type Set struct {
    10  	m map[int64]bool
    11  	sync.RWMutex
    12  }
    13  
    14  func NewSet() *Set {
    15  	return &Set{
    16  		m: map[int64]bool{},
    17  	}
    18  }
    19  
    20  func (s *Set) Add(item int64) {
    21  	s.Lock()
    22  	defer s.Unlock()
    23  	s.m[item] = true
    24  }
    25  
    26  func (s *Set) Remove(item int64) {
    27  	s.Lock()
    28  	s.Unlock()
    29  	delete(s.m, item)
    30  }
    31  
    32  func (s *Set) Has(item int64) bool {
    33  	s.RLock()
    34  	defer s.RUnlock()
    35  	_, ok := s.m[item]
    36  	return ok
    37  }
    38  
    39  func (s *Set) Len() int {
    40  	return len(s.List())
    41  }
    42  
    43  func (s *Set) Clear() {
    44  	s.Lock()
    45  	defer s.Unlock()
    46  	s.m = map[int64]bool{}
    47  }
    48  
    49  func (s *Set) IsEmpty() bool {
    50  	if s.Len() == 0 {
    51  		return true
    52  	}
    53  	return false
    54  }
    55  
    56  func (s *Set) String() string {
    57  	s.RLock()
    58  	defer s.RUnlock()
    59  	list := []string{}
    60  	for item := range s.m {
    61  		list = append(list, strconv.FormatInt(item, 10))
    62  	}
    63  	return strings.Join(list, ",")
    64  }
    65  
    66  func (s *Set) List() []int64 {
    67  	s.RLock()
    68  	defer s.RUnlock()
    69  	list := []int64{}
    70  	for item := range s.m {
    71  		list = append(list, item)
    72  	}
    73  	return list
    74  }