Debian Codegraph @

sortedset/intersect.go

raw
1 package sortedset
2
3 import (
4 "bytes"
5
6 "github.com/segmentio/asm/cpu"
7 "github.com/segmentio/asm/cpu/x86"
8 "github.com/segmentio/asm/internal"
9 )
10
11 func Intersect(dst, a, b []byte, size int) []byte {
12 if len(a) == 0 || len(b) == 0 {
13 return dst[:0]
14 }
15 if size <= 0 || !internal.PairMultipleOf(size, len(a), len(b)) {
16 panic("input lengths must be a multiple of size")
17 }
18 if cap(dst) < len(a) && cap(dst) < len(b) {
19 panic("cap(dst) < min(len(a),len(b))")
20 }
21
22 // Fast paths for non-overlapping sets.
23 if bytes.Compare(a[len(a)-size:], b[:size]) < 0 || bytes.Compare(b[len(b)-size:], a[:size]) < 0 {
24 return dst[:0]
25 }
26
27 var pos int
28 switch {
29 case size == 16 && cpu.X86.Has(x86.AVX):
30 pos = intersect16(dst, a, b)
31 default:
32 pos = intersectGeneric(dst, a, b, size)
33 }
34
35 return dst[:pos]
36 }
37
38 func intersectGeneric(dst, a, b []byte, size int) int {
39 i, j, k := 0, 0, 0
40 for i < len(a) && j < len(b) {
41 itemA := a[i : i+size]
42 itemB := b[j : j+size]
43 switch bytes.Compare(itemA, itemB) {
44 case 0:
45 copy(dst[k:k+size], itemA)
46 i += size
47 j += size
48 k += size
49 case -1:
50 i += size
51 case 1:
52 j += size
53 }
54 }
55 return k
56 }