Debian Codegraph @

sortedset/dedupe.go

raw
1 package sortedset
2
3 import (
4 "bytes"
5
6 "github.com/segmentio/asm/internal"
7 )
8
9 // Dedupe writes to dst the deduplicated sequence of items of the given size
10 // read from src, returning the byte slice containing the result.
11 //
12 // If dst is too small, a new slice is allocated and returned instead.
13 //
14 // The source and destination slices may be the same to perform in-place
15 // deduplication of the elements. The behavior is undefined for any other
16 // conditions where the source and destination slices overlap.
17 //
18 // The function panics if len(src) is not a multiple of the element size.
19 func Dedupe(dst, src []byte, size int) []byte {
20 if !internal.MultipleOf(size, len(src)) {
21 panic("input length is not a multiple of the item size")
22 }
23 if len(dst) < len(src) {
24 dst = make([]byte, len(src))
25 }
26 var n int
27 switch size {
28 case 1:
29 n = dedupe1(dst, src)
30 case 2:
31 n = dedupe2(dst, src)
32 case 4:
33 n = dedupe4(dst, src)
34 case 8:
35 n = dedupe8(dst, src)
36 case 16:
37 n = dedupe16(dst, src)
38 case 32:
39 n = dedupe32(dst, src)
40 default:
41 n = dedupeGeneric(dst, src, size)
42 }
43 return dst[:n]
44 }
45
46 func dedupeGeneric(dst, src []byte, size int) int {
47 if len(src) == 0 {
48 return 0
49 }
50
51 i := size
52 j := size
53 copy(dst, src[:size])
54
55 for i < len(src) {
56 if !bytes.Equal(src[i-size:i], src[i:i+size]) {
57 copy(dst[j:], src[i:i+size])
58 j += size
59 }
60 i += size
61 }
62
63 return j
64 }