github.com/dubbogo/gost@v1.14.0/container/set/hashset.go (about) 1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package gxset 19 20 import ( 21 "fmt" 22 "strings" 23 ) 24 25 var itemExists = struct{}{} 26 27 type HashSet struct { 28 Items map[interface{}]struct{} 29 } 30 31 func NewSet(values ...interface{}) *HashSet { 32 set := &HashSet{Items: make(map[interface{}]struct{})} 33 if len(values) > 0 { 34 set.Add(values...) 35 } 36 return set 37 } 38 39 func (set *HashSet) Add(items ...interface{}) { 40 for _, item := range items { 41 set.Items[item] = itemExists 42 } 43 } 44 45 func (set *HashSet) Remove(items ...interface{}) { 46 for _, item := range items { 47 delete(set.Items, item) 48 } 49 } 50 51 func (set *HashSet) Contains(items ...interface{}) bool { 52 for _, item := range items { 53 if _, contains := set.Items[item]; !contains { 54 return false 55 } 56 } 57 return true 58 } 59 60 func (set *HashSet) Empty() bool { 61 return set.Size() == 0 62 } 63 64 func (set *HashSet) Size() int { 65 return len(set.Items) 66 } 67 68 func (set *HashSet) Clear() { 69 set.Items = make(map[interface{}]struct{}) 70 } 71 72 func (set *HashSet) Values() []interface{} { 73 values := make([]interface{}, set.Size()) 74 count := 0 75 for item := range set.Items { 76 values[count] = item 77 count++ 78 } 79 return values 80 } 81 82 func (set *HashSet) String() string { 83 str := "HashSet\n" 84 var items []string 85 for k := range set.Items { 86 items = append(items, fmt.Sprintf("%v", k)) 87 } 88 str += strings.Join(items, ", ") 89 return str 90 }