github.com/hamba/slices@v0.2.1-0.20220316050741-75c057d92699/intersect.go (about) 1 package slices 2 3 import ( 4 "unsafe" 5 ) 6 7 type intersectFn func(sptr, optr unsafe.Pointer) interface{} 8 9 // Intersect returns a slice with the intersection of slice and other. 10 // When the slices are the same, slice is returned. 11 func Intersect(slice, other interface{}) interface{} { 12 fn, ok := intersectOf(slice, other) 13 if fn == nil { 14 panic("slice is not supported slice type") 15 } 16 if !ok { 17 panic("other is not the same type as slice") 18 } 19 20 sptr := noescape(ptrOf(slice)) 21 optr := noescape(ptrOf(other)) 22 return fn(sptr, optr) 23 } 24 25 func intersectOf(slice, other interface{}) (intersectFn, bool) { 26 switch slice.(type) { 27 case []string: 28 _, ok := other.([]string) 29 return stringIntersect, ok 30 case []int: 31 _, ok := other.([]int) 32 return intIntersect, ok 33 case []int8: 34 _, ok := other.([]int8) 35 return int8Intersect, ok 36 case []int16: 37 _, ok := other.([]int16) 38 return int16Intersect, ok 39 case []int32: 40 _, ok := other.([]int32) 41 return int32Intersect, ok 42 case []int64: 43 _, ok := other.([]int64) 44 return int64Intersect, ok 45 case []uint: 46 _, ok := other.([]uint) 47 return uintIntersect, ok 48 case []uint8: 49 _, ok := other.([]uint8) 50 return uint8Intersect, ok 51 case []uint16: 52 _, ok := other.([]uint16) 53 return uint16Intersect, ok 54 case []uint32: 55 _, ok := other.([]uint32) 56 return uint32Intersect, ok 57 case []uint64: 58 _, ok := other.([]uint64) 59 return uint64Intersect, ok 60 case []float32: 61 _, ok := other.([]float32) 62 return float32Intersect, ok 63 case []float64: 64 _, ok := other.([]float64) 65 return float64Intersect, ok 66 } 67 return nil, false 68 }