github.com/hamba/slices@v0.2.1-0.20220316050741-75c057d92699/contains.go (about) 1 package slices 2 3 import ( 4 "unsafe" 5 ) 6 7 type containsFn func(sptr, vptr unsafe.Pointer) bool 8 9 // Contains determines if the slice contains val. 10 func Contains(slice, val interface{}) bool { 11 fn, ok := containsOf(slice, val) 12 if fn == nil { 13 panic("slice is not supported slice type") 14 } 15 if !ok { 16 panic("val is not the same type as slice") 17 } 18 19 sptr := noescape(ptrOf(slice)) 20 vptr := noescape(ptrOf(val)) 21 return fn(sptr, vptr) 22 } 23 24 func containsOf(slice, val interface{}) (containsFn, bool) { 25 switch slice.(type) { 26 case []bool: 27 _, ok := val.(bool) 28 return boolContains, ok 29 case []string: 30 _, ok := val.(string) 31 return stringContains, ok 32 case []int: 33 _, ok := val.(int) 34 return intContains, ok 35 case []int8: 36 _, ok := val.(int8) 37 return int8Contains, ok 38 case []int16: 39 _, ok := val.(int16) 40 return int16Contains, ok 41 case []int32: 42 _, ok := val.(int32) 43 return int32Contains, ok 44 case []int64: 45 _, ok := val.(int64) 46 return int64Contains, ok 47 case []uint: 48 _, ok := val.(uint) 49 return uintContains, ok 50 case []uint8: 51 _, ok := val.(uint8) 52 return uint8Contains, ok 53 case []uint16: 54 _, ok := val.(uint16) 55 return uint16Contains, ok 56 case []uint32: 57 _, ok := val.(uint32) 58 return uint32Contains, ok 59 case []uint64: 60 _, ok := val.(uint64) 61 return uint64Contains, ok 62 case []float32: 63 _, ok := val.(float32) 64 return float32Contains, ok 65 case []float64: 66 _, ok := val.(float64) 67 return float64Contains, ok 68 } 69 return nil, false 70 }