| 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 Union(dst, a, b []byte, size int) []byte { |
| 12 |
if size <= 0 || !internal.PairMultipleOf(size, len(a), len(b)) { |
| 13 |
panic("input lengths must be a multiple of size") |
| 14 |
} |
| 15 |
if cap(dst) < len(a)+len(b) { |
| 16 |
panic("cap(dst) < len(a)+len(b)") |
| 17 |
} |
| 18 |
|
| 19 |
// Fast paths for non-overlapping sets. |
| 20 |
switch { |
| 21 |
case len(a) == 0: |
| 22 |
return dst[:copy(dst[:cap(dst)], b)] |
| 23 |
case len(b) == 0: |
| 24 |
return dst[:copy(dst[:cap(dst)], a)] |
| 25 |
case bytes.Compare(a[len(a)-size:], b[:size]) < 0: |
| 26 |
k := copy(dst[:len(a)], a) |
| 27 |
k += copy(dst[k:k+len(b)], b) |
| 28 |
return dst[:k] |
| 29 |
case bytes.Compare(b[len(b)-size:], a[:size]) < 0: |
| 30 |
k := copy(dst[:len(b)], b) |
| 31 |
k += copy(dst[k:k+len(a)], a) |
| 32 |
return dst[:k] |
| 33 |
} |
| 34 |
|
| 35 |
i, j, k := 0, 0, 0 |
| 36 |
switch { |
| 37 |
case size == 16 && cpu.X86.Has(x86.AVX): |
| 38 |
i, j, k = union16(dst, a, b) |
| 39 |
default: |
| 40 |
i, j, k = unionGeneric(dst, a, b, size) |
| 41 |
} |
| 42 |
|
| 43 |
if i < len(a) { |
| 44 |
k += copy(dst[k:k+len(a)-i], a[i:]) |
| 45 |
} else if j < len(b) { |
| 46 |
k += copy(dst[k:k+len(b)-j], b[j:]) |
| 47 |
} |
| 48 |
|
| 49 |
return dst[:k] |
| 50 |
} |
| 51 |
|
| 52 |
func unionGeneric(dst, a, b []byte, size int) (i, j, k int) { |
| 53 |
i, j, k = 0, 0, 0 |
| 54 |
for i < len(a) && j < len(b) { |
| 55 |
itemA := a[i : i+size] |
| 56 |
itemB := b[j : j+size] |
| 57 |
switch bytes.Compare(itemA, itemB) { |
| 58 |
case 0: |
| 59 |
copy(dst[k:k+size], itemA) |
| 60 |
i += size |
| 61 |
j += size |
| 62 |
case -1: |
| 63 |
copy(dst[k:k+size], itemA) |
| 64 |
i += size |
| 65 |
case 1: |
| 66 |
copy(dst[k:k+size], itemB) |
| 67 |
j += size |
| 68 |
} |
| 69 |
k += size |
| 70 |
} |
| 71 |
return |
| 72 |
} |