Debian Codegraph @

third-party/xxhash/doc/xxhash_spec.md

raw
1 xxHash fast digest algorithm
2 ======================
3
4 ### Notices
5
6 Copyright (c) Yann Collet
7
8 Permission is granted to copy and distribute this document
9 for any purpose and without charge,
10 including translations into other languages
11 and incorporation into compilations,
12 provided that the copyright notice and this notice are preserved,
13 and that any substantive changes or deletions from the original
14 are clearly marked.
15 Distribution of this document is unlimited.
16
17 ### Version
18
19 0.2.0 (29/06/23)
20
21
22 Table of Contents
23 ---------------------
24 - [Introduction](#introduction)
25 - [XXH32 algorithm description](#xxh32-algorithm-description)
26 - [XXH64 algorithm description](#xxh64-algorithm-description)
27 - [XXH3 algorithm description](#xxh3-algorithm-overview)
28 - [Small inputs](#xxh3-algorithm-description-for-small-inputs)
29 - [Medium inputs](#xxh3-algorithm-description-for-medium-inputs)
30 - [Large inputs](#xxh3-algorithm-description-for-large-inputs)
31 - [Performance considerations](#performance-considerations)
32 - [Reference Implementation](#reference-implementation)
33
34
35 Introduction
36 ----------------
37
38 This document describes the xxHash digest algorithm for both 32-bit and 64-bit variants, named `XXH32` and `XXH64`. The algorithm takes an input a message of arbitrary length and an optional seed value, then produces an output of 32 or 64-bit as "fingerprint" or "digest".
39
40 xxHash is primarily designed for speed. It is labeled non-cryptographic, and is not meant to avoid intentional collisions (same digest for 2 different messages), or to prevent producing a message with a predefined digest.
41
42 XXH32 is designed to be fast on 32-bit machines.
43 XXH64 is designed to be fast on 64-bit machines.
44 Both variants produce different output.
45 However, a given variant shall produce exactly the same output, irrespective of the cpu / os used. In particular, the result remains identical whatever the endianness and width of the cpu is.
46
47 ### Operation notations
48
49 All operations are performed modulo {32,64} bits. Arithmetic overflows are expected.
50 `XXH32` uses 32-bit modular operations.
51 `XXH64` and `XXH3` use 64-bit modular operations.
52 When an operation ingests input or secret as multi-bytes values, it reads it using little-endian convention.
53
54 - `+`: denotes modular addition
55 - `-`: denotes modular subtraction
56 - `*`: denotes modular multiplication
57 - **Exception:** In `XXH3`, if it is in the form `(u128)x * (u128)y`, it denotes 64-bit by 64-bit normal multiplication into a full 128-bit result.
58 - `X <<< s`: denotes the value obtained by circularly shifting (rotating) `X` left by `s` bit positions.
59 - `X >> s`: denotes the value obtained by shifting `X` right by s bit positions. Upper `s` bits become `0`.
60 - `X << s`: denotes the value obtained by shifting `X` left by s bit positions. Lower `s` bits become `0`.
61 - `X xor Y`: denotes the bit-wise XOR of `X` and `Y` (same width).
62 - `X | Y`: denotes the bit-wise OR of `X` and `Y` (same width).
63 - `~X`: denotes the bit-wise negation of `X`.
64
65
66 XXH32 Algorithm Description
67 -------------------------------------
68
69 ### Overview
70
71 We begin by supposing that we have a message of any length `L` as input, and that we wish to find its digest. Here `L` is an arbitrary nonnegative integer; `L` may be zero. The following steps are performed to compute the digest of the message.
72
73 The algorithm collect and transform input in _stripes_ of 16 bytes. The transforms are stored inside 4 "accumulators", each one storing an unsigned 32-bit value. Each accumulator can be processed independently in parallel, speeding up processing for cpu with multiple execution units.
74
75 The algorithm uses 32-bits addition, multiplication, rotate, shift and xor operations. Many operations require some 32-bits prime number constants, all defined below:
76
77 ```c
78 static const u32 PRIME32_1 = 0x9E3779B1U; // 0b10011110001101110111100110110001
79 static const u32 PRIME32_2 = 0x85EBCA77U; // 0b10000101111010111100101001110111
80 static const u32 PRIME32_3 = 0xC2B2AE3DU; // 0b11000010101100101010111000111101
81 static const u32 PRIME32_4 = 0x27D4EB2FU; // 0b00100111110101001110101100101111
82 static const u32 PRIME32_5 = 0x165667B1U; // 0b00010110010101100110011110110001
83 ```
84
85 These constants are prime numbers, and feature a good mix of bits 1 and 0, neither too regular, nor too dissymmetric. These properties help dispersion capabilities.
86
87 ### Step 1. Initialize internal accumulators
88
89 Each accumulator gets an initial value based on optional `seed` input. Since the `seed` is optional, it can be `0`.
90
91 ```c
92 u32 acc1 = seed + PRIME32_1 + PRIME32_2;
93 u32 acc2 = seed + PRIME32_2;
94 u32 acc3 = seed + 0;
95 u32 acc4 = seed - PRIME32_1;
96 ```
97
98 #### Special case: input is less than 16 bytes
99
100 When the input is too small (< 16 bytes), the algorithm will not process any stripes. Consequently, it will not make use of parallel accumulators.
101
102 In this case, a simplified initialization is performed, using a single accumulator:
103
104 ```c
105 u32 acc = seed + PRIME32_5;
106 ```
107
108 The algorithm then proceeds directly to step 4.
109
110 ### Step 2. Process stripes
111
112 A stripe is a contiguous segment of 16 bytes.
113 It is evenly divided into 4 _lanes_, of 4 bytes each.
114 The first lane is used to update accumulator 1, the second lane is used to update accumulator 2, and so on.
115
116 Each lane read its associated 32-bit value using __little-endian__ convention.
117
118 For each {lane, accumulator}, the update process is called a _round_, and applies the following formula:
119
120 ```c
121 accN = accN + (laneN * PRIME32_2);
122 accN = accN <<< 13;
123 accN = accN * PRIME32_1;
124 ```
125
126 This shuffles the bits so that any bit from input _lane_ impacts several bits in output _accumulator_. All operations are performed modulo 2^32.
127
128 Input is consumed one full stripe at a time. Step 2 is looped as many times as necessary to consume the whole input, except for the last remaining bytes which cannot form a stripe (< 16 bytes).
129 When that happens, move to step 3.
130
131 ### Step 3. Accumulator convergence
132
133 All 4 lane accumulators from the previous steps are merged to produce a single remaining accumulator of the same width (32-bit). The associated formula is as follows:
134
135 ```c
136 acc = (acc1 <<< 1) + (acc2 <<< 7) + (acc3 <<< 12) + (acc4 <<< 18);
137 ```
138
139 ### Step 4. Add input length
140
141 The input total length is presumed known at this stage. This step is just about adding the length to accumulator, so that it participates to final mixing.
142
143 ```c
144 acc = acc + (u32)inputLength;
145 ```
146
147 Note that, if input length is so large that it requires more than 32-bits, only the lower 32-bits are added to the accumulator.
148
149 ### Step 5. Consume remaining input
150
151 There may be up to 15 bytes remaining to consume from the input.
152 The final stage will digest them according to following pseudo-code:
153
154 ```c
155 while (remainingLength >= 4) {
156 lane = read_32bit_little_endian(input_ptr);
157 acc = acc + lane * PRIME32_3;
158 acc = (acc <<< 17) * PRIME32_4;
159 input_ptr += 4; remainingLength -= 4;
160 }
161
162 while (remainingLength >= 1) {
163 lane = read_byte(input_ptr);
164 acc = acc + lane * PRIME32_5;
165 acc = (acc <<< 11) * PRIME32_1;
166 input_ptr += 1; remainingLength -= 1;
167 }
168 ```
169
170 This process ensures that all input bytes are present in the final mix.
171
172 ### Step 6. Final mix (avalanche)
173
174 The final mix ensures that all input bits have a chance to impact any bit in the output digest, resulting in an unbiased distribution. This is also called avalanche effect.
175
176 ```c
177 acc = acc xor (acc >> 15);
178 acc = acc * PRIME32_2;
179 acc = acc xor (acc >> 13);
180 acc = acc * PRIME32_3;
181 acc = acc xor (acc >> 16);
182 ```
183
184 ### Step 7. Output
185
186 The `XXH32()` function produces an unsigned 32-bit value as output.
187
188 For systems which require to store and/or display the result in binary or hexadecimal format, the canonical format is defined to reproduce the same value as the natural decimal format, hence follows __big-endian__ convention (most significant byte first).
189
190
191 XXH64 Algorithm Description
192 -------------------------------------
193
194 ### Overview
195
196 `XXH64`'s algorithm structure is very similar to `XXH32` one. The major difference is that `XXH64` uses 64-bit arithmetic, speeding up memory transfer for 64-bit compliant systems, but also relying on cpu capability to efficiently perform 64-bit operations.
197
198 The algorithm collects and transforms input in _stripes_ of 32 bytes. The transforms are stored inside 4 "accumulators", each one storing an unsigned 64-bit value. Each accumulator can be processed independently in parallel, speeding up processing for cpu with multiple execution units.
199
200 The algorithm uses 64-bit addition, multiplication, rotate, shift and xor operations. Many operations require some 64-bit prime number constants, all defined below:
201
202 ```c
203 static const u64 PRIME64_1 = 0x9E3779B185EBCA87ULL; // 0b1001111000110111011110011011000110000101111010111100101010000111
204 static const u64 PRIME64_2 = 0xC2B2AE3D27D4EB4FULL; // 0b1100001010110010101011100011110100100111110101001110101101001111
205 static const u64 PRIME64_3 = 0x165667B19E3779F9ULL; // 0b0001011001010110011001111011000110011110001101110111100111111001
206 static const u64 PRIME64_4 = 0x85EBCA77C2B2AE63ULL; // 0b1000010111101011110010100111011111000010101100101010111001100011
207 static const u64 PRIME64_5 = 0x27D4EB2F165667C5ULL; // 0b0010011111010100111010110010111100010110010101100110011111000101
208 ```
209
210 These constants are prime numbers, and feature a good mix of bits 1 and 0, neither too regular, nor too dissymmetric. These properties help dispersion capabilities.
211
212 ### Step 1. Initialize internal accumulators
213
214 Each accumulator gets an initial value based on optional `seed` input. Since the `seed` is optional, it can be `0`.
215
216 ```c
217 u64 acc1 = seed + PRIME64_1 + PRIME64_2;
218 u64 acc2 = seed + PRIME64_2;
219 u64 acc3 = seed + 0;
220 u64 acc4 = seed - PRIME64_1;
221 ```
222
223 #### Special case: input is less than 32 bytes
224
225 When the input is too small (< 32 bytes), the algorithm will not process any stripes. Consequently, it will not make use of parallel accumulators.
226
227 In this case, a simplified initialization is performed, using a single accumulator:
228
229 ```c
230 u64 acc = seed + PRIME64_5;
231 ```
232
233 The algorithm then proceeds directly to step 4.
234
235 ### Step 2. Process stripes
236
237 A stripe is a contiguous segment of 32 bytes.
238 It is evenly divided into 4 _lanes_, of 8 bytes each.
239 The first lane is used to update accumulator 1, the second lane is used to update accumulator 2, and so on.
240
241 Each lane read its associated 64-bit value using __little-endian__ convention.
242
243 For each {lane, accumulator}, the update process is called a _round_, and applies the following formula:
244
245 ```c
246 round(accN,laneN):
247 accN = accN + (laneN * PRIME64_2);
248 accN = accN <<< 31;
249 return accN * PRIME64_1;
250 ```
251
252 This shuffles the bits so that any bit from input _lane_ impacts several bits in output _accumulator_. All operations are performed modulo 2^64.
253
254 Input is consumed one full stripe at a time. Step 2 is looped as many times as necessary to consume the whole input, except for the last remaining bytes which cannot form a stripe (< 32 bytes).
255 When that happens, move to step 3.
256
257 ### Step 3. Accumulator convergence
258
259 All 4 lane accumulators from previous steps are merged to produce a single remaining accumulator of same width (64-bit). The associated formula is as follows.
260
261 Note that accumulator convergence is more complex than 32-bit variant, and requires to define another function called _mergeAccumulator()_:
262
263 ```c
264 mergeAccumulator(acc,accN):
265 acc = acc xor round(0, accN);
266 acc = acc * PRIME64_1;
267 return acc + PRIME64_4;
268 ```
269
270 which is then used in the convergence formula:
271
272 ```c
273 acc = (acc1 <<< 1) + (acc2 <<< 7) + (acc3 <<< 12) + (acc4 <<< 18);
274 acc = mergeAccumulator(acc, acc1);
275 acc = mergeAccumulator(acc, acc2);
276 acc = mergeAccumulator(acc, acc3);
277 acc = mergeAccumulator(acc, acc4);
278 ```
279
280 ### Step 4. Add input length
281
282 The input total length is presumed known at this stage. This step is just about adding the length to accumulator, so that it participates to final mixing.
283
284 ```c
285 acc = acc + inputLength;
286 ```
287
288 ### Step 5. Consume remaining input
289
290 There may be up to 31 bytes remaining to consume from the input.
291 The final stage will digest them according to following pseudo-code:
292
293 ```c
294 while (remainingLength >= 8) {
295 lane = read_64bit_little_endian(input_ptr);
296 acc = acc xor round(0, lane);
297 acc = (acc <<< 27) * PRIME64_1;
298 acc = acc + PRIME64_4;
299 input_ptr += 8; remainingLength -= 8;
300 }
301
302 if (remainingLength >= 4) {
303 lane = read_32bit_little_endian(input_ptr);
304 acc = acc xor (lane * PRIME64_1);
305 acc = (acc <<< 23) * PRIME64_2;
306 acc = acc + PRIME64_3;
307 input_ptr += 4; remainingLength -= 4;
308 }
309
310 while (remainingLength >= 1) {
311 lane = read_byte(input_ptr);
312 acc = acc xor (lane * PRIME64_5);
313 acc = (acc <<< 11) * PRIME64_1;
314 input_ptr += 1; remainingLength -= 1;
315 }
316 ```
317
318 This process ensures that all input bytes are present in the final mix.
319
320 ### Step 6. Final mix (avalanche)
321
322 The final mix ensures that all input bits have a chance to impact any bit in the output digest, resulting in an unbiased distribution. This is also called avalanche effect.
323
324 ```c
325 acc = acc xor (acc >> 33);
326 acc = acc * PRIME64_2;
327 acc = acc xor (acc >> 29);
328 acc = acc * PRIME64_3;
329 acc = acc xor (acc >> 32);
330 ```
331
332 ### Step 7. Output
333
334 The `XXH64()` function produces an unsigned 64-bit value as output.
335
336 For systems which require to store and/or display the result in binary or hexadecimal format, the canonical format is defined to reproduce the same value as the natural decimal format, hence follows __big-endian__ convention (most significant byte first).
337
338 XXH3 Algorithm Overview
339 -------------------------------------
340
341 XXH3 comes in two different versions: XXH3-64 and XXH3-128 (or XXH128), producing 64 and 128 bits of output, respectively.
342
343 XXH3 uses different algorithms for small (0-16 bytes), medium (17-240 bytes), and large (241+ bytes) inputs. The algorithms for small and medium inputs are optimized for performance. The three algorithms are described in the following sections.
344
345 Many operations require some 64-bit prime number constants, which are mostly the same constants used in XXH32 and XXH64, all defined below:
346
347 ```c
348 static const u64 PRIME32_1 = 0x9E3779B1U; // 0b10011110001101110111100110110001
349 static const u64 PRIME32_2 = 0x85EBCA77U; // 0b10000101111010111100101001110111
350 static const u64 PRIME32_3 = 0xC2B2AE3DU; // 0b11000010101100101010111000111101
351 static const u64 PRIME64_1 = 0x9E3779B185EBCA87ULL; // 0b1001111000110111011110011011000110000101111010111100101010000111
352 static const u64 PRIME64_2 = 0xC2B2AE3D27D4EB4FULL; // 0b1100001010110010101011100011110100100111110101001110101101001111
353 static const u64 PRIME64_3 = 0x165667B19E3779F9ULL; // 0b0001011001010110011001111011000110011110001101110111100111111001
354 static const u64 PRIME64_4 = 0x85EBCA77C2B2AE63ULL; // 0b1000010111101011110010100111011111000010101100101010111001100011
355 static const u64 PRIME64_5 = 0x27D4EB2F165667C5ULL; // 0b0010011111010100111010110010111100010110010101100110011111000101
356 static const u64 PRIME_MX1 = 0x165667919E3779F9ULL; // 0b0001011001010110011001111001000110011110001101110111100111111001
357 static const u64 PRIME_MX2 = 0x9FB21C651E98DF25ULL; // 0b1001111110110010000111000110010100011110100110001101111100100101
358 ```
359
360 The `XXH3_64bits()` function produces an unsigned 64-bit value.
361 The `XXH3_128bits()` function produces a `XXH128_hash_t` struct containing `low64` and `high64` - the lower and higher 64-bit half values of the result, respectively.
362
363 For systems requiring storing and/or displaying the result in binary or hexadecimal format, the canonical format is defined to reproduce the same value as the natural decimal format, hence following **big-endian** convention (most significant byte first).
364
365 ### Seed and Secret
366
367 XXH3 provides seeded hashing by introducing two configurable constants used in the hashing process: the seed and the secret. The seed is an unsigned 64-bit value, and the secret is an array of bytes that is at least 136 bytes in size. The default seed is 0, and the default secret is the following 192-byte value:
368
369 ```c
370 static const u8 defaultSecret[192] = {
371 0xb8, 0xfe, 0x6c, 0x39, 0x23, 0xa4, 0x4b, 0xbe, 0x7c, 0x01, 0x81, 0x2c, 0xf7, 0x21, 0xad, 0x1c,
372 0xde, 0xd4, 0x6d, 0xe9, 0x83, 0x90, 0x97, 0xdb, 0x72, 0x40, 0xa4, 0xa4, 0xb7, 0xb3, 0x67, 0x1f,
373 0xcb, 0x79, 0xe6, 0x4e, 0xcc, 0xc0, 0xe5, 0x78, 0x82, 0x5a, 0xd0, 0x7d, 0xcc, 0xff, 0x72, 0x21,
374 0xb8, 0x08, 0x46, 0x74, 0xf7, 0x43, 0x24, 0x8e, 0xe0, 0x35, 0x90, 0xe6, 0x81, 0x3a, 0x26, 0x4c,
375 0x3c, 0x28, 0x52, 0xbb, 0x91, 0xc3, 0x00, 0xcb, 0x88, 0xd0, 0x65, 0x8b, 0x1b, 0x53, 0x2e, 0xa3,
376 0x71, 0x64, 0x48, 0x97, 0xa2, 0x0d, 0xf9, 0x4e, 0x38, 0x19, 0xef, 0x46, 0xa9, 0xde, 0xac, 0xd8,
377 0xa8, 0xfa, 0x76, 0x3f, 0xe3, 0x9c, 0x34, 0x3f, 0xf9, 0xdc, 0xbb, 0xc7, 0xc7, 0x0b, 0x4f, 0x1d,
378 0x8a, 0x51, 0xe0, 0x4b, 0xcd, 0xb4, 0x59, 0x31, 0xc8, 0x9f, 0x7e, 0xc9, 0xd9, 0x78, 0x73, 0x64,
379 0xea, 0xc5, 0xac, 0x83, 0x34, 0xd3, 0xeb, 0xc3, 0xc5, 0x81, 0xa0, 0xff, 0xfa, 0x13, 0x63, 0xeb,
380 0x17, 0x0d, 0xdd, 0x51, 0xb7, 0xf0, 0xda, 0x49, 0xd3, 0x16, 0x55, 0x26, 0x29, 0xd4, 0x68, 0x9e,
381 0x2b, 0x16, 0xbe, 0x58, 0x7d, 0x47, 0xa1, 0xfc, 0x8f, 0xf8, 0xb8, 0xd1, 0x7a, 0xd0, 0x31, 0xce,
382 0x45, 0xcb, 0x3a, 0x8f, 0x95, 0x16, 0x04, 0x28, 0xaf, 0xd7, 0xfb, 0xca, 0xbb, 0x4b, 0x40, 0x7e,
383 };
384 ```
385
386 The seed and the secret can be optionally specified using the `*_withSecret` and `*_withSeed` versions of the hash function.
387
388 The seed and the secret cannot be specified simultaneously (`*_withSecretAndSeed` is actually `*_withSeed` for short and medium inputs <= 240 bytes, and `*_withSecret` for large inputs). When one is specified, the other one uses the default value.
389 There is one exception though: when input is large (> 240 bytes) and a seed is given, a secret is derived from the seed value and the default secret using the following procedure:
390
391 ```c
392 deriveSecret(u64 seed):
393 u64 derivedSecret[24] = defaultSecret[0:192];
394 for (i = 0; i < 12; i++) {
395 derivedSecret[i*2] += seed;
396 derivedSecret[i*2+1] -= seed;
397 }
398 return derivedSecret; // convert to u8[192] (little-endian)
399 ```
400
401 The derivation treats the secrets as 24 64-bit values. In XXH3 algorithms, the secret is always read similarly by treating a contiguous segment of the array as one or more 32-bit or 64-bit values. **The secret values are always read using little-endian convention**.
402
403 ### Final Mixing Step (avalanche)
404
405 To make sure that all input bits have a chance to impact any bit in the output digest (avalanche effect), the final step of the XXH3 algorithm is usually one of the two fixed operations that mix the bits in a 64-bit value. These operations are denoted `avalanche()` and `avalanche_XXH64()` in the following XXH3 description.
406
407 ```c
408 avalanche(u64 x):
409 x = x xor (x >> 37);
410 x = x * PRIME_MX1;
411 x = x xor (x >> 32);
412 return x;
413
414 avalanche_XXH64(u64 x):
415 x = x xor (x >> 33);
416 x = x * PRIME64_2;
417 x = x xor (x >> 29);
418 x = x * PRIME64_3;
419 x = x xor (x >> 32);
420 return x;
421 ```
422
423 XXH3 Algorithm Description (for small inputs)
424 -------------------------------------
425
426 The algorithm for small inputs (0-16 bytes of input) is further divided into 4 cases: empty, 1-3 bytes, 4-8 bytes, and 9-16 bytes of input.
427
428 The algorithm uses byte-swap operations. The byte-swap operation reverses the byte order in a 32-bit or 64-bit value. It is denoted `bswap32` and `bswap64` for its 32-bit and 64-bit versions, respectively.
429
430 ### Empty input
431
432 The hash of empty input is calculated from the seed and a segment of the secret:
433
434 ```c
435 XXH3_64_empty():
436 u64 secretWords[2] = secret[56:72];
437 return avalanche_XXH64(seed xor secretWords[0] xor secretWords[1]);
438
439 XXH3_128_empty():
440 u64 secretWords[4] = secret[64:96];
441 return {avalanche_XXH64(seed xor secretWords[0] xor secretWords[1]), // lower half
442 avalanche_XXH64(seed xor secretWords[2] xor secretWords[3])}; // higher half
443 ```
444
445 ### 1-3 bytes of input
446
447 The algorithm starts from a single 32-bit value combining the input bytes and its length:
448
449 ```c
450 u32 combined = (u32)input[inputLength-1] | ((u32)inputLength << 8) |
451 ((u32)input[0] << 16) | ((u32)input[inputLength>>1] << 24);
452 // LSB 8 16 24 MSB
453 // | last byte | length | first byte | middle-or-last byte |
454 ```
455
456 Then the final output is calculated from the value and the first 8 bytes (XXH3-64) or 16 bytes (XXH3-128) of the secret to produce the final result. The secret here is read as 32-bit values instead of the usual 64-bit values.
457
458 ```c
459 XXH3_64_1to3():
460 u32 secretWords[2] = secret[0:8];
461 u64 value = ((u64)(secretWords[0] xor secretWords[1]) + seed) xor (u64)combined;
462 return avalanche_XXH64(value);
463
464 XXH3_128_1to3():
465 u32 secretWords[4] = secret[0:16];
466 u64 low = ((u64)(secretWords[0] xor secretWords[1]) + seed) xor (u64)combined;
467 u64 high = ((u64)(secretWords[2] xor secretWords[3]) - seed) xor (u64)(bswap32(combined) <<< 13);
468 // note that the bswap32(combined) <<< 13 above is 32-bit rotate
469 return {avalanche_XXH64(low), // lower half
470 avalanche_XXH64(high)}; // higher half
471 ```
472
473 Note that the XXH3-64 result is the lower half of XXH3-128 result.
474
475 ### 4-8 bytes of input
476
477 The algorithm starts from reading the first and last 4 bytes of the input as little-endian 32-bit values, and a modified seed:
478
479 ```c
480 u32 inputFirst = input[0:4];
481 u32 inputLast = input[inputLength-4:inputLength];
482 u64 modifiedSeed = seed xor ((u64)bswap32((u32)lowerHalf(seed)) << 32);
483 ```
484
485 Again, these values are combined with a segment of the secret to produce the final value.
486
487 ```c
488 XXH3_64_4to8():
489 u64 secretWords[2] = secret[8:24];
490 u64 combined = (u64)inputLast | ((u64)inputFirst << 32);
491 u64 value = ((secretWords[0] xor secretWords[1]) - modifiedSeed) xor combined;
492 value = value xor (value <<< 49) xor (value <<< 24);
493 value = value * PRIME_MX2;
494 value = value xor ((value >> 35) + inputLength);
495 value = value * PRIME_MX2;
496 value = value xor (value >> 28);
497 return value;
498
499 XXH3_128_4to8():
500 u64 secretWords[2] = secret[16:32];
501 u64 combined = (u64)inputFirst | ((u64)inputLast << 32);
502 u64 value = ((secretWords[0] xor secretWords[1]) + modifiedSeed) xor combined;
503 u128 mulResult = (u128)value * (u128)(PRIME64_1 + (inputLength << 2));
504 u64 high = higherHalf(mulResult); // mulResult >> 64
505 u64 low = lowerHalf(mulResult); // mulResult & 0xFFFFFFFFFFFFFFFF
506 high = high + (low << 1);
507 low = low xor (high >> 3);
508 low = low xor (low >> 35);
509 low = low * PRIME_MX2;
510 low = low xor (low >> 28);
511 high = avalanche(high);
512 return {low, high};
513 ```
514
515 ### 9-16 bytes of input
516
517 The algorithm starts from reading the first and last 8 bytes of the input as little-endian 64-bit values:
518
519 ```c
520 u64 inputFirst = input[0:8];
521 u64 inputLast = input[inputLength-8:inputLength];
522 ```
523
524 Once again, these values are combined with a segment of the secret to produce the final value.
525
526 ```c
527 XXH3_64_9to16():
528 u64 secretWords[4] = secret[24:56];
529 u64 low = ((secretWords[0] xor secretWords[1]) + seed) xor inputFirst;
530 u64 high = ((secretWords[2] xor secretWords[3]) - seed) xor inputLast;
531 u128 mulResult = (u128)low * (u128)high;
532 u64 value = inputLength + bswap64(low) + high + (u64)(lowerHalf(mulResult) xor higherHalf(mulResult));
533 return avalanche(value);
534
535 XXH3_128_9to16():
536 u64 secretWords[4] = secret[32:64];
537 u64 val1 = ((secretWords[0] xor secretWords[1]) - seed) xor inputFirst xor inputLast;
538 u64 val2 = ((secretWords[2] xor secretWords[3]) + seed) xor inputLast;
539 u128 mulResult = (u128)val1 * (u128)PRIME64_1;
540 u64 low = lowerHalf(mulResult) + ((u64)(inputLength - 1) << 54);
541 u64 high = higherHalf(mulResult) + ((u64)higherHalf(val2) << 32) + (u64)lowerHalf(val2) * PRIME32_2;
542 // the above line can also be simplified to higherHalf(mulResult) + val2 + (u64)lowerHalf(val2) * (PRIME32_2 - 1);
543 low = low xor bswap64(high);
544 // the following three lines are in fact a 128x64 -> 128 multiplication ({low,high} = (u128){low,high} * PRIME64_2)
545 u128 mulResult2 = (u128)low * (u128)PRIME64_2;
546 low = lowerHalf(mulResult2);
547 high = higherHalf(mulResult2) + high * PRIME64_2;
548 return {avalanche(low), // lower half
549 avalanche(high)}; // higher half
550 ```
551
552
553 XXH3 Algorithm Description (for medium inputs)
554 -------------------------------------
555
556 This algorithm is used for medium inputs (17-240 bytes of input). Its internal hash state is stored inside 1 (XXH3-64) or 2 (XXH3-128) "accumulators", each storing an unsigned 64-bit value.
557
558 ### Step 1. Initialize internal accumulators
559
560 The accumulator(s) are initialized based on the input length.
561
562 ```c
563 // For XXH3-64
564 u64 acc = inputLength * PRIME64_1;
565
566 // For XXH3-128
567 u64 acc[2] = {inputLength * PRIME64_1, 0};
568 ```
569
570 ### Step 2. Process the input
571
572 This step is further divided into two cases: one for 17-128 bytes of input, and one for 129-240 bytes of input.
573
574 #### Mixing operation
575
576 This step uses a mixing operation that mixes a 16-byte segment of data, a 16-byte segment of secret and the seed into a 64-bit value as a building block. This operation treat the segment of data and secret as little-endian 64-bit values.
577
578 ```c
579 mixStep(u8 data[16], size secretOffset, u64 seed):
580 u64 dataWords[2] = data[0:16];
581 u64 secretWords[2] = secret[secretOffset:secretOffset+16];
582 u128 mulResult = (u128)(dataWords[0] xor (secretWords[0] + seed)) *
583 (u128)(dataWords[1] xor (secretWords[1] - seed));
584 return lowerHalf(mulResult) xor higherHalf(mulResult);
585 ```
586
587 The mixing operation is always invoked in groups of two in XXH3-128, where two 16-byte segments of data are mixed with a 32-byte segment of secret, and the accumulators are updated accordingly.
588
589 ```c
590 mixTwoChunks(u8 data1[16], u8 data2[16], size secretOffset, u64 seed):
591 u64 dataWords1[2] = data1[0:16]; // again, little-endian conversion
592 u64 dataWords2[2] = data2[0:16];
593 acc[0] = acc[0] + mixStep(data1, secretOffset, seed);
594 acc[1] = acc[1] + mixStep(data2, secretOffset + 16, seed);
595 acc[0] = acc[0] xor (dataWords2[0] + dataWords2[1]);
596 acc[1] = acc[1] xor (dataWords1[0] + dataWords1[1]);
597 ```
598
599 The input is split into several 16-byte chunks and mixed, and the result is added to the accumulator(s).
600
601 #### 17-128 bytes of input
602
603 The input is read as *N* 16-byte chunks starting from the beginning and *N* chunks starting from the end, where *N* is the smallest number that these 2*N* chunks cover the whole input. These chunks are paired up and mixed, and the results are accumulated to the accumulator(s).
604
605 ```c
606 // the loop variable `i` should be signed to avoid underflow in implementation
607 processInput_XXH3_64_17to128():
608 u64 numRounds = ((inputLength - 1) >> 5) + 1;
609 for (i = numRounds - 1; i >= 0; i--) {
610 size offsetStart = i*16;
611 size offsetEnd = inputLength - i*16 - 16;
612 acc += mixStep(input[offsetStart:offsetStart+16], i*32, seed);
613 acc += mixStep(input[offsetEnd:offsetEnd+16], i*32+16, seed);
614 }
615
616 processInput_XXH3_128_17to128():
617 u64 numRounds = ((inputLength - 1) >> 5) + 1;
618 for (i = numRounds - 1; i >= 0; i--) {
619 size offsetStart = i*16;
620 size offsetEnd = inputLength - i*16 - 16;
621 mixTwoChunks(input[offsetStart:offsetStart+16], input[offsetEnd:offsetEnd+16], i*32, seed);
622 }
623 ```
624
625 #### 129-240 bytes of input
626
627 The input is split into 16-byte (XXH3-64) or 32-byte (XXH3-128) chunks. The first 128 bytes are first mixed chunk by chunk, followed by an intermediate avalanche operation. Then the remaining full chunks are processed, and finally the last 16/32 bytes are treated as a chunk to process.
628
629 ```c
630 processInput_XXH3_64_129to240():
631 u64 numChunks = inputLength >> 4;
632 for (i = 0; i < 8; i++) {
633 acc += mixStep(input[i*16:i*16+16], i*16, seed);
634 }
635 acc = avalanche(acc);
636 for (i = 8; i < numChunks; i++) {
637 acc += mixStep(input[i*16:i*16+16], (i-8)*16 + 3, seed);
638 }
639 acc += mixStep(input[inputLength-16:inputLength], 119, seed);
640
641 processInput_XXH3_128_129to240():
642 u64 numChunks = inputLength >> 5;
643 for (i = 0; i < 4; i++) {
644 mixTwoChunks(input[i*32:i*32+16], input[i*32+16:i*32+32], i*32, seed);
645 }
646 acc[0] = avalanche(acc[0]);
647 acc[1] = avalanche(acc[1]);
648 for (i = 4; i < numChunks; i++) {
649 mixTwoChunks(input[i*32:i*32+16], input[i*32+16:i*32+32], (i-4)*32 + 3, seed);
650 }
651 // note that the half-chunk order and the seed is different here
652 mixTwoChunks(input[inputLength-16:inputLength], input[inputLength-32:inputLength-16], 103, (u64)0 - seed);
653 ```
654
655 ### Step 3. Finalization
656
657 The final result is extracted from the accumulator(s).
658
659 ```c
660 XXH3_64_17to240():
661 return avalanche(acc);
662
663 XXH3_128_17to240():
664 u64 low = acc[0] + acc[1];
665 u64 high = (acc[0] * PRIME64_1) + (acc[1] * PRIME64_4) + (((u64)inputLength - seed) * PRIME64_2);
666 return {avalanche(low), // lower half
667 (u64)0 - avalanche(high)}; // higher half
668 ```
669
670 XXH3 Algorithm Description (for large inputs)
671 -------------------------------------
672
673 This algorithm is used for inputs larger than 240 bytes. The internal hash state is stored inside 8 "accumulators", each one storing an unsigned 64-bit value.
674
675 ### Step 1. Initialize internal accumulators
676
677 The accumulators are initialized to fixed constants:
678
679 ```c
680 u64 acc[8] = {
681 PRIME32_3, PRIME64_1, PRIME64_2, PRIME64_3,
682 PRIME64_4, PRIME32_2, PRIME64_5, PRIME32_1};
683 ```
684
685 ### Step 2. Process blocks
686
687 The input is consumed and processed one full block at a time. The size of the block depends on the length of the secret. Specifically, a block consists of several 64-byte stripes. The number of stripes per block is `floor((secretLength-64)/8)` . For the default 192-byte secret, there are 16 stripes in a block, and thus the block size is 1024 bytes.
688
689 ```c
690 secretLength = lengthInBytes(secret); // default 192; at least 136
691 stripesPerBlock = (secretLength-64) / 8; // default 16; at least 9
692 blockSize = 64 * stripesPerBlock; // default 1024; at least 576
693 ```
694
695 The process of processing a full block is called a *round*. It consists of the following two sub-steps:
696
697 #### Step 2-1. Process stripes in the block
698
699 A stripe is evenly divided into 8 lanes, of 8 bytes each. In an accumulation step, one stripe and a 64-byte contiguous segment of the secret are used to update the accumulators. Each lane reads its associated 64-bit value using little-endian convention.
700
701 The accumulation step applies the following procedure:
702
703 ```c
704 accumulate(u64 stripe[8], size secretOffset):
705 u64 secretWords[8] = secret[secretOffset:secretOffset+64];
706 for (i = 0; i < 8; i++) {
707 u64 value = stripe[i] xor secretWords[i];
708 acc[i xor 1] = acc[i xor 1] + stripe[i];
709 acc[i] = acc[i] + (u64)lowerHalf(value) * (u64)higherHalf(value);
710 // (value and 0xFFFFFFFF) * (value >> 32)
711 }
712 ```
713
714 The accumulation step is repeated for all stripes in a block, using different segments of the secret, starting from the first 64 bytes for the first stripe, and offset by 8 bytes for each following round:
715
716 ```c
717 round_accumulate(u8 block[blockSize]):
718 for (n = 0; n < stripesPerBlock; n++) {
719 u64 stripe[8] = block[n*64:n*64+64]; // 64 bytes = 8 u64s
720 accumulate(stripe, n*8);
721 }
722 ```
723
724 #### Step 2-2. Scramble accumulators
725
726 After the accumulation steps are finished for all stripes in the block, the accumulators are scrambled using the last 64 bytes of the secret.
727
728 ```c
729 round_scramble():
730 u64 secretWords[8] = secret[secretLength-64:secretLength];
731 for (i = 0; i < 8; i++) {
732 acc[i] = acc[i] xor (acc[i] >> 47);
733 acc[i] = acc[i] xor secretWords[i];
734 acc[i] = acc[i] * PRIME32_1;
735 }
736 ```
737
738 A round is thus a `round_accumulate` followed by a `round_scramble`:
739
740 ```c
741 round(u8 block[blockSize]):
742 round_accumulate(block);
743 round_scramble();
744 ```
745
746 Step 2 is looped to consume the input until there are less than or equal to `blockSize` bytes of input left. Note that we leave the last block to the next step even if it is a full block.
747
748 ### Step 3. Process the last block and the last 64 bytes
749
750 Accumulation steps are run for the stripes in the last block, except for the last stripe (whether it is full or not). After that, run a final accumulation step by treating the last 64 bytes as a stripe. Note that the last 64 bytes might overlap with the second-to-last block.
751
752 ```c
753 // len is the size of the last block (1 <= len <= blockSize)
754 lastRound(u8 block[], size len, u64 lastStripe[8]):
755 size nFullStripes = (len-1)/64;
756 for (n = 0; n < nFullStripes; n++) {
757 u64 stripe[8] = block[n*64:n*64+64];
758 accumulate(stripe, n * 8);
759 }
760 accumulate(lastStripe, secretLength - 71);
761 ```
762
763 ### Step 4. Finalization
764
765 In the finalization step, a merging procedure is used to extract a single 64-bit value from the accumulators, using an initial seed value and a 64-byte segment of the secret.
766
767 ```c
768 finalMerge(u64 initValue, size secretOffset):
769 u64 secretWords[8] = secret[secretOffset:secretOffset+64];
770 u64 result = initValue;
771 for (i = 0; i < 4; i++) {
772 // 64-bit by 64-bit multiplication to 128-bit full result
773 u128 mulResult = (u128)(acc[i*2] xor secretWords[i*2]) *
774 (u128)(acc[i*2+1] xor secretWords[i*2+1]);
775 result = result + (lowerHalf(mulResult) xor higherHalf(mulResult));
776 // (mulResult and 0xFFFFFFFFFFFFFFFF) xor (mulResult >> 64)
777 }
778 return avalanche(result);
779 ```
780
781 XXH3-128 runs the merging procedure twice for the two halves of the result, using different secret segments and different initial values derived from the total input length.
782 The XXH3-64 result is just the lower half of the XXH3-128 result.
783
784 ```c
785 XXH3_64_large():
786 return finalMerge((u64)inputLength * PRIME64_1, 11);
787
788 XXH3_128_large():
789 return {finalMerge((u64)inputLength * PRIME64_1, 11), // lower half
790 finalMerge(~((u64)inputLength * PRIME64_2), secretLength - 75)}; // higher half
791 ```
792
793
794 Performance considerations
795 ----------------------------------
796
797 The xxHash algorithms are simple and compact to implement. They provide a system independent "fingerprint" or digest of a message of arbitrary length.
798
799 The algorithm allows input to be streamed and processed in multiple steps. In such case, an internal buffer is needed to ensure data is presented to the algorithm in full stripes.
800
801 On 64-bit systems, the 64-bit variant `XXH64` is generally faster to compute, so it is a recommended variant, even when only 32-bit are needed.
802
803 On 32-bit systems though, positions are reversed: `XXH64` performance is reduced, due to its usage of 64-bit arithmetic. `XXH32` becomes a faster variant.
804
805 Finally, when vector operations are possible, `XXH3` is likely the faster variant.
806
807
808 Reference Implementation
809 ----------------------------------------
810
811 A reference library written in C is available at https://www.xxhash.com.
812 The web page also links to multiple other implementations written in many different languages.
813 It links to the [github project page](https://github.com/Cyan4973/xxHash) where an [issue board](https://github.com/Cyan4973/xxHash/issues) can be used for further public discussions on the topic.
814
815
816 Version changes
817 --------------------
818 v0.2.0: added XXH3 specification, by Adrien Wu
819 v0.1.1: added a note on rationale for selection of constants
820 v0.1.0: initial release