github.com/searKing/golang/go@v1.2.117/container/hashset/hashset.go (about) 1 // Copyright 2020 The searKing Author. 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 hashset 6 7 import "errors" 8 9 // HashSet is an auto make set 10 type HashSet struct { 11 m map[any]struct{} 12 } 13 14 func New() *HashSet { 15 return &HashSet{} 16 } 17 18 // Init initializes or clears map m. 19 func (m *HashSet) Init() *HashSet { 20 m.m = make(map[any]struct{}) 21 return m 22 } 23 24 // lazyInit lazily initializes a zero map value. 25 func (m *HashSet) lazyInit() { 26 if m.m == nil { 27 m.Init() 28 } 29 } 30 31 func (m *HashSet) Keys() []any { 32 keys := []any{} 33 for key, _ := range m.m { 34 keys = append(keys, key) 35 } 36 return keys 37 } 38 39 // add adds Key to the head of the linked list. 40 func (m *HashSet) Add(key any) error { 41 m.lazyInit() 42 if _, ok := m.m[key]; ok { 43 return errors.New("Key was already in HashSet") 44 } 45 m.m[key] = struct{}{} 46 return nil 47 } 48 49 func (m *HashSet) AddOrUpdate(key any, value any) { 50 m.Remove(key) 51 m.Add(key) 52 } 53 54 // Remove removes Key from cl. 55 func (m *HashSet) Remove(key any) any { 56 if v, ok := m.m[key]; ok { 57 delete(m.m, key) 58 return v 59 } 60 return nil 61 } 62 63 func (m *HashSet) Clear() { 64 m.m = nil 65 } 66 func (m *HashSet) Find(key any) bool { 67 return m.Contains(key) 68 } 69 70 func (m *HashSet) Contains(key any) bool { 71 _, ok := m.m[key] 72 return ok 73 } 74 75 func (m *HashSet) Peek(key any) bool { 76 if m.Contains(key) { 77 m.Remove(key) 78 return true 79 } 80 return false 81 } 82 83 // Len returns the number of items in the cache. 84 func (m *HashSet) Len() int { 85 return len(m.m) 86 } 87 88 func (m *HashSet) Count() int { 89 return m.Len() 90 } 91 func (m *HashSet) Size() int { 92 return m.Len() 93 }