Debian Codegraph @

chunker.go

raw
1 package desync
2
3 import (
4 "errors"
5 "fmt"
6 "io"
7 "math/bits"
8 )
9
10 // ChunkerWindowSize is the number of bytes in the rolling hash window
11 const ChunkerWindowSize = 48
12
13 func discriminatorFromAvg(avg uint64) uint32 {
14 return uint32(float64(avg) / (-1.42888852e-7*float64(avg) + 1.33237515))
15 }
16
17 // modInverse32 computes the modular multiplicative inverse of an odd number d
18 // modulo 2^32 using Newton's method. This is used for Lemire's fast
19 // divisibility test which replaces expensive hardware division.
20 func modInverse32(d uint32) uint32 {
21 x := d // d is odd, so d*d ≡ 1 (mod 4) is a valid start
22 x *= 2 - d*x // 3 bits
23 x *= 2 - d*x // 6 bits
24 x *= 2 - d*x // 12 bits
25 x *= 2 - d*x // 24 bits
26 x *= 2 - d*x // 48 bits → full 32-bit precision
27 return x
28 }
29
30 var hashTable = [256]uint32{
31 0x458be752, 0xc10748cc, 0xfbbcdbb8, 0x6ded5b68,
32 0xb10a82b5, 0x20d75648, 0xdfc5665f, 0xa8428801,
33 0x7ebf5191, 0x841135c7, 0x65cc53b3, 0x280a597c,
34 0x16f60255, 0xc78cbc3e, 0x294415f5, 0xb938d494,
35 0xec85c4e6, 0xb7d33edc, 0xe549b544, 0xfdeda5aa,
36 0x882bf287, 0x3116737c, 0x05569956, 0xe8cc1f68,
37 0x0806ac5e, 0x22a14443, 0x15297e10, 0x50d090e7,
38 0x4ba60f6f, 0xefd9f1a7, 0x5c5c885c, 0x82482f93,
39 0x9bfd7c64, 0x0b3e7276, 0xf2688e77, 0x8fad8abc,
40 0xb0509568, 0xf1ada29f, 0xa53efdfe, 0xcb2b1d00,
41 0xf2a9e986, 0x6463432b, 0x95094051, 0x5a223ad2,
42 0x9be8401b, 0x61e579cb, 0x1a556a14, 0x5840fdc2,
43 0x9261ddf6, 0xcde002bb, 0x52432bb0, 0xbf17373e,
44 0x7b7c222f, 0x2955ed16, 0x9f10ca59, 0xe840c4c9,
45 0xccabd806, 0x14543f34, 0x1462417a, 0x0d4a1f9c,
46 0x087ed925, 0xd7f8f24c, 0x7338c425, 0xcf86c8f5,
47 0xb19165cd, 0x9891c393, 0x325384ac, 0x0308459d,
48 0x86141d7e, 0xc922116a, 0xe2ffa6b6, 0x53f52aed,
49 0x2cd86197, 0xf5b9f498, 0xbf319c8f, 0xe0411fae,
50 0x977eb18c, 0xd8770976, 0x9833466a, 0xc674df7f,
51 0x8c297d45, 0x8ca48d26, 0xc49ed8e2, 0x7344f874,
52 0x556f79c7, 0x6b25eaed, 0xa03e2b42, 0xf68f66a4,
53 0x8e8b09a2, 0xf2e0e62a, 0x0d3a9806, 0x9729e493,
54 0x8c72b0fc, 0x160b94f6, 0x450e4d3d, 0x7a320e85,
55 0xbef8f0e1, 0x21d73653, 0x4e3d977a, 0x1e7b3929,
56 0x1cc6c719, 0xbe478d53, 0x8d752809, 0xe6d8c2c6,
57 0x275f0892, 0xc8acc273, 0x4cc21580, 0xecc4a617,
58 0xf5f7be70, 0xe795248a, 0x375a2fe9, 0x425570b6,
59 0x8898dcf8, 0xdc2d97c4, 0x0106114b, 0x364dc22f,
60 0x1e0cad1f, 0xbe63803c, 0x5f69fac2, 0x4d5afa6f,
61 0x1bc0dfb5, 0xfb273589, 0x0ea47f7b, 0x3c1c2b50,
62 0x21b2a932, 0x6b1223fd, 0x2fe706a8, 0xf9bd6ce2,
63 0xa268e64e, 0xe987f486, 0x3eacf563, 0x1ca2018c,
64 0x65e18228, 0x2207360a, 0x57cf1715, 0x34c37d2b,
65 0x1f8f3cde, 0x93b657cf, 0x31a019fd, 0xe69eb729,
66 0x8bca7b9b, 0x4c9d5bed, 0x277ebeaf, 0xe0d8f8ae,
67 0xd150821c, 0x31381871, 0xafc3f1b0, 0x927db328,
68 0xe95effac, 0x305a47bd, 0x426ba35b, 0x1233af3f,
69 0x686a5b83, 0x50e072e5, 0xd9d3bb2a, 0x8befc475,
70 0x487f0de6, 0xc88dff89, 0xbd664d5e, 0x971b5d18,
71 0x63b14847, 0xd7d3c1ce, 0x7f583cf3, 0x72cbcb09,
72 0xc0d0a81c, 0x7fa3429b, 0xe9158a1b, 0x225ea19a,
73 0xd8ca9ea3, 0xc763b282, 0xbb0c6341, 0x020b8293,
74 0xd4cd299d, 0x58cfa7f8, 0x91b4ee53, 0x37e4d140,
75 0x95ec764c, 0x30f76b06, 0x5ee68d24, 0x679c8661,
76 0xa41979c2, 0xf2b61284, 0x4fac1475, 0x0adb49f9,
77 0x19727a23, 0x15a7e374, 0xc43a18d5, 0x3fb1aa73,
78 0x342fc615, 0x924c0793, 0xbee2d7f0, 0x8a279de9,
79 0x4aa2d70c, 0xe24dd37f, 0xbe862c0b, 0x177c22c2,
80 0x5388e5ee, 0xcd8a7510, 0xf901b4fd, 0xdbc13dbc,
81 0x6c0bae5b, 0x64efe8c7, 0x48b02079, 0x80331a49,
82 0xca3d8ae6, 0xf3546190, 0xfed7108b, 0xc49b941b,
83 0x32baf4a9, 0xeb833a4a, 0x88a3f1a5, 0x3a91ce0a,
84 0x3cc27da1, 0x7112e684, 0x4a3096b1, 0x3794574c,
85 0xa3c8b6f3, 0x1d213941, 0x6e0a2e00, 0x233479f1,
86 0x0f4cd82f, 0x6093edd2, 0x5d7d209e, 0x464fe319,
87 0xd4dcac9e, 0x0db845cb, 0xfb5e4bc3, 0xe0256ce1,
88 0x09fb4ed1, 0x0914be1e, 0xa5bdb2c3, 0xc6eb57bb,
89 0x30320350, 0x3f397e91, 0xa67791bc, 0x86bc0e2c,
90 0xefa0a7e2, 0xe9ff7543, 0xe733612c, 0xd185897b,
91 0x329e5388, 0x91dd236b, 0x2ecb0d93, 0xf4d82a3d,
92 0x35b5c03f, 0xe4e606f0, 0x05b21843, 0x37b45964,
93 0x5eff22f4, 0x6027f4cc, 0x77178b3c, 0xae507131,
94 0x7bf7cabc, 0xf9c18d66, 0x593ade65, 0xd95ddf11,
95 }
96
97 // hashTableRotated contains hashTable values pre-rotated by ChunkerWindowSize,
98 // eliminating a RotateLeft32 call per byte in the hot loop.
99 var hashTableRotated [256]uint32
100
101 func init() {
102 for i := range hashTable {
103 hashTableRotated[i] = bits.RotateLeft32(hashTable[i], ChunkerWindowSize)
104 }
105 }
106
107 // Chunker is used to break up a data stream into chunks of data.
108 type Chunker struct {
109 r io.Reader
110 min, avg, max uint64
111
112 start uint64
113
114 buf []byte
115 backingBuf []byte // reusable backing buffer for fillBuffer
116 hitEOF bool // true once the reader returned EOF
117
118 hDiscriminator uint32
119
120 // Precomputed constants for the boundary test "hValue % d == d-1",
121 // evaluated without hardware division as "hValue+1 is divisible by d".
122 // Factor d = oddPart * 2^k, then (Hacker's Delight §10-17):
123 // v divisible by d ⟺ rotr32(v*inverse(oddPart), k) <= (2^32-1)/d
124 // hValue+1 wraps to 0 for hValue == 2^32-1, where the true remainder is
125 // d-1 only if d is a power of two; hQBias shifts the comparison to
126 // exclude exactly that wrapped case when d has an odd factor.
127 hInverseOdd uint32 // modular inverse of odd part of hDiscriminator
128 hQMax uint32 // (2^32-1)/hDiscriminator - hQBias
129 hQBias uint32 // 1 if hDiscriminator has an odd factor, else 0
130 hRot int // -k, right-rotation by the power-of-2 factor
131 }
132
133 // NewChunker initializes a chunker for a data stream according to min/avg/max chunk size.
134 func NewChunker(r io.Reader, min, avg, max uint64) (Chunker, error) {
135 if min < ChunkerWindowSize {
136 return Chunker{}, fmt.Errorf("min chunk size too small, must be over %d", ChunkerWindowSize)
137 }
138 if min > max {
139 return Chunker{}, errors.New("min chunk size must not be greater than max")
140 }
141 if min > avg {
142 return Chunker{}, errors.New("min chunk size must not be greater than avg")
143 }
144 if avg > max {
145 return Chunker{}, errors.New("avg chunk size must not be greater than max")
146 }
147 disc := discriminatorFromAvg(avg)
148
149 // Precompute the fast divisibility constants, see the Chunker struct
150 // for how they are used. We test "hValue % disc == disc-1" as
151 // "hValue+1 is divisible by disc" with disc = oddPart * 2^k.
152 k := uint(bits.TrailingZeros32(disc))
153 oddPart := disc >> k
154 inverseOdd := modInverse32(oddPart)
155 var qBias uint32
156 if oddPart > 1 {
157 qBias = 1
158 }
159
160 return Chunker{
161 r: r,
162 min: min,
163 avg: avg,
164 max: max,
165 hDiscriminator: disc,
166 hInverseOdd: inverseOdd,
167 hQMax: ^uint32(0)/disc - qBias,
168 hQBias: qBias,
169 hRot: -int(k),
170 }, nil
171 }
172
173 // Make a new buffer with 10*max bytes and copy anything that may be leftover
174 // from before into it, then fill it up with new bytes. Don't fail on EOF.
175 func (c *Chunker) fillBuffer() (n int, err error) {
176 if c.hitEOF { // We won't get anymore here, no need for more allocations
177 return
178 }
179 size := 10 * c.max
180 // Reuse the backing buffer if it has sufficient capacity
181 var buf []byte
182 if uint64(cap(c.backingBuf)) >= size {
183 buf = c.backingBuf[:size]
184 } else {
185 buf = make([]byte, int(size))
186 c.backingBuf = buf
187 }
188 n = copy(buf, c.buf) // copy the remaining bytes from the old buffer
189 for uint64(n) < size && err == nil { // read until the buffer is at max or we get an EOF
190 var nn int
191 nn, err = c.r.Read(buf[n:])
192 n += nn
193 }
194 c.buf = buf[:n] // we are not going to get any more, resize the buffer
195 if err == io.EOF {
196 c.hitEOF = true
197 err = nil
198 }
199 return
200 }
201
202 // Next returns the starting position as well as the chunk data. Returns
203 // an empty byte slice when complete. The returned byte slice is only valid
204 // until the next call to Next; callers that pass the slice to other
205 // goroutines must copy it first.
206 func (c *Chunker) Next() (uint64, []byte, error) {
207 if len(c.buf) < int(c.max) {
208 n, err := c.fillBuffer()
209 if err != nil {
210 return c.split(n, err)
211 }
212 }
213
214 // No need to carry on if we don't have enough bytes left to even fill the min chunk
215 if len(c.buf) <= int(c.min) {
216 return c.split(len(c.buf), nil)
217 }
218
219 // m is the upper boundary for the current chunk. It's either c.max if we have
220 // enough bytes in the buffer, or len(c.buf)
221 m := min(len(c.buf), int(c.max))
222
223 // Initialize the rolling hash over the ChunkerWindowSize bytes
224 // immediately prior to min size
225 var hValue uint32
226 for i, b := range c.buf[c.min-ChunkerWindowSize : c.min] {
227 hValue ^= bits.RotateLeft32(hashTable[b], ChunkerWindowSize-i-1)
228 }
229
230 // The window bytes all live in c.buf, so instead of maintaining a ring
231 // buffer, the byte leaving the window at position pos is simply
232 // c.buf[pos-ChunkerWindowSize]. in and out are the incoming and
233 // outgoing byte ranges, sliced to equal length n.
234 base := int(c.min)
235 n := m - base
236 in := c.buf[base : base+n]
237 out := c.buf[base-ChunkerWindowSize : base-ChunkerWindowSize+n]
238
239 // Hoist frequently accessed struct fields and the table addresses into
240 // locals to avoid repeated pointer dereferences in the hot loop.
241 inverseOdd := c.hInverseOdd
242 qMax := c.hQMax
243 qBias := c.hQBias
244 rot := c.hRot
245 ht := &hashTable
246 htr := &hashTableRotated
247
248 // Process two bytes per iteration. Rolling one byte is
249 // h' = rol1(h) ^ a, with a = hashTableRotated[out] ^ hashTable[in].
250 // Rotation distributes over xor, so two bytes at once is
251 // h'' = rol2(h) ^ rol1(a0) ^ a1, which shortens the loop-carried
252 // dependency chain from two rotate+xor pairs to one rotate and two
253 // xors per two bytes; the table loads, the intermediate hash h1 and
254 // the boundary tests all run off the critical path.
255 //
256 // The boundary test "h % d == d-1" is evaluated as "h+1 divisible
257 // by d" using the multiply-and-rotate divisibility test; see the
258 // Chunker struct for the derivation of the constants.
259 for i := 0; i+1 < n; i += 2 {
260 a0 := htr[out[i]] ^ ht[in[i]]
261 a1 := htr[out[i+1]] ^ ht[in[i+1]]
262 h1 := bits.RotateLeft32(hValue, 1) ^ a0
263 hValue = bits.RotateLeft32(hValue, 2) ^ bits.RotateLeft32(a0, 1) ^ a1
264
265 if bits.RotateLeft32((h1+1)*inverseOdd, rot)-qBias <= qMax {
266 return c.split(base+i+1, nil)
267 }
268 if bits.RotateLeft32((hValue+1)*inverseOdd, rot)-qBias <= qMax {
269 return c.split(base+i+2, nil)
270 }
271 }
272
273 // No boundary found before reaching the max chunk size. If n is odd, the
274 // leftover byte needs no processing: a boundary there would split at m
275 // anyway, and the hash state is discarded on split.
276 return c.split(m, nil)
277 }
278
279 func (c *Chunker) split(i int, err error) (uint64, []byte, error) {
280 // save the remaining bytes (after the split position) for the next round
281 start := c.start
282 b := c.buf[:i]
283 c.buf = c.buf[i:]
284 c.start += uint64(i)
285 return start, b, err
286 }
287
288 // Advance n bytes without producing chunks. This can be used if the content of the next
289 // section in the file is known (i.e. it is known that there are a number of null chunks
290 // coming). This resets everything in the chunker and behaves as if the streams starts
291 // at (current position+n).
292 func (c *Chunker) Advance(n int) error {
293 // We might still have bytes in the buffer. These count towards the move forward.
294 // It's possible the advance stays within the buffer and doesn't impact the reader.
295 c.start += uint64(n)
296 if n <= len(c.buf) {
297 c.buf = c.buf[n:]
298 return nil
299 }
300 readerN := int64(n - len(c.buf))
301 c.buf = nil
302 rs, ok := c.r.(io.Seeker)
303 if ok {
304 _, err := rs.Seek(readerN, io.SeekCurrent)
305 return err
306 }
307 _, err := io.CopyN(io.Discard, c.r, readerN)
308 return err
309 }
310
311 // Min returns the minimum chunk size
312 func (c *Chunker) Min() uint64 { return c.min }
313
314 // Avg returns the average chunk size
315 func (c *Chunker) Avg() uint64 { return c.avg }
316
317 // Max returns the maximum chunk size
318 func (c *Chunker) Max() uint64 { return c.max }
319
320 // Hash implements the rolling hash algorithm used to find chunk boundaries
321 // in a stream of bytes.
322 type Hash struct {
323 value uint32
324 window []byte
325 size int
326 idx int
327 discriminator uint32
328 }
329
330 // NewHash returns a new instance of a hash. size determines the length of the
331 // hash window used and the discriminator is used to find the boundary.
332 func NewHash(size int, discriminator uint32) Hash {
333 return Hash{
334 window: make([]byte, size),
335 size: size,
336 discriminator: discriminator,
337 }
338 }
339
340 // Roll adds a new byte to the hash calculation. No useful value is returned until
341 // the hash window has been populated.
342 func (h *Hash) Roll(b byte) {
343 ob := h.window[h.idx]
344 h.window[h.idx] = b
345 h.idx = (h.idx + 1) % h.size
346
347 h.value = bits.RotateLeft32(h.value, 1) ^
348 bits.RotateLeft32(hashTable[ob], len(h.window)) ^
349 hashTable[b]
350 }
351
352 // Initialize the window used for the rolling hash calculation. The size of the
353 // slice must match the window size
354 func (h *Hash) Initialize(b []byte) {
355 for i, c := range b {
356 h.value ^= bits.RotateLeft32(hashTable[c], h.size-i-1)
357 }
358 copy(h.window, b)
359 }
360
361 // IsBoundary returns true if the discriminator and hash match to signal a
362 // chunk boundary has been reached
363 func (h *Hash) IsBoundary() bool {
364 return h.value%h.discriminator == h.discriminator-1
365 }
366
367 // Reset the hash window and value
368 func (h *Hash) Reset() {
369 h.idx = 0
370 h.value = 0
371 }