Debian Codegraph @

crt/aws-checksums/source/external/xxhash.h

raw symbols SCIP
1 /*
2 * xxHash - Extremely Fast Hash algorithm
3 * Header File
4 * Copyright (C) 2012-2023 Yann Collet
5 *
6 * BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php)
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are
10 * met:
11 *
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * * Redistributions in binary form must reproduce the above
15 * copyright notice, this list of conditions and the following disclaimer
16 * in the documentation and/or other materials provided with the
17 * distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 *
31 * You can contact the author at:
32 * - xxHash homepage: https://www.xxhash.com
33 * - xxHash source repository: https://github.com/Cyan4973/xxHash
34 */
35
36 /*!
37 * @mainpage xxHash
38 *
39 * xxHash is an extremely fast non-cryptographic hash algorithm, working at RAM speed
40 * limits.
41 *
42 * It is proposed in four flavors, in three families:
43 * 1. @ref XXH32_family
44 * - Classic 32-bit hash function. Simple, compact, and runs on almost all
45 * 32-bit and 64-bit systems.
46 * 2. @ref XXH64_family
47 * - Classic 64-bit adaptation of XXH32. Just as simple, and runs well on most
48 * 64-bit systems (but _not_ 32-bit systems).
49 * 3. @ref XXH3_family
50 * - Modern 64-bit and 128-bit hash function family which features improved
51 * strength and performance across the board, especially on smaller data.
52 * It benefits greatly from SIMD and 64-bit without requiring it.
53 *
54 * Benchmarks
55 * ---
56 * The reference system uses an Intel i7-9700K CPU, and runs Ubuntu x64 20.04.
57 * The open source benchmark program is compiled with clang v10.0 using -O3 flag.
58 *
59 * | Hash Name | ISA ext | Width | Large Data Speed | Small Data Velocity |
60 * | -------------------- | ------- | ----: | ---------------: | ------------------: |
61 * | XXH3_64bits() | @b AVX2 | 64 | 59.4 GB/s | 133.1 |
62 * | MeowHash | AES-NI | 128 | 58.2 GB/s | 52.5 |
63 * | XXH3_128bits() | @b AVX2 | 128 | 57.9 GB/s | 118.1 |
64 * | CLHash | PCLMUL | 64 | 37.1 GB/s | 58.1 |
65 * | XXH3_64bits() | @b SSE2 | 64 | 31.5 GB/s | 133.1 |
66 * | XXH3_128bits() | @b SSE2 | 128 | 29.6 GB/s | 118.1 |
67 * | RAM sequential read | | N/A | 28.0 GB/s | N/A |
68 * | ahash | AES-NI | 64 | 22.5 GB/s | 107.2 |
69 * | City64 | | 64 | 22.0 GB/s | 76.6 |
70 * | T1ha2 | | 64 | 22.0 GB/s | 99.0 |
71 * | City128 | | 128 | 21.7 GB/s | 57.7 |
72 * | FarmHash | AES-NI | 64 | 21.3 GB/s | 71.9 |
73 * | XXH64() | | 64 | 19.4 GB/s | 71.0 |
74 * | SpookyHash | | 64 | 19.3 GB/s | 53.2 |
75 * | Mum | | 64 | 18.0 GB/s | 67.0 |
76 * | CRC32C | SSE4.2 | 32 | 13.0 GB/s | 57.9 |
77 * | XXH32() | | 32 | 9.7 GB/s | 71.9 |
78 * | City32 | | 32 | 9.1 GB/s | 66.0 |
79 * | Blake3* | @b AVX2 | 256 | 4.4 GB/s | 8.1 |
80 * | Murmur3 | | 32 | 3.9 GB/s | 56.1 |
81 * | SipHash* | | 64 | 3.0 GB/s | 43.2 |
82 * | Blake3* | @b SSE2 | 256 | 2.4 GB/s | 8.1 |
83 * | HighwayHash | | 64 | 1.4 GB/s | 6.0 |
84 * | FNV64 | | 64 | 1.2 GB/s | 62.7 |
85 * | Blake2* | | 256 | 1.1 GB/s | 5.1 |
86 * | SHA1* | | 160 | 0.8 GB/s | 5.6 |
87 * | MD5* | | 128 | 0.6 GB/s | 7.8 |
88 * @note
89 * - Hashes which require a specific ISA extension are noted. SSE2 is also noted,
90 * even though it is mandatory on x64.
91 * - Hashes with an asterisk are cryptographic. Note that MD5 is non-cryptographic
92 * by modern standards.
93 * - Small data velocity is a rough average of algorithm's efficiency for small
94 * data. For more accurate information, see the wiki.
95 * - More benchmarks and strength tests are found on the wiki:
96 * https://github.com/Cyan4973/xxHash/wiki
97 *
98 * Usage
99 * ------
100 * All xxHash variants use a similar API. Changing the algorithm is a trivial
101 * substitution.
102 *
103 * @pre
104 * For functions which take an input and length parameter, the following
105 * requirements are assumed:
106 * - The range from [`input`, `input + length`) is valid, readable memory.
107 * - The only exception is if the `length` is `0`, `input` may be `NULL`.
108 * - For C++, the objects must have the *TriviallyCopyable* property, as the
109 * functions access bytes directly as if it was an array of `unsigned char`.
110 *
111 * @anchor single_shot_example
112 * **Single Shot**
113 *
114 * These functions are stateless functions which hash a contiguous block of memory,
115 * immediately returning the result. They are the easiest and usually the fastest
116 * option.
117 *
118 * XXH32(), XXH64(), XXH3_64bits(), XXH3_128bits()
119 *
120 * @code{.c}
121 * #include <string.h>
122 * #include "xxhash.h"
123 *
124 * // Example for a function which hashes a null terminated string with XXH32().
125 * XXH32_hash_t hash_string(const char* string, XXH32_hash_t seed)
126 * {
127 * // NULL pointers are only valid if the length is zero
128 * size_t length = (string == NULL) ? 0 : strlen(string);
129 * return XXH32(string, length, seed);
130 * }
131 * @endcode
132 *
133 *
134 * @anchor streaming_example
135 * **Streaming**
136 *
137 * These groups of functions allow incremental hashing of unknown size, even
138 * more than what would fit in a size_t.
139 *
140 * XXH32_reset(), XXH64_reset(), XXH3_64bits_reset(), XXH3_128bits_reset()
141 *
142 * @code{.c}
143 * #include <stdio.h>
144 * #include <assert.h>
145 * #include "xxhash.h"
146 * // Example for a function which hashes a FILE incrementally with XXH3_64bits().
147 * XXH64_hash_t hashFile(FILE* f)
148 * {
149 * // Allocate a state struct. Do not just use malloc() or new.
150 * XXH3_state_t* state = XXH3_createState();
151 * assert(state != NULL && "Out of memory!");
152 * // Reset the state to start a new hashing session.
153 * XXH3_64bits_reset(state);
154 * char buffer[4096];
155 * size_t count;
156 * // Read the file in chunks
157 * while ((count = fread(buffer, 1, sizeof(buffer), f)) != 0) {
158 * // Run update() as many times as necessary to process the data
159 * XXH3_64bits_update(state, buffer, count);
160 * }
161 * // Retrieve the finalized hash. This will not change the state.
162 * XXH64_hash_t result = XXH3_64bits_digest(state);
163 * // Free the state. Do not use free().
164 * XXH3_freeState(state);
165 * return result;
166 * }
167 * @endcode
168 *
169 * Streaming functions generate the xxHash value from an incremental input.
170 * This method is slower than single-call functions, due to state management.
171 * For small inputs, prefer `XXH32()` and `XXH64()`, which are better optimized.
172 *
173 * An XXH state must first be allocated using `XXH*_createState()`.
174 *
175 * Start a new hash by initializing the state with a seed using `XXH*_reset()`.
176 *
177 * Then, feed the hash state by calling `XXH*_update()` as many times as necessary.
178 *
179 * The function returns an error code, with 0 meaning OK, and any other value
180 * meaning there is an error.
181 *
182 * Finally, a hash value can be produced anytime, by using `XXH*_digest()`.
183 * This function returns the nn-bits hash as an int or long long.
184 *
185 * It's still possible to continue inserting input into the hash state after a
186 * digest, and generate new hash values later on by invoking `XXH*_digest()`.
187 *
188 * When done, release the state using `XXH*_freeState()`.
189 *
190 *
191 * @anchor canonical_representation_example
192 * **Canonical Representation**
193 *
194 * The default return values from XXH functions are unsigned 32, 64 and 128 bit
195 * integers.
196 * This the simplest and fastest format for further post-processing.
197 *
198 * However, this leaves open the question of what is the order on the byte level,
199 * since little and big endian conventions will store the same number differently.
200 *
201 * The canonical representation settles this issue by mandating big-endian
202 * convention, the same convention as human-readable numbers (large digits first).
203 *
204 * When writing hash values to storage, sending them over a network, or printing
205 * them, it's highly recommended to use the canonical representation to ensure
206 * portability across a wider range of systems, present and future.
207 *
208 * The following functions allow transformation of hash values to and from
209 * canonical format.
210 *
211 * XXH32_canonicalFromHash(), XXH32_hashFromCanonical(),
212 * XXH64_canonicalFromHash(), XXH64_hashFromCanonical(),
213 * XXH128_canonicalFromHash(), XXH128_hashFromCanonical(),
214 *
215 * @code{.c}
216 * #include <stdio.h>
217 * #include "xxhash.h"
218 *
219 * // Example for a function which prints XXH32_hash_t in human readable format
220 * void printXxh32(XXH32_hash_t hash)
221 * {
222 * XXH32_canonical_t cano;
223 * XXH32_canonicalFromHash(&cano, hash);
224 * size_t i;
225 * for(i = 0; i < sizeof(cano.digest); ++i) {
226 * printf("%02x", cano.digest[i]);
227 * }
228 * printf("\n");
229 * }
230 *
231 * // Example for a function which converts XXH32_canonical_t to XXH32_hash_t
232 * XXH32_hash_t convertCanonicalToXxh32(XXH32_canonical_t cano)
233 * {
234 * XXH32_hash_t hash = XXH32_hashFromCanonical(&cano);
235 * return hash;
236 * }
237 * @endcode
238 *
239 *
240 * @file xxhash.h
241 * xxHash prototypes and implementation
242 */
243
244 /*************************
245 * Note: this version has been modified to pass custom allocator for all mem allocations.
246 * Remainder of the code is unchanged.
247 * Affected section will have a similar disclaimer.
248 */
249
250 #if defined(__cplusplus) && !defined(XXH_NO_EXTERNC_GUARD)
251 extern "C" {
252 #endif
253
254 /* ****************************
255 * INLINE mode
256 ******************************/
257 /*!
258 * @defgroup public Public API
259 * Contains details on the public xxHash functions.
260 * @{
261 */
262 #ifdef XXH_DOXYGEN
263 /*!
264 * @brief Gives access to internal state declaration, required for static allocation.
265 *
266 * Incompatible with dynamic linking, due to risks of ABI changes.
267 *
268 * Usage:
269 * @code{.c}
270 * #define XXH_STATIC_LINKING_ONLY
271 * #include "xxhash.h"
272 * @endcode
273 */
274 # define XXH_STATIC_LINKING_ONLY
275 /* Do not undef XXH_STATIC_LINKING_ONLY for Doxygen */
276
277 /*!
278 * @brief Gives access to internal definitions.
279 *
280 * Usage:
281 * @code{.c}
282 * #define XXH_STATIC_LINKING_ONLY
283 * #define XXH_IMPLEMENTATION
284 * #include "xxhash.h"
285 * @endcode
286 */
287 # define XXH_IMPLEMENTATION
288 /* Do not undef XXH_IMPLEMENTATION for Doxygen */
289
290 /*!
291 * @brief Exposes the implementation and marks all functions as `inline`.
292 *
293 * Use these build macros to inline xxhash into the target unit.
294 * Inlining improves performance on small inputs, especially when the length is
295 * expressed as a compile-time constant:
296 *
297 * https://fastcompression.blogspot.com/2018/03/xxhash-for-small-keys-impressive-power.html
298 *
299 * It also keeps xxHash symbols private to the unit, so they are not exported.
300 *
301 * Usage:
302 * @code{.c}
303 * #define XXH_INLINE_ALL
304 * #include "xxhash.h"
305 * @endcode
306 * Do not compile and link xxhash.o as a separate object, as it is not useful.
307 */
308 # define XXH_INLINE_ALL
309 # undef XXH_INLINE_ALL
310 /*!
311 * @brief Exposes the implementation without marking functions as inline.
312 */
313 # define XXH_PRIVATE_API
314 # undef XXH_PRIVATE_API
315 /*!
316 * @brief Emulate a namespace by transparently prefixing all symbols.
317 *
318 * If you want to include _and expose_ xxHash functions from within your own
319 * library, but also want to avoid symbol collisions with other libraries which
320 * may also include xxHash, you can use @ref XXH_NAMESPACE to automatically prefix
321 * any public symbol from xxhash library with the value of @ref XXH_NAMESPACE
322 * (therefore, avoid empty or numeric values).
323 *
324 * Note that no change is required within the calling program as long as it
325 * includes `xxhash.h`: Regular symbol names will be automatically translated
326 * by this header.
327 */
328 # define XXH_NAMESPACE /* YOUR NAME HERE */
329 # undef XXH_NAMESPACE
330 #endif
331
332 #define XXH_CAT(A, B) A##B
333 #define XXH_NAME2(A, B) XXH_CAT(A, B)
334 #define XXH_IPREF(Id) XXH_NAME2(XXH_NAMESPACE, Id)
335
336 #if (defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API)) && !defined(XXH_INLINE_ALL_31684351384)
337 /* this section should be traversed only once */
338 # define XXH_INLINE_ALL_31684351384
339 /* give access to the advanced API, required to compile implementations */
340 # undef XXH_STATIC_LINKING_ONLY /* avoid macro redef */
341 # define XXH_STATIC_LINKING_ONLY
342 /* make all functions private */
343 # undef XXH_PUBLIC_API
344 # if defined(__GNUC__)
345 # define XXH_PUBLIC_API static __inline __attribute__((__unused__))
346 # elif defined(__cplusplus) || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
347 # define XXH_PUBLIC_API static inline
348 # elif defined(_MSC_VER)
349 # define XXH_PUBLIC_API static __inline
350 # else
351 /* note: this version may generate warnings for unused static functions */
352 # define XXH_PUBLIC_API static
353 # endif
354
355 /*
356 * This part deals with the special case where a unit wants to inline xxHash,
357 * but "xxhash.h" has previously been included without XXH_INLINE_ALL,
358 * such as part of some previously included *.h header file.
359 * Without further action, the new include would just be ignored,
360 * and functions would effectively _not_ be inlined (silent failure).
361 * The following macros solve this situation by prefixing all inlined names,
362 * avoiding naming collision with previous inclusions.
363 */
364 /* Before that, we unconditionally #undef all symbols,
365 * in case they were already defined with XXH_NAMESPACE.
366 * They will then be redefined for XXH_INLINE_ALL
367 */
368 # undef XXH_versionNumber
369 /* XXH32 */
370 # undef XXH32
371 # undef XXH32_createState
372 # undef XXH32_freeState
373 # undef XXH32_reset
374 # undef XXH32_update
375 # undef XXH32_digest
376 # undef XXH32_copyState
377 # undef XXH32_canonicalFromHash
378 # undef XXH32_hashFromCanonical
379 /* XXH64 */
380 # undef XXH64
381 # undef XXH64_createState
382 # undef XXH64_freeState
383 # undef XXH64_reset
384 # undef XXH64_update
385 # undef XXH64_digest
386 # undef XXH64_copyState
387 # undef XXH64_canonicalFromHash
388 # undef XXH64_hashFromCanonical
389 /* XXH3_64bits */
390 # undef XXH3_64bits
391 # undef XXH3_64bits_withSecret
392 # undef XXH3_64bits_withSeed
393 # undef XXH3_64bits_withSecretandSeed
394 # undef XXH3_createState
395 # undef XXH3_freeState
396 # undef XXH3_copyState
397 # undef XXH3_64bits_reset
398 # undef XXH3_64bits_reset_withSeed
399 # undef XXH3_64bits_reset_withSecret
400 # undef XXH3_64bits_update
401 # undef XXH3_64bits_digest
402 # undef XXH3_generateSecret
403 /* XXH3_128bits */
404 # undef XXH128
405 # undef XXH3_128bits
406 # undef XXH3_128bits_withSeed
407 # undef XXH3_128bits_withSecret
408 # undef XXH3_128bits_reset
409 # undef XXH3_128bits_reset_withSeed
410 # undef XXH3_128bits_reset_withSecret
411 # undef XXH3_128bits_reset_withSecretandSeed
412 # undef XXH3_128bits_update
413 # undef XXH3_128bits_digest
414 # undef XXH128_isEqual
415 # undef XXH128_cmp
416 # undef XXH128_canonicalFromHash
417 # undef XXH128_hashFromCanonical
418 /* Finally, free the namespace itself */
419 # undef XXH_NAMESPACE
420
421 /* employ the namespace for XXH_INLINE_ALL */
422 # define XXH_NAMESPACE XXH_INLINE_
423 /*
424 * Some identifiers (enums, type names) are not symbols,
425 * but they must nonetheless be renamed to avoid redeclaration.
426 * Alternative solution: do not redeclare them.
427 * However, this requires some #ifdefs, and has a more dispersed impact.
428 * Meanwhile, renaming can be achieved in a single place.
429 */
430 # define XXH_OK XXH_IPREF(XXH_OK)
431 # define XXH_ERROR XXH_IPREF(XXH_ERROR)
432 # define XXH_errorcode XXH_IPREF(XXH_errorcode)
433 # define XXH32_canonical_t XXH_IPREF(XXH32_canonical_t)
434 # define XXH64_canonical_t XXH_IPREF(XXH64_canonical_t)
435 # define XXH128_canonical_t XXH_IPREF(XXH128_canonical_t)
436 # define XXH32_state_s XXH_IPREF(XXH32_state_s)
437 # define XXH32_state_t XXH_IPREF(XXH32_state_t)
438 # define XXH64_state_s XXH_IPREF(XXH64_state_s)
439 # define XXH64_state_t XXH_IPREF(XXH64_state_t)
440 # define XXH3_state_s XXH_IPREF(XXH3_state_s)
441 # define XXH3_state_t XXH_IPREF(XXH3_state_t)
442 # define XXH128_hash_t XXH_IPREF(XXH128_hash_t)
443 /* Ensure the header is parsed again, even if it was previously included */
444 # undef XXHASH_H_5627135585666179
445 # undef XXHASH_H_STATIC_13879238742
446 #endif /* XXH_INLINE_ALL || XXH_PRIVATE_API */
447
448 /* ****************************************************************
449 * Stable API
450 *****************************************************************/
451 #ifndef XXHASH_H_5627135585666179
452 # define XXHASH_H_5627135585666179 1
453
454 /*! @brief Marks a global symbol. */
455 # if !defined(XXH_INLINE_ALL) && !defined(XXH_PRIVATE_API)
456 # if defined(_WIN32) && defined(_MSC_VER) && (defined(XXH_IMPORT) || defined(XXH_EXPORT))
457 # ifdef XXH_EXPORT
458 # define XXH_PUBLIC_API __declspec(dllexport)
459 # elif XXH_IMPORT
460 # define XXH_PUBLIC_API __declspec(dllimport)
461 # endif
462 # else
463 # define XXH_PUBLIC_API /* do nothing */
464 # endif
465 # endif
466
467 # ifdef XXH_NAMESPACE
468 # define XXH_versionNumber XXH_IPREF(XXH_versionNumber)
469 /* XXH32 */
470 # define XXH32 XXH_IPREF(XXH32)
471 # define XXH32_createState XXH_IPREF(XXH32_createState)
472 # define XXH32_freeState XXH_IPREF(XXH32_freeState)
473 # define XXH32_reset XXH_IPREF(XXH32_reset)
474 # define XXH32_update XXH_IPREF(XXH32_update)
475 # define XXH32_digest XXH_IPREF(XXH32_digest)
476 # define XXH32_copyState XXH_IPREF(XXH32_copyState)
477 # define XXH32_canonicalFromHash XXH_IPREF(XXH32_canonicalFromHash)
478 # define XXH32_hashFromCanonical XXH_IPREF(XXH32_hashFromCanonical)
479 /* XXH64 */
480 # define XXH64 XXH_IPREF(XXH64)
481 # define XXH64_createState XXH_IPREF(XXH64_createState)
482 # define XXH64_freeState XXH_IPREF(XXH64_freeState)
483 # define XXH64_reset XXH_IPREF(XXH64_reset)
484 # define XXH64_update XXH_IPREF(XXH64_update)
485 # define XXH64_digest XXH_IPREF(XXH64_digest)
486 # define XXH64_copyState XXH_IPREF(XXH64_copyState)
487 # define XXH64_canonicalFromHash XXH_IPREF(XXH64_canonicalFromHash)
488 # define XXH64_hashFromCanonical XXH_IPREF(XXH64_hashFromCanonical)
489 /* XXH3_64bits */
490 # define XXH3_64bits XXH_IPREF(XXH3_64bits)
491 # define XXH3_64bits_withSecret XXH_IPREF(XXH3_64bits_withSecret)
492 # define XXH3_64bits_withSeed XXH_IPREF(XXH3_64bits_withSeed)
493 # define XXH3_64bits_withSecretandSeed XXH_IPREF(XXH3_64bits_withSecretandSeed)
494 # define XXH3_createState XXH_IPREF(XXH3_createState)
495 # define XXH3_freeState XXH_IPREF(XXH3_freeState)
496 # define XXH3_copyState XXH_IPREF(XXH3_copyState)
497 # define XXH3_64bits_reset XXH_IPREF(XXH3_64bits_reset)
498 # define XXH3_64bits_reset_withSeed XXH_IPREF(XXH3_64bits_reset_withSeed)
499 # define XXH3_64bits_reset_withSecret XXH_IPREF(XXH3_64bits_reset_withSecret)
500 # define XXH3_64bits_reset_withSecretandSeed XXH_IPREF(XXH3_64bits_reset_withSecretandSeed)
501 # define XXH3_64bits_update XXH_IPREF(XXH3_64bits_update)
502 # define XXH3_64bits_digest XXH_IPREF(XXH3_64bits_digest)
503 # define XXH3_generateSecret XXH_IPREF(XXH3_generateSecret)
504 # define XXH3_generateSecret_fromSeed XXH_IPREF(XXH3_generateSecret_fromSeed)
505 /* XXH3_128bits */
506 # define XXH128 XXH_IPREF(XXH128)
507 # define XXH3_128bits XXH_IPREF(XXH3_128bits)
508 # define XXH3_128bits_withSeed XXH_IPREF(XXH3_128bits_withSeed)
509 # define XXH3_128bits_withSecret XXH_IPREF(XXH3_128bits_withSecret)
510 # define XXH3_128bits_withSecretandSeed XXH_IPREF(XXH3_128bits_withSecretandSeed)
511 # define XXH3_128bits_reset XXH_IPREF(XXH3_128bits_reset)
512 # define XXH3_128bits_reset_withSeed XXH_IPREF(XXH3_128bits_reset_withSeed)
513 # define XXH3_128bits_reset_withSecret XXH_IPREF(XXH3_128bits_reset_withSecret)
514 # define XXH3_128bits_reset_withSecretandSeed XXH_IPREF(XXH3_128bits_reset_withSecretandSeed)
515 # define XXH3_128bits_update XXH_IPREF(XXH3_128bits_update)
516 # define XXH3_128bits_digest XXH_IPREF(XXH3_128bits_digest)
517 # define XXH128_isEqual XXH_IPREF(XXH128_isEqual)
518 # define XXH128_cmp XXH_IPREF(XXH128_cmp)
519 # define XXH128_canonicalFromHash XXH_IPREF(XXH128_canonicalFromHash)
520 # define XXH128_hashFromCanonical XXH_IPREF(XXH128_hashFromCanonical)
521 # endif
522
523 /* *************************************
524 * Compiler specifics
525 ***************************************/
526
527 /* specific declaration modes for Windows */
528 # if !defined(XXH_INLINE_ALL) && !defined(XXH_PRIVATE_API)
529 # if defined(_WIN32) && defined(_MSC_VER) && (defined(XXH_IMPORT) || defined(XXH_EXPORT))
530 # ifdef XXH_EXPORT
531 # define XXH_PUBLIC_API __declspec(dllexport)
532 # elif XXH_IMPORT
533 # define XXH_PUBLIC_API __declspec(dllimport)
534 # endif
535 # else
536 # define XXH_PUBLIC_API /* do nothing */
537 # endif
538 # endif
539
540 # if defined(__GNUC__)
541 # define XXH_CONSTF __attribute__((__const__))
542 # define XXH_PUREF __attribute__((__pure__))
543 # define XXH_MALLOCF __attribute__((__malloc__))
544 # else
545 # define XXH_CONSTF /* disable */
546 # define XXH_PUREF
547 # define XXH_MALLOCF
548 # endif
549
550 /* *************************************
551 * Version
552 ***************************************/
553 # define XXH_VERSION_MAJOR 0
554 # define XXH_VERSION_MINOR 8
555 # define XXH_VERSION_RELEASE 3
556 /*! @brief Version number, encoded as two digits each */
557 # define XXH_VERSION_NUMBER (XXH_VERSION_MAJOR * 100 * 100 + XXH_VERSION_MINOR * 100 + XXH_VERSION_RELEASE)
558
559 /*!
560 * @brief Obtains the xxHash version.
561 *
562 * This is mostly useful when xxHash is compiled as a shared library,
563 * since the returned value comes from the library, as opposed to header file.
564 *
565 * @return @ref XXH_VERSION_NUMBER of the invoked library.
566 */
567 XXH_PUBLIC_API XXH_CONSTF unsigned XXH_versionNumber(void);
568
569 /* ****************************
570 * Common basic types
571 ******************************/
572 # include <stddef.h> /* size_t */
573 /*!
574 * @brief Exit code for the streaming API.
575 */
576 typedef enum {
577 XXH_OK = 0, /*!< OK */
578 XXH_ERROR /*!< Error */
579 } XXH_errorcode;
580
581 /*-**********************************************************************
582 * 32-bit hash
583 ************************************************************************/
584 # if defined(XXH_DOXYGEN) /* Don't show <stdint.h> include */
585 /*!
586 * @brief An unsigned 32-bit integer.
587 *
588 * Not necessarily defined to `uint32_t` but functionally equivalent.
589 */
590 typedef uint32_t XXH32_hash_t;
591
592 # elif !defined(__VMS) && \
593 (defined(__cplusplus) || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */))
594 # ifdef _AIX
595 # include <inttypes.h>
596 # else
597 # include <stdint.h>
598 # endif
599 typedef uint32_t XXH32_hash_t;
600
601 # else
602 # include <limits.h>
603 # if UINT_MAX == 0xFFFFFFFFUL
604 typedef unsigned int XXH32_hash_t;
605 # elif ULONG_MAX == 0xFFFFFFFFUL
606 typedef unsigned long XXH32_hash_t;
607 # else
608 # error "unsupported platform: need a 32-bit type"
609 # endif
610 # endif
611
612 /*!
613 * @}
614 *
615 * @defgroup XXH32_family XXH32 family
616 * @ingroup public
617 * Contains functions used in the classic 32-bit xxHash algorithm.
618 *
619 * @note
620 * XXH32 is useful for older platforms, with no or poor 64-bit performance.
621 * Note that the @ref XXH3_family provides competitive speed for both 32-bit
622 * and 64-bit systems, and offers true 64/128 bit hash results.
623 *
624 * @see @ref XXH64_family, @ref XXH3_family : Other xxHash families
625 * @see @ref XXH32_impl for implementation details
626 * @{
627 */
628
629 /*!
630 * @brief Calculates the 32-bit hash of @p input using xxHash32.
631 *
632 * @param input The block of data to be hashed, at least @p length bytes in size.
633 * @param length The length of @p input, in bytes.
634 * @param seed The 32-bit seed to alter the hash's output predictably.
635 *
636 * @pre
637 * The memory between @p input and @p input + @p length must be valid,
638 * readable, contiguous memory. However, if @p length is `0`, @p input may be
639 * `NULL`. In C++, this also must be *TriviallyCopyable*.
640 *
641 * @return The calculated 32-bit xxHash32 value.
642 *
643 * @see @ref single_shot_example "Single Shot Example" for an example.
644 */
645 XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32(const void *input, size_t length, XXH32_hash_t seed);
646
647 # ifndef XXH_NO_STREAM
648 /*!
649 * @typedef struct XXH32_state_s XXH32_state_t
650 * @brief The opaque state struct for the XXH32 streaming API.
651 *
652 * @see XXH32_state_s for details.
653 * @see @ref streaming_example "Streaming Example"
654 */
655 typedef struct XXH32_state_s XXH32_state_t;
656
657 /*!
658 * @brief Allocates an @ref XXH32_state_t.
659 *
660 * @return An allocated pointer of @ref XXH32_state_t on success.
661 * @return `NULL` on failure.
662 *
663 * @note Must be freed with XXH32_freeState().
664 *
665 * @see @ref streaming_example "Streaming Example"
666 */
667 XXH_PUBLIC_API XXH_MALLOCF XXH32_state_t *XXH32_createState(void);
668 /*!
669 * @brief Frees an @ref XXH32_state_t.
670 *
671 * @param statePtr A pointer to an @ref XXH32_state_t allocated with @ref XXH32_createState().
672 *
673 * @return @ref XXH_OK.
674 *
675 * @note @p statePtr must be allocated with XXH32_createState().
676 *
677 * @see @ref streaming_example "Streaming Example"
678 *
679 */
680 XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t *statePtr);
681 /*!
682 * @brief Copies one @ref XXH32_state_t to another.
683 *
684 * @param dst_state The state to copy to.
685 * @param src_state The state to copy from.
686 * @pre
687 * @p dst_state and @p src_state must not be `NULL` and must not overlap.
688 */
689 XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t *dst_state, const XXH32_state_t *src_state);
690
691 /*!
692 * @brief Resets an @ref XXH32_state_t to begin a new hash.
693 *
694 * @param statePtr The state struct to reset.
695 * @param seed The 32-bit seed to alter the hash result predictably.
696 *
697 * @pre
698 * @p statePtr must not be `NULL`.
699 *
700 * @return @ref XXH_OK on success.
701 * @return @ref XXH_ERROR on failure.
702 *
703 * @note This function resets and seeds a state. Call it before @ref XXH32_update().
704 *
705 * @see @ref streaming_example "Streaming Example"
706 */
707 XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t *statePtr, XXH32_hash_t seed);
708
709 /*!
710 * @brief Consumes a block of @p input to an @ref XXH32_state_t.
711 *
712 * @param statePtr The state struct to update.
713 * @param input The block of data to be hashed, at least @p length bytes in size.
714 * @param length The length of @p input, in bytes.
715 *
716 * @pre
717 * @p statePtr must not be `NULL`.
718 * @pre
719 * The memory between @p input and @p input + @p length must be valid,
720 * readable, contiguous memory. However, if @p length is `0`, @p input may be
721 * `NULL`. In C++, this also must be *TriviallyCopyable*.
722 *
723 * @return @ref XXH_OK on success.
724 * @return @ref XXH_ERROR on failure.
725 *
726 * @note Call this to incrementally consume blocks of data.
727 *
728 * @see @ref streaming_example "Streaming Example"
729 */
730 XXH_PUBLIC_API XXH_errorcode XXH32_update(XXH32_state_t *statePtr, const void *input, size_t length);
731
732 /*!
733 * @brief Returns the calculated hash value from an @ref XXH32_state_t.
734 *
735 * @param statePtr The state struct to calculate the hash from.
736 *
737 * @pre
738 * @p statePtr must not be `NULL`.
739 *
740 * @return The calculated 32-bit xxHash32 value from that state.
741 *
742 * @note
743 * Calling XXH32_digest() will not affect @p statePtr, so you can update,
744 * digest, and update again.
745 *
746 * @see @ref streaming_example "Streaming Example"
747 */
748 XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32_digest(const XXH32_state_t *statePtr);
749 # endif /* !XXH_NO_STREAM */
750
751 /******* Canonical representation *******/
752
753 /*!
754 * @brief Canonical (big endian) representation of @ref XXH32_hash_t.
755 */
756 typedef struct {
757 unsigned char digest[4]; /*!< Hash bytes, big endian */
758 } XXH32_canonical_t;
759
760 /*!
761 * @brief Converts an @ref XXH32_hash_t to a big endian @ref XXH32_canonical_t.
762 *
763 * @param dst The @ref XXH32_canonical_t pointer to be stored to.
764 * @param hash The @ref XXH32_hash_t to be converted.
765 *
766 * @pre
767 * @p dst must not be `NULL`.
768 *
769 * @see @ref canonical_representation_example "Canonical Representation Example"
770 */
771 XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t *dst, XXH32_hash_t hash);
772
773 /*!
774 * @brief Converts an @ref XXH32_canonical_t to a native @ref XXH32_hash_t.
775 *
776 * @param src The @ref XXH32_canonical_t to convert.
777 *
778 * @pre
779 * @p src must not be `NULL`.
780 *
781 * @return The converted hash.
782 *
783 * @see @ref canonical_representation_example "Canonical Representation Example"
784 */
785 XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t *src);
786
787 /*! @cond Doxygen ignores this part */
788 # ifdef __has_attribute
789 # define XXH_HAS_ATTRIBUTE(x) __has_attribute(x)
790 # else
791 # define XXH_HAS_ATTRIBUTE(x) 0
792 # endif
793 /*! @endcond */
794
795 /*! @cond Doxygen ignores this part */
796 /* C-language Attributes are added in C23. */
797 # if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L) && defined(__has_c_attribute)
798 # define XXH_HAS_C_ATTRIBUTE(x) __has_c_attribute(x)
799 # else
800 # define XXH_HAS_C_ATTRIBUTE(x) 0
801 # endif
802 /*! @endcond */
803
804 /*! @cond Doxygen ignores this part */
805 # if defined(__cplusplus) && defined(__has_cpp_attribute)
806 # define XXH_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
807 # else
808 # define XXH_HAS_CPP_ATTRIBUTE(x) 0
809 # endif
810 /*! @endcond */
811
812 /*! @cond Doxygen ignores this part */
813 /*
814 * Define XXH_FALLTHROUGH macro for annotating switch case with the 'fallthrough' attribute
815 * introduced in CPP17 and C23.
816 * CPP17 : https://en.cppreference.com/w/cpp/language/attributes/fallthrough
817 * C23 : https://en.cppreference.com/w/c/language/attributes/fallthrough
818 */
819 # if XXH_HAS_C_ATTRIBUTE(fallthrough) || XXH_HAS_CPP_ATTRIBUTE(fallthrough)
820 # define XXH_FALLTHROUGH [[fallthrough]]
821 # elif XXH_HAS_ATTRIBUTE(__fallthrough__)
822 # define XXH_FALLTHROUGH __attribute__((__fallthrough__))
823 # else
824 # define XXH_FALLTHROUGH /* fallthrough */
825 # endif
826 /*! @endcond */
827
828 /*! @cond Doxygen ignores this part */
829 /*
830 * Define XXH_NOESCAPE for annotated pointers in public API.
831 * https://clang.llvm.org/docs/AttributeReference.html#noescape
832 * As of writing this, only supported by clang.
833 */
834 # if XXH_HAS_ATTRIBUTE(noescape)
835 # define XXH_NOESCAPE __attribute__((__noescape__))
836 # else
837 # define XXH_NOESCAPE
838 # endif
839 /*! @endcond */
840
841 /*!
842 * @}
843 * @ingroup public
844 * @{
845 */
846
847 # ifndef XXH_NO_LONG_LONG
848 /*-**********************************************************************
849 * 64-bit hash
850 ************************************************************************/
851 # if defined(XXH_DOXYGEN) /* don't include <stdint.h> */
852 /*!
853 * @brief An unsigned 64-bit integer.
854 *
855 * Not necessarily defined to `uint64_t` but functionally equivalent.
856 */
857 typedef uint64_t XXH64_hash_t;
858 # elif !defined(__VMS) && \
859 (defined(__cplusplus) || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */))
860 # ifdef _AIX
861 # include <inttypes.h>
862 # else
863 # include <stdint.h>
864 # endif
865 typedef uint64_t XXH64_hash_t;
866 # else
867 # include <limits.h>
868 # if defined(__LP64__) && ULONG_MAX == 0xFFFFFFFFFFFFFFFFULL
869 /* LP64 ABI says uint64_t is unsigned long */
870 typedef unsigned long XXH64_hash_t;
871 # else
872 /* the following type must have a width of 64-bit */
873 typedef unsigned long long XXH64_hash_t;
874 # endif
875 # endif
876
877 /*!
878 * @}
879 *
880 * @defgroup XXH64_family XXH64 family
881 * @ingroup public
882 * @{
883 * Contains functions used in the classic 64-bit xxHash algorithm.
884 *
885 * @note
886 * XXH3 provides competitive speed for both 32-bit and 64-bit systems,
887 * and offers true 64/128 bit hash results.
888 * It provides better speed for systems with vector processing capabilities.
889 */
890
891 /*!
892 * @brief Calculates the 64-bit hash of @p input using xxHash64.
893 *
894 * @param input The block of data to be hashed, at least @p length bytes in size.
895 * @param length The length of @p input, in bytes.
896 * @param seed The 64-bit seed to alter the hash's output predictably.
897 *
898 * @pre
899 * The memory between @p input and @p input + @p length must be valid,
900 * readable, contiguous memory. However, if @p length is `0`, @p input may be
901 * `NULL`. In C++, this also must be *TriviallyCopyable*.
902 *
903 * @return The calculated 64-bit xxHash64 value.
904 *
905 * @see @ref single_shot_example "Single Shot Example" for an example.
906 */
907 XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH64(XXH_NOESCAPE const void *input, size_t length, XXH64_hash_t seed);
908
909 /******* Streaming *******/
910 # ifndef XXH_NO_STREAM
911 /*!
912 * @brief The opaque state struct for the XXH64 streaming API.
913 *
914 * @see XXH64_state_s for details.
915 * @see @ref streaming_example "Streaming Example"
916 */
917 typedef struct XXH64_state_s XXH64_state_t; /* incomplete type */
918
919 /*!
920 * @brief Allocates an @ref XXH64_state_t.
921 *
922 * @return An allocated pointer of @ref XXH64_state_t on success.
923 * @return `NULL` on failure.
924 *
925 * @note Must be freed with XXH64_freeState().
926 *
927 * @see @ref streaming_example "Streaming Example"
928 */
929 XXH_PUBLIC_API XXH_MALLOCF XXH64_state_t *XXH64_createState(void);
930
931 /*!
932 * @brief Frees an @ref XXH64_state_t.
933 *
934 * @param statePtr A pointer to an @ref XXH64_state_t allocated with @ref XXH64_createState().
935 *
936 * @return @ref XXH_OK.
937 *
938 * @note @p statePtr must be allocated with XXH64_createState().
939 *
940 * @see @ref streaming_example "Streaming Example"
941 */
942 XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t *statePtr);
943
944 /*!
945 * @brief Copies one @ref XXH64_state_t to another.
946 *
947 * @param dst_state The state to copy to.
948 * @param src_state The state to copy from.
949 * @pre
950 * @p dst_state and @p src_state must not be `NULL` and must not overlap.
951 */
952 XXH_PUBLIC_API void XXH64_copyState(XXH_NOESCAPE XXH64_state_t *dst_state, const XXH64_state_t *src_state);
953
954 /*!
955 * @brief Resets an @ref XXH64_state_t to begin a new hash.
956 *
957 * @param statePtr The state struct to reset.
958 * @param seed The 64-bit seed to alter the hash result predictably.
959 *
960 * @pre
961 * @p statePtr must not be `NULL`.
962 *
963 * @return @ref XXH_OK on success.
964 * @return @ref XXH_ERROR on failure.
965 *
966 * @note This function resets and seeds a state. Call it before @ref XXH64_update().
967 *
968 * @see @ref streaming_example "Streaming Example"
969 */
970 XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH_NOESCAPE XXH64_state_t *statePtr, XXH64_hash_t seed);
971
972 /*!
973 * @brief Consumes a block of @p input to an @ref XXH64_state_t.
974 *
975 * @param statePtr The state struct to update.
976 * @param input The block of data to be hashed, at least @p length bytes in size.
977 * @param length The length of @p input, in bytes.
978 *
979 * @pre
980 * @p statePtr must not be `NULL`.
981 * @pre
982 * The memory between @p input and @p input + @p length must be valid,
983 * readable, contiguous memory. However, if @p length is `0`, @p input may be
984 * `NULL`. In C++, this also must be *TriviallyCopyable*.
985 *
986 * @return @ref XXH_OK on success.
987 * @return @ref XXH_ERROR on failure.
988 *
989 * @note Call this to incrementally consume blocks of data.
990 *
991 * @see @ref streaming_example "Streaming Example"
992 */
993 XXH_PUBLIC_API XXH_errorcode
994 XXH64_update(XXH_NOESCAPE XXH64_state_t *statePtr, XXH_NOESCAPE const void *input, size_t length);
995
996 /*!
997 * @brief Returns the calculated hash value from an @ref XXH64_state_t.
998 *
999 * @param statePtr The state struct to calculate the hash from.
1000 *
1001 * @pre
1002 * @p statePtr must not be `NULL`.
1003 *
1004 * @return The calculated 64-bit xxHash64 value from that state.
1005 *
1006 * @note
1007 * Calling XXH64_digest() will not affect @p statePtr, so you can update,
1008 * digest, and update again.
1009 *
1010 * @see @ref streaming_example "Streaming Example"
1011 */
1012 XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH64_digest(XXH_NOESCAPE const XXH64_state_t *statePtr);
1013 # endif /* !XXH_NO_STREAM */
1014 /******* Canonical representation *******/
1015
1016 /*!
1017 * @brief Canonical (big endian) representation of @ref XXH64_hash_t.
1018 */
1019 typedef struct {
1020 unsigned char digest[sizeof(XXH64_hash_t)];
1021 } XXH64_canonical_t;
1022
1023 /*!
1024 * @brief Converts an @ref XXH64_hash_t to a big endian @ref XXH64_canonical_t.
1025 *
1026 * @param dst The @ref XXH64_canonical_t pointer to be stored to.
1027 * @param hash The @ref XXH64_hash_t to be converted.
1028 *
1029 * @pre
1030 * @p dst must not be `NULL`.
1031 *
1032 * @see @ref canonical_representation_example "Canonical Representation Example"
1033 */
1034 XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH_NOESCAPE XXH64_canonical_t *dst, XXH64_hash_t hash);
1035
1036 /*!
1037 * @brief Converts an @ref XXH64_canonical_t to a native @ref XXH64_hash_t.
1038 *
1039 * @param src The @ref XXH64_canonical_t to convert.
1040 *
1041 * @pre
1042 * @p src must not be `NULL`.
1043 *
1044 * @return The converted hash.
1045 *
1046 * @see @ref canonical_representation_example "Canonical Representation Example"
1047 */
1048 XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH64_hashFromCanonical(XXH_NOESCAPE const XXH64_canonical_t *src);
1049
1050 # ifndef XXH_NO_XXH3
1051
1052 /*!
1053 * @}
1054 * ************************************************************************
1055 * @defgroup XXH3_family XXH3 family
1056 * @ingroup public
1057 * @{
1058 *
1059 * XXH3 is a more recent hash algorithm featuring:
1060 * - Improved speed for both small and large inputs
1061 * - True 64-bit and 128-bit outputs
1062 * - SIMD acceleration
1063 * - Improved 32-bit viability
1064 *
1065 * Speed analysis methodology is explained here:
1066 *
1067 * https://fastcompression.blogspot.com/2019/03/presenting-xxh3.html
1068 *
1069 * Compared to XXH64, expect XXH3 to run approximately
1070 * ~2x faster on large inputs and >3x faster on small ones,
1071 * exact differences vary depending on platform.
1072 *
1073 * XXH3's speed benefits greatly from SIMD and 64-bit arithmetic,
1074 * but does not require it.
1075 * Most 32-bit and 64-bit targets that can run XXH32 smoothly can run XXH3
1076 * at competitive speeds, even without vector support. Further details are
1077 * explained in the implementation.
1078 *
1079 * XXH3 has a fast scalar implementation, but it also includes accelerated SIMD
1080 * implementations for many common platforms:
1081 * - AVX512
1082 * - AVX2
1083 * - SSE2
1084 * - ARM NEON
1085 * - WebAssembly SIMD128
1086 * - POWER8 VSX
1087 * - s390x ZVector
1088 * This can be controlled via the @ref XXH_VECTOR macro, but it automatically
1089 * selects the best version according to predefined macros. For the x86 family, an
1090 * automatic runtime dispatcher is included separately in @ref xxh_x86dispatch.c.
1091 *
1092 * XXH3 implementation is portable:
1093 * it has a generic C90 formulation that can be compiled on any platform,
1094 * all implementations generate exactly the same hash value on all platforms.
1095 * Starting from v0.8.0, it's also labelled "stable", meaning that
1096 * any future version will also generate the same hash value.
1097 *
1098 * XXH3 offers 2 variants, _64bits and _128bits.
1099 *
1100 * When only 64 bits are needed, prefer invoking the _64bits variant, as it
1101 * reduces the amount of mixing, resulting in faster speed on small inputs.
1102 * It's also generally simpler to manipulate a scalar return type than a struct.
1103 *
1104 * The API supports one-shot hashing, streaming mode, and custom secrets.
1105 */
1106
1107 /*!
1108 * @ingroup tuning
1109 * @brief Possible values for @ref XXH_VECTOR.
1110 *
1111 * Unless set explicitly, determined automatically.
1112 */
1113 # define XXH_SCALAR 0 /*!< Portable scalar version */
1114 # define XXH_SSE2 1 /*!< SSE2 for Pentium 4, Opteron, all x86_64. */
1115 # define XXH_AVX2 2 /*!< AVX2 for Haswell and Bulldozer */
1116 # define XXH_AVX512 3 /*!< AVX512 for Skylake and Icelake */
1117 # define XXH_NEON 4 /*!< NEON for most ARMv7-A, all AArch64, and WASM SIMD128 */
1118 # define XXH_VSX 5 /*!< VSX and ZVector for POWER8/z13 (64-bit) */
1119 # define XXH_SVE 6 /*!< SVE for some ARMv8-A and ARMv9-A */
1120 # define XXH_LSX 7 /*!< LSX (128-bit SIMD) for LoongArch64 */
1121 # define XXH_LASX 8 /*!< LASX (256-bit SIMD) for LoongArch64 */
1122 # define XXH_RVV 9 /*!< RVV (RISC-V Vector) for RISC-V */
1123
1124 /*-**********************************************************************
1125 * XXH3 64-bit variant
1126 ************************************************************************/
1127
1128 /*!
1129 * @brief Calculates 64-bit unseeded variant of XXH3 hash of @p input.
1130 *
1131 * @param input The block of data to be hashed, at least @p length bytes in size.
1132 * @param length The length of @p input, in bytes.
1133 *
1134 * @pre
1135 * The memory between @p input and @p input + @p length must be valid,
1136 * readable, contiguous memory. However, if @p length is `0`, @p input may be
1137 * `NULL`. In C++, this also must be *TriviallyCopyable*.
1138 *
1139 * @return The calculated 64-bit XXH3 hash value.
1140 *
1141 * @note
1142 * This is equivalent to @ref XXH3_64bits_withSeed() with a seed of `0`, however
1143 * it may have slightly better performance due to constant propagation of the
1144 * defaults.
1145 *
1146 * @see
1147 * XXH3_64bits_withSeed(), XXH3_64bits_withSecret(): other seeding variants
1148 * @see @ref single_shot_example "Single Shot Example" for an example.
1149 */
1150 XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits(XXH_NOESCAPE const void *input, size_t length);
1151
1152 /*!
1153 * @brief Calculates 64-bit seeded variant of XXH3 hash of @p input.
1154 *
1155 * @param input The block of data to be hashed, at least @p length bytes in size.
1156 * @param length The length of @p input, in bytes.
1157 * @param seed The 64-bit seed to alter the hash result predictably.
1158 *
1159 * @pre
1160 * The memory between @p input and @p input + @p length must be valid,
1161 * readable, contiguous memory. However, if @p length is `0`, @p input may be
1162 * `NULL`. In C++, this also must be *TriviallyCopyable*.
1163 *
1164 * @return The calculated 64-bit XXH3 hash value.
1165 *
1166 * @note
1167 * seed == 0 produces the same results as @ref XXH3_64bits().
1168 *
1169 * This variant generates a custom secret on the fly based on default secret
1170 * altered using the @p seed value.
1171 *
1172 * While this operation is decently fast, note that it's not completely free.
1173 *
1174 * @see @ref single_shot_example "Single Shot Example" for an example.
1175 */
1176 XXH_PUBLIC_API XXH_PUREF XXH64_hash_t
1177 XXH3_64bits_withSeed(XXH_NOESCAPE const void *input, size_t length, XXH64_hash_t seed);
1178
1179 /*!
1180 * The bare minimum size for a custom secret.
1181 *
1182 * @see
1183 * XXH3_64bits_withSecret(), XXH3_64bits_reset_withSecret(),
1184 * XXH3_128bits_withSecret(), XXH3_128bits_reset_withSecret().
1185 */
1186 # define XXH3_SECRET_SIZE_MIN 136
1187
1188 /*!
1189 * @brief Calculates 64-bit variant of XXH3 with a custom "secret".
1190 *
1191 * @param data The block of data to be hashed, at least @p len bytes in size.
1192 * @param len The length of @p data, in bytes.
1193 * @param secret The secret data.
1194 * @param secretSize The length of @p secret, in bytes.
1195 *
1196 * @return The calculated 64-bit XXH3 hash value.
1197 *
1198 * @pre
1199 * The memory between @p data and @p data + @p len must be valid,
1200 * readable, contiguous memory. However, if @p length is `0`, @p data may be
1201 * `NULL`. In C++, this also must be *TriviallyCopyable*.
1202 *
1203 * It's possible to provide any blob of bytes as a "secret" to generate the hash.
1204 * This makes it more difficult for an external actor to prepare an intentional collision.
1205 * The main condition is that @p secretSize *must* be large enough (>= @ref XXH3_SECRET_SIZE_MIN).
1206 * However, the quality of the secret impacts the dispersion of the hash algorithm.
1207 * Therefore, the secret _must_ look like a bunch of random bytes.
1208 * Avoid "trivial" or structured data such as repeated sequences or a text document.
1209 * Whenever in doubt about the "randomness" of the blob of bytes,
1210 * consider employing @ref XXH3_generateSecret() instead (see below).
1211 * It will generate a proper high entropy secret derived from the blob of bytes.
1212 * Another advantage of using XXH3_generateSecret() is that
1213 * it guarantees that all bits within the initial blob of bytes
1214 * will impact every bit of the output.
1215 * This is not necessarily the case when using the blob of bytes directly
1216 * because, when hashing _small_ inputs, only a portion of the secret is employed.
1217 *
1218 * @see @ref single_shot_example "Single Shot Example" for an example.
1219 */
1220 XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits_withSecret(
1221 XXH_NOESCAPE const void *data,
1222 size_t len,
1223 XXH_NOESCAPE const void *secret,
1224 size_t secretSize);
1225
1226 /******* Streaming *******/
1227 # ifndef XXH_NO_STREAM
1228 /*
1229 * Streaming requires state maintenance.
1230 * This operation costs memory and CPU.
1231 * As a consequence, streaming is slower than one-shot hashing.
1232 * For better performance, prefer one-shot functions whenever applicable.
1233 */
1234
1235 /*!
1236 * @brief The opaque state struct for the XXH3 streaming API.
1237 *
1238 * @see XXH3_state_s for details.
1239 * @see @ref streaming_example "Streaming Example"
1240 */
1241 typedef struct XXH3_state_s XXH3_state_t;
1242 XXH_PUBLIC_API XXH_MALLOCF XXH3_state_t *XXH3_createState(void);
1243 XXH_PUBLIC_API XXH_errorcode XXH3_freeState(XXH3_state_t *statePtr);
1244
1245 /*!
1246 * @brief Copies one @ref XXH3_state_t to another.
1247 *
1248 * @param dst_state The state to copy to.
1249 * @param src_state The state to copy from.
1250 * @pre
1251 * @p dst_state and @p src_state must not be `NULL` and must not overlap.
1252 */
1253 XXH_PUBLIC_API void XXH3_copyState(XXH_NOESCAPE XXH3_state_t *dst_state, XXH_NOESCAPE const XXH3_state_t *src_state);
1254
1255 /*!
1256 * @brief Resets an @ref XXH3_state_t to begin a new hash.
1257 *
1258 * @param statePtr The state struct to reset.
1259 *
1260 * @pre
1261 * @p statePtr must not be `NULL`.
1262 *
1263 * @return @ref XXH_OK on success.
1264 * @return @ref XXH_ERROR on failure.
1265 *
1266 * @note
1267 * - This function resets `statePtr` and generate a secret with default parameters.
1268 * - Call this function before @ref XXH3_64bits_update().
1269 * - Digest will be equivalent to `XXH3_64bits()`.
1270 *
1271 * @see @ref streaming_example "Streaming Example"
1272 *
1273 */
1274 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset(XXH_NOESCAPE XXH3_state_t *statePtr);
1275
1276 /*!
1277 * @brief Resets an @ref XXH3_state_t with 64-bit seed to begin a new hash.
1278 *
1279 * @param statePtr The state struct to reset.
1280 * @param seed The 64-bit seed to alter the hash result predictably.
1281 *
1282 * @pre
1283 * @p statePtr must not be `NULL`.
1284 *
1285 * @return @ref XXH_OK on success.
1286 * @return @ref XXH_ERROR on failure.
1287 *
1288 * @note
1289 * - This function resets `statePtr` and generate a secret from `seed`.
1290 * - Call this function before @ref XXH3_64bits_update().
1291 * - Digest will be equivalent to `XXH3_64bits_withSeed()`.
1292 *
1293 * @see @ref streaming_example "Streaming Example"
1294 *
1295 */
1296 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t *statePtr, XXH64_hash_t seed);
1297
1298 /*!
1299 * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash.
1300 *
1301 * @param statePtr The state struct to reset.
1302 * @param secret The secret data.
1303 * @param secretSize The length of @p secret, in bytes.
1304 *
1305 * @pre
1306 * @p statePtr must not be `NULL`.
1307 *
1308 * @return @ref XXH_OK on success.
1309 * @return @ref XXH_ERROR on failure.
1310 *
1311 * @note
1312 * `secret` is referenced, it _must outlive_ the hash streaming session.
1313 *
1314 * Similar to one-shot API, `secretSize` must be >= @ref XXH3_SECRET_SIZE_MIN,
1315 * and the quality of produced hash values depends on secret's entropy
1316 * (secret's content should look like a bunch of random bytes).
1317 * When in doubt about the randomness of a candidate `secret`,
1318 * consider employing `XXH3_generateSecret()` instead (see below).
1319 *
1320 * @see @ref streaming_example "Streaming Example"
1321 */
1322 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSecret(
1323 XXH_NOESCAPE XXH3_state_t *statePtr,
1324 XXH_NOESCAPE const void *secret,
1325 size_t secretSize);
1326
1327 /*!
1328 * @brief Consumes a block of @p input to an @ref XXH3_state_t.
1329 *
1330 * @param statePtr The state struct to update.
1331 * @param input The block of data to be hashed, at least @p length bytes in size.
1332 * @param length The length of @p input, in bytes.
1333 *
1334 * @pre
1335 * @p statePtr must not be `NULL`.
1336 * @pre
1337 * The memory between @p input and @p input + @p length must be valid,
1338 * readable, contiguous memory. However, if @p length is `0`, @p input may be
1339 * `NULL`. In C++, this also must be *TriviallyCopyable*.
1340 *
1341 * @return @ref XXH_OK on success.
1342 * @return @ref XXH_ERROR on failure.
1343 *
1344 * @note Call this to incrementally consume blocks of data.
1345 *
1346 * @see @ref streaming_example "Streaming Example"
1347 */
1348 XXH_PUBLIC_API XXH_errorcode
1349 XXH3_64bits_update(XXH_NOESCAPE XXH3_state_t *statePtr, XXH_NOESCAPE const void *input, size_t length);
1350
1351 /*!
1352 * @brief Returns the calculated XXH3 64-bit hash value from an @ref XXH3_state_t.
1353 *
1354 * @param statePtr The state struct to calculate the hash from.
1355 *
1356 * @pre
1357 * @p statePtr must not be `NULL`.
1358 *
1359 * @return The calculated XXH3 64-bit hash value from that state.
1360 *
1361 * @note
1362 * Calling XXH3_64bits_digest() will not affect @p statePtr, so you can update,
1363 * digest, and update again.
1364 *
1365 * @see @ref streaming_example "Streaming Example"
1366 */
1367 XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits_digest(XXH_NOESCAPE const XXH3_state_t *statePtr);
1368 # endif /* !XXH_NO_STREAM */
1369
1370 /* note : canonical representation of XXH3 is the same as XXH64
1371 * since they both produce XXH64_hash_t values */
1372
1373 /*-**********************************************************************
1374 * XXH3 128-bit variant
1375 ************************************************************************/
1376
1377 /*!
1378 * @brief The return value from 128-bit hashes.
1379 *
1380 * Stored in little endian order, although the fields themselves are in native
1381 * endianness.
1382 */
1383 typedef struct {
1384 XXH64_hash_t low64; /*!< `value & 0xFFFFFFFFFFFFFFFF` */
1385 XXH64_hash_t high64; /*!< `value >> 64` */
1386 } XXH128_hash_t;
1387
1388 /*!
1389 * @brief Calculates 128-bit unseeded variant of XXH3 of @p data.
1390 *
1391 * @param data The block of data to be hashed, at least @p length bytes in size.
1392 * @param len The length of @p data, in bytes.
1393 *
1394 * @return The calculated 128-bit variant of XXH3 value.
1395 *
1396 * The 128-bit variant of XXH3 has more strength, but it has a bit of overhead
1397 * for shorter inputs.
1398 *
1399 * This is equivalent to @ref XXH3_128bits_withSeed() with a seed of `0`, however
1400 * it may have slightly better performance due to constant propagation of the
1401 * defaults.
1402 *
1403 * @see XXH3_128bits_withSeed(), XXH3_128bits_withSecret(): other seeding variants
1404 * @see @ref single_shot_example "Single Shot Example" for an example.
1405 */
1406 XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits(XXH_NOESCAPE const void *data, size_t len);
1407 /*! @brief Calculates 128-bit seeded variant of XXH3 hash of @p data.
1408 *
1409 * @param data The block of data to be hashed, at least @p length bytes in size.
1410 * @param len The length of @p data, in bytes.
1411 * @param seed The 64-bit seed to alter the hash result predictably.
1412 *
1413 * @return The calculated 128-bit variant of XXH3 value.
1414 *
1415 * @note
1416 * seed == 0 produces the same results as @ref XXH3_64bits().
1417 *
1418 * This variant generates a custom secret on the fly based on default secret
1419 * altered using the @p seed value.
1420 *
1421 * While this operation is decently fast, note that it's not completely free.
1422 *
1423 * @see XXH3_128bits(), XXH3_128bits_withSecret(): other seeding variants
1424 * @see @ref single_shot_example "Single Shot Example" for an example.
1425 */
1426 XXH_PUBLIC_API XXH_PUREF XXH128_hash_t
1427 XXH3_128bits_withSeed(XXH_NOESCAPE const void *data, size_t len, XXH64_hash_t seed);
1428 /*!
1429 * @brief Calculates 128-bit variant of XXH3 with a custom "secret".
1430 *
1431 * @param data The block of data to be hashed, at least @p len bytes in size.
1432 * @param len The length of @p data, in bytes.
1433 * @param secret The secret data.
1434 * @param secretSize The length of @p secret, in bytes.
1435 *
1436 * @return The calculated 128-bit variant of XXH3 value.
1437 *
1438 * It's possible to provide any blob of bytes as a "secret" to generate the hash.
1439 * This makes it more difficult for an external actor to prepare an intentional collision.
1440 * The main condition is that @p secretSize *must* be large enough (>= @ref XXH3_SECRET_SIZE_MIN).
1441 * However, the quality of the secret impacts the dispersion of the hash algorithm.
1442 * Therefore, the secret _must_ look like a bunch of random bytes.
1443 * Avoid "trivial" or structured data such as repeated sequences or a text document.
1444 * Whenever in doubt about the "randomness" of the blob of bytes,
1445 * consider employing @ref XXH3_generateSecret() instead (see below).
1446 * It will generate a proper high entropy secret derived from the blob of bytes.
1447 * Another advantage of using XXH3_generateSecret() is that
1448 * it guarantees that all bits within the initial blob of bytes
1449 * will impact every bit of the output.
1450 * This is not necessarily the case when using the blob of bytes directly
1451 * because, when hashing _small_ inputs, only a portion of the secret is employed.
1452 *
1453 * @see @ref single_shot_example "Single Shot Example" for an example.
1454 */
1455 XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits_withSecret(
1456 XXH_NOESCAPE const void *data,
1457 size_t len,
1458 XXH_NOESCAPE const void *secret,
1459 size_t secretSize);
1460
1461 /******* Streaming *******/
1462 # ifndef XXH_NO_STREAM
1463 /*
1464 * Streaming requires state maintenance.
1465 * This operation costs memory and CPU.
1466 * As a consequence, streaming is slower than one-shot hashing.
1467 * For better performance, prefer one-shot functions whenever applicable.
1468 *
1469 * XXH3_128bits uses the same XXH3_state_t as XXH3_64bits().
1470 * Use already declared XXH3_createState() and XXH3_freeState().
1471 *
1472 * All reset and streaming functions have same meaning as their 64-bit counterpart.
1473 */
1474
1475 /*!
1476 * @brief Resets an @ref XXH3_state_t to begin a new hash.
1477 *
1478 * @param statePtr The state struct to reset.
1479 *
1480 * @pre
1481 * @p statePtr must not be `NULL`.
1482 *
1483 * @return @ref XXH_OK on success.
1484 * @return @ref XXH_ERROR on failure.
1485 *
1486 * @note
1487 * - This function resets `statePtr` and generate a secret with default parameters.
1488 * - Call it before @ref XXH3_128bits_update().
1489 * - Digest will be equivalent to `XXH3_128bits()`.
1490 *
1491 * @see @ref streaming_example "Streaming Example"
1492 */
1493 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset(XXH_NOESCAPE XXH3_state_t *statePtr);
1494
1495 /*!
1496 * @brief Resets an @ref XXH3_state_t with 64-bit seed to begin a new hash.
1497 *
1498 * @param statePtr The state struct to reset.
1499 * @param seed The 64-bit seed to alter the hash result predictably.
1500 *
1501 * @pre
1502 * @p statePtr must not be `NULL`.
1503 *
1504 * @return @ref XXH_OK on success.
1505 * @return @ref XXH_ERROR on failure.
1506 *
1507 * @note
1508 * - This function resets `statePtr` and generate a secret from `seed`.
1509 * - Call it before @ref XXH3_128bits_update().
1510 * - Digest will be equivalent to `XXH3_128bits_withSeed()`.
1511 *
1512 * @see @ref streaming_example "Streaming Example"
1513 */
1514 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t *statePtr, XXH64_hash_t seed);
1515 /*!
1516 * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash.
1517 *
1518 * @param statePtr The state struct to reset.
1519 * @param secret The secret data.
1520 * @param secretSize The length of @p secret, in bytes.
1521 *
1522 * @pre
1523 * @p statePtr must not be `NULL`.
1524 *
1525 * @return @ref XXH_OK on success.
1526 * @return @ref XXH_ERROR on failure.
1527 *
1528 * `secret` is referenced, it _must outlive_ the hash streaming session.
1529 * Similar to one-shot API, `secretSize` must be >= @ref XXH3_SECRET_SIZE_MIN,
1530 * and the quality of produced hash values depends on secret's entropy
1531 * (secret's content should look like a bunch of random bytes).
1532 * When in doubt about the randomness of a candidate `secret`,
1533 * consider employing `XXH3_generateSecret()` instead (see below).
1534 *
1535 * @see @ref streaming_example "Streaming Example"
1536 */
1537 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSecret(
1538 XXH_NOESCAPE XXH3_state_t *statePtr,
1539 XXH_NOESCAPE const void *secret,
1540 size_t secretSize);
1541
1542 /*!
1543 * @brief Consumes a block of @p input to an @ref XXH3_state_t.
1544 *
1545 * Call this to incrementally consume blocks of data.
1546 *
1547 * @param statePtr The state struct to update.
1548 * @param input The block of data to be hashed, at least @p length bytes in size.
1549 * @param length The length of @p input, in bytes.
1550 *
1551 * @pre
1552 * @p statePtr must not be `NULL`.
1553 *
1554 * @return @ref XXH_OK on success.
1555 * @return @ref XXH_ERROR on failure.
1556 *
1557 * @note
1558 * The memory between @p input and @p input + @p length must be valid,
1559 * readable, contiguous memory. However, if @p length is `0`, @p input may be
1560 * `NULL`. In C++, this also must be *TriviallyCopyable*.
1561 *
1562 */
1563 XXH_PUBLIC_API XXH_errorcode
1564 XXH3_128bits_update(XXH_NOESCAPE XXH3_state_t *statePtr, XXH_NOESCAPE const void *input, size_t length);
1565
1566 /*!
1567 * @brief Returns the calculated XXH3 128-bit hash value from an @ref XXH3_state_t.
1568 *
1569 * @param statePtr The state struct to calculate the hash from.
1570 *
1571 * @pre
1572 * @p statePtr must not be `NULL`.
1573 *
1574 * @return The calculated XXH3 128-bit hash value from that state.
1575 *
1576 * @note
1577 * Calling XXH3_128bits_digest() will not affect @p statePtr, so you can update,
1578 * digest, and update again.
1579 *
1580 */
1581 XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits_digest(XXH_NOESCAPE const XXH3_state_t *statePtr);
1582 # endif /* !XXH_NO_STREAM */
1583
1584 /* Following helper functions make it possible to compare XXH128_hast_t values.
1585 * Since XXH128_hash_t is a structure, this capability is not offered by the language.
1586 * Note: For better performance, these functions can be inlined using XXH_INLINE_ALL */
1587
1588 /*!
1589 * @brief Check equality of two XXH128_hash_t values
1590 *
1591 * @param h1 The 128-bit hash value.
1592 * @param h2 Another 128-bit hash value.
1593 *
1594 * @return `1` if `h1` and `h2` are equal.
1595 * @return `0` if they are not.
1596 */
1597 XXH_PUBLIC_API XXH_PUREF int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2);
1598
1599 /*!
1600 * @brief Compares two @ref XXH128_hash_t
1601 *
1602 * This comparator is compatible with stdlib's `qsort()`/`bsearch()`.
1603 *
1604 * @param h128_1 Left-hand side value
1605 * @param h128_2 Right-hand side value
1606 *
1607 * @return >0 if @p h128_1 > @p h128_2
1608 * @return =0 if @p h128_1 == @p h128_2
1609 * @return <0 if @p h128_1 < @p h128_2
1610 */
1611 XXH_PUBLIC_API XXH_PUREF int XXH128_cmp(XXH_NOESCAPE const void *h128_1, XXH_NOESCAPE const void *h128_2);
1612
1613 /******* Canonical representation *******/
1614 typedef struct {
1615 unsigned char digest[sizeof(XXH128_hash_t)];
1616 } XXH128_canonical_t;
1617
1618 /*!
1619 * @brief Converts an @ref XXH128_hash_t to a big endian @ref XXH128_canonical_t.
1620 *
1621 * @param dst The @ref XXH128_canonical_t pointer to be stored to.
1622 * @param hash The @ref XXH128_hash_t to be converted.
1623 *
1624 * @pre
1625 * @p dst must not be `NULL`.
1626 * @see @ref canonical_representation_example "Canonical Representation Example"
1627 */
1628 XXH_PUBLIC_API void XXH128_canonicalFromHash(XXH_NOESCAPE XXH128_canonical_t *dst, XXH128_hash_t hash);
1629
1630 /*!
1631 * @brief Converts an @ref XXH128_canonical_t to a native @ref XXH128_hash_t.
1632 *
1633 * @param src The @ref XXH128_canonical_t to convert.
1634 *
1635 * @pre
1636 * @p src must not be `NULL`.
1637 *
1638 * @return The converted hash.
1639 * @see @ref canonical_representation_example "Canonical Representation Example"
1640 */
1641 XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH128_hashFromCanonical(XXH_NOESCAPE const XXH128_canonical_t *src);
1642
1643 # endif /* !XXH_NO_XXH3 */
1644 # endif /* XXH_NO_LONG_LONG */
1645
1646 /*!
1647 * @}
1648 */
1649 #endif /* XXHASH_H_5627135585666179 */
1650
1651 #if defined(XXH_STATIC_LINKING_ONLY) && !defined(XXHASH_H_STATIC_13879238742)
1652 # define XXHASH_H_STATIC_13879238742
1653 /* ****************************************************************************
1654 * This section contains declarations which are not guaranteed to remain stable.
1655 * They may change in future versions, becoming incompatible with a different
1656 * version of the library.
1657 * These declarations should only be used with static linking.
1658 * Never use them in association with dynamic linking!
1659 ***************************************************************************** */
1660
1661 /*
1662 * These definitions are only present to allow static allocation
1663 * of XXH states, on stack or in a struct, for example.
1664 * Never **ever** access their members directly.
1665 */
1666
1667 /*!
1668 * @internal
1669 * @brief Structure for XXH32 streaming API.
1670 *
1671 * @note This is only defined when @ref XXH_STATIC_LINKING_ONLY,
1672 * @ref XXH_INLINE_ALL, or @ref XXH_IMPLEMENTATION is defined. Otherwise it is
1673 * an opaque type. This allows fields to safely be changed.
1674 *
1675 * Typedef'd to @ref XXH32_state_t.
1676 * Do not access the members of this struct directly.
1677 * @see XXH64_state_s, XXH3_state_s
1678 */
1679 struct XXH32_state_s {
1680 XXH32_hash_t total_len_32; /*!< Total length hashed, modulo 2^32 */
1681 XXH32_hash_t large_len; /*!< Whether the hash is >= 16 (handles @ref total_len_32 overflow) */
1682 XXH32_hash_t acc[4]; /*!< Accumulator lanes */
1683 unsigned char buffer[16]; /*!< Internal buffer for partial reads. */
1684 XXH32_hash_t bufferedSize; /*!< Amount of data in @ref buffer */
1685 XXH32_hash_t reserved; /*!< Reserved field. Do not read nor write to it. */
1686 }; /* typedef'd to XXH32_state_t */
1687
1688 # ifndef XXH_NO_LONG_LONG /* defined when there is no 64-bit support */
1689
1690 /*!
1691 * @internal
1692 * @brief Structure for XXH64 streaming API.
1693 *
1694 * @note This is only defined when @ref XXH_STATIC_LINKING_ONLY,
1695 * @ref XXH_INLINE_ALL, or @ref XXH_IMPLEMENTATION is defined. Otherwise it is
1696 * an opaque type. This allows fields to safely be changed.
1697 *
1698 * Typedef'd to @ref XXH64_state_t.
1699 * Do not access the members of this struct directly.
1700 * @see XXH32_state_s, XXH3_state_s
1701 */
1702 struct XXH64_state_s {
1703 XXH64_hash_t total_len; /*!< Total length hashed. This is always 64-bit. */
1704 XXH64_hash_t acc[4]; /*!< Accumulator lanes */
1705 unsigned char buffer[32]; /*!< Internal buffer for partial reads.. */
1706 XXH32_hash_t bufferedSize; /*!< Amount of data in @ref buffer */
1707 XXH32_hash_t reserved32; /*!< Reserved field, needed for padding anyways*/
1708 XXH64_hash_t reserved64; /*!< Reserved field. Do not read or write to it. */
1709 }; /* typedef'd to XXH64_state_t */
1710
1711 # ifndef XXH_NO_XXH3
1712
1713 # if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* >= C11 */
1714 # define XXH_ALIGN(n) _Alignas(n)
1715 # elif defined(__cplusplus) && (__cplusplus >= 201103L) /* >= C++11 */
1716 /* In C++ alignas() is a keyword */
1717 # define XXH_ALIGN(n) alignas(n)
1718 # elif defined(__GNUC__)
1719 # define XXH_ALIGN(n) __attribute__((aligned(n)))
1720 # elif defined(_MSC_VER)
1721 # define XXH_ALIGN(n) __declspec(align(n))
1722 # else
1723 # define XXH_ALIGN(n) /* disabled */
1724 # endif
1725
1726 /* Old GCC versions only accept the attribute after the type in structures. */
1727 # if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) /* C11+ */ \
1728 && !(defined(__cplusplus) && (__cplusplus >= 201103L)) /* >= C++11 */ \
1729 && defined(__GNUC__)
1730 # define XXH_ALIGN_MEMBER(align, type) type XXH_ALIGN(align)
1731 # else
1732 # define XXH_ALIGN_MEMBER(align, type) XXH_ALIGN(align) type
1733 # endif
1734
1735 /*!
1736 * @internal
1737 * @brief The size of the internal XXH3 buffer.
1738 *
1739 * This is the optimal update size for incremental hashing.
1740 *
1741 * @see XXH3_64b_update(), XXH3_128b_update().
1742 */
1743 # define XXH3_INTERNALBUFFER_SIZE 256
1744
1745 /*!
1746 * @def XXH3_SECRET_DEFAULT_SIZE
1747 * @brief Default Secret's size
1748 *
1749 * This is the size of internal XXH3_kSecret
1750 * and is needed by XXH3_generateSecret_fromSeed().
1751 *
1752 * Not to be confused with @ref XXH3_SECRET_SIZE_MIN.
1753 */
1754 # define XXH3_SECRET_DEFAULT_SIZE 192
1755
1756 /*!
1757 * @internal
1758 * @brief Structure for XXH3 streaming API.
1759 *
1760 * @note This is only defined when @ref XXH_STATIC_LINKING_ONLY,
1761 * @ref XXH_INLINE_ALL, or @ref XXH_IMPLEMENTATION is defined.
1762 * Otherwise it is an opaque type.
1763 * Never use this definition in combination with dynamic library.
1764 * This allows fields to safely be changed in the future.
1765 *
1766 * @note ** This structure has a strict alignment requirement of 64 bytes!! **
1767 * Do not allocate this with `malloc()` or `new`,
1768 * it will not be sufficiently aligned.
1769 * Use @ref XXH3_createState() and @ref XXH3_freeState(), or stack allocation.
1770 *
1771 * Typedef'd to @ref XXH3_state_t.
1772 * Do never access the members of this struct directly.
1773 *
1774 * @see XXH3_INITSTATE() for stack initialization.
1775 * @see XXH3_createState(), XXH3_freeState().
1776 * @see XXH32_state_s, XXH64_state_s
1777 */
1778 struct XXH3_state_s {
1779 XXH_ALIGN_MEMBER(64, XXH64_hash_t acc[8]);
1780 /*!< The 8 accumulators. See @ref XXH32_state_s::acc and @ref XXH64_state_s::acc */
1781 XXH_ALIGN_MEMBER(64, unsigned char customSecret[XXH3_SECRET_DEFAULT_SIZE]);
1782 /*!< Used to store a custom secret generated from a seed. */
1783 XXH_ALIGN_MEMBER(64, unsigned char buffer[XXH3_INTERNALBUFFER_SIZE]);
1784 /*!< The internal buffer. @see XXH32_state_s::mem32 */
1785 XXH32_hash_t bufferedSize;
1786 /*!< The amount of memory in @ref buffer, @see XXH32_state_s::memsize */
1787 XXH32_hash_t useSeed;
1788 /*!< Reserved field. Needed for padding on 64-bit. */
1789 size_t nbStripesSoFar;
1790 /*!< Number or stripes processed. */
1791 XXH64_hash_t totalLen;
1792 /*!< Total length hashed. 64-bit even on 32-bit targets. */
1793 size_t nbStripesPerBlock;
1794 /*!< Number of stripes per block. */
1795 size_t secretLimit;
1796 /*!< Size of @ref customSecret or @ref extSecret */
1797 XXH64_hash_t seed;
1798 /*!< Seed for _withSeed variants. Must be zero otherwise, @see XXH3_INITSTATE() */
1799 XXH64_hash_t reserved64;
1800 /*!< Reserved field. */
1801 const unsigned char *extSecret;
1802 /*!< Reference to an external secret for the _withSecret variants, NULL
1803 * for other variants. */
1804 /* note: there may be some padding at the end due to alignment on 64 bytes */
1805 }; /* typedef'd to XXH3_state_t */
1806
1807 # undef XXH_ALIGN_MEMBER
1808
1809 /*!
1810 * @brief Initializes a stack-allocated `XXH3_state_s`.
1811 *
1812 * When the @ref XXH3_state_t structure is merely emplaced on stack,
1813 * it should be initialized with XXH3_INITSTATE() or a memset()
1814 * in case its first reset uses XXH3_NNbits_reset_withSeed().
1815 * This init can be omitted if the first reset uses default or _withSecret mode.
1816 * This operation isn't necessary when the state is created with XXH3_createState().
1817 * Note that this doesn't prepare the state for a streaming operation,
1818 * it's still necessary to use XXH3_NNbits_reset*() afterwards.
1819 */
1820 # define XXH3_INITSTATE(XXH3_state_ptr) \
1821 do { \
1822 XXH3_state_t *tmp_xxh3_state_ptr = (XXH3_state_ptr); \
1823 tmp_xxh3_state_ptr->seed = 0; \
1824 tmp_xxh3_state_ptr->extSecret = NULL; \
1825 } while (0)
1826
1827 /*!
1828 * @brief Calculates the 128-bit hash of @p data using XXH3.
1829 *
1830 * @param data The block of data to be hashed, at least @p len bytes in size.
1831 * @param len The length of @p data, in bytes.
1832 * @param seed The 64-bit seed to alter the hash's output predictably.
1833 *
1834 * @pre
1835 * The memory between @p data and @p data + @p len must be valid,
1836 * readable, contiguous memory. However, if @p len is `0`, @p data may be
1837 * `NULL`. In C++, this also must be *TriviallyCopyable*.
1838 *
1839 * @return The calculated 128-bit XXH3 value.
1840 *
1841 * @see @ref single_shot_example "Single Shot Example" for an example.
1842 */
1843 XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH128(XXH_NOESCAPE const void *data, size_t len, XXH64_hash_t seed);
1844
1845 /* === Experimental API === */
1846 /* Symbols defined below must be considered tied to a specific library version. */
1847
1848 /*!
1849 * @brief Derive a high-entropy secret from any user-defined content, named customSeed.
1850 *
1851 * @param secretBuffer A writable buffer for derived high-entropy secret data.
1852 * @param secretSize Size of secretBuffer, in bytes. Must be >= XXH3_SECRET_SIZE_MIN.
1853 * @param customSeed A user-defined content.
1854 * @param customSeedSize Size of customSeed, in bytes.
1855 *
1856 * @return @ref XXH_OK on success.
1857 * @return @ref XXH_ERROR on failure.
1858 *
1859 * The generated secret can be used in combination with `*_withSecret()` functions.
1860 * The `_withSecret()` variants are useful to provide a higher level of protection
1861 * than 64-bit seed, as it becomes much more difficult for an external actor to
1862 * guess how to impact the calculation logic.
1863 *
1864 * The function accepts as input a custom seed of any length and any content,
1865 * and derives from it a high-entropy secret of length @p secretSize into an
1866 * already allocated buffer @p secretBuffer.
1867 *
1868 * The generated secret can then be used with any `*_withSecret()` variant.
1869 * The functions @ref XXH3_128bits_withSecret(), @ref XXH3_64bits_withSecret(),
1870 * @ref XXH3_128bits_reset_withSecret() and @ref XXH3_64bits_reset_withSecret()
1871 * are part of this list. They all accept a `secret` parameter
1872 * which must be large enough for implementation reasons (>= @ref XXH3_SECRET_SIZE_MIN)
1873 * _and_ feature very high entropy (consist of random-looking bytes).
1874 * These conditions can be a high bar to meet, so @ref XXH3_generateSecret() can
1875 * be employed to ensure proper quality.
1876 *
1877 * @p customSeed can be anything. It can have any size, even small ones,
1878 * and its content can be anything, even "poor entropy" sources such as a bunch
1879 * of zeroes. The resulting `secret` will nonetheless provide all required qualities.
1880 *
1881 * @pre
1882 * - @p secretSize must be >= @ref XXH3_SECRET_SIZE_MIN
1883 * - When @p customSeedSize > 0, supplying NULL as customSeed is undefined behavior.
1884 *
1885 * Example code:
1886 * @code{.c}
1887 * #include <stdio.h>
1888 * #include <stdlib.h>
1889 * #include <string.h>
1890 * #define XXH_STATIC_LINKING_ONLY // expose unstable API
1891 * #include "xxhash.h"
1892 * // Hashes argv[2] using the entropy from argv[1].
1893 * int main(int argc, char* argv[])
1894 * {
1895 * char secret[XXH3_SECRET_SIZE_MIN];
1896 * if (argv != 3) { return 1; }
1897 * XXH3_generateSecret(secret, sizeof(secret), argv[1], strlen(argv[1]));
1898 * XXH64_hash_t h = XXH3_64bits_withSecret(
1899 * argv[2], strlen(argv[2]),
1900 * secret, sizeof(secret)
1901 * );
1902 * printf("%016llx\n", (unsigned long long) h);
1903 * }
1904 * @endcode
1905 */
1906 XXH_PUBLIC_API XXH_errorcode XXH3_generateSecret(
1907 XXH_NOESCAPE void *secretBuffer,
1908 size_t secretSize,
1909 XXH_NOESCAPE const void *customSeed,
1910 size_t customSeedSize);
1911
1912 /*!
1913 * @brief Generate the same secret as the _withSeed() variants.
1914 *
1915 * @param secretBuffer A writable buffer of @ref XXH3_SECRET_DEFAULT_SIZE bytes
1916 * @param seed The 64-bit seed to alter the hash result predictably.
1917 *
1918 * The generated secret can be used in combination with
1919 *`*_withSecret()` and `_withSecretandSeed()` variants.
1920 *
1921 * Example C++ `std::string` hash class:
1922 * @code{.cpp}
1923 * #include <string>
1924 * #define XXH_STATIC_LINKING_ONLY // expose unstable API
1925 * #include "xxhash.h"
1926 * // Slow, seeds each time
1927 * class HashSlow {
1928 * XXH64_hash_t seed;
1929 * public:
1930 * HashSlow(XXH64_hash_t s) : seed{s} {}
1931 * size_t operator()(const std::string& x) const {
1932 * return size_t{XXH3_64bits_withSeed(x.c_str(), x.length(), seed)};
1933 * }
1934 * };
1935 * // Fast, caches the seeded secret for future uses.
1936 * class HashFast {
1937 * unsigned char secret[XXH3_SECRET_DEFAULT_SIZE];
1938 * public:
1939 * HashFast(XXH64_hash_t s) {
1940 * XXH3_generateSecret_fromSeed(secret, seed);
1941 * }
1942 * size_t operator()(const std::string& x) const {
1943 * return size_t{
1944 * XXH3_64bits_withSecret(x.c_str(), x.length(), secret, sizeof(secret))
1945 * };
1946 * }
1947 * };
1948 * @endcode
1949 */
1950 XXH_PUBLIC_API void XXH3_generateSecret_fromSeed(XXH_NOESCAPE void *secretBuffer, XXH64_hash_t seed);
1951
1952 /*!
1953 * @brief Maximum size of "short" key in bytes.
1954 */
1955 # define XXH3_MIDSIZE_MAX 240
1956
1957 /*!
1958 * @brief Calculates 64/128-bit seeded variant of XXH3 hash of @p data.
1959 *
1960 * @param data The block of data to be hashed, at least @p len bytes in size.
1961 * @param len The length of @p data, in bytes.
1962 * @param secret The secret data.
1963 * @param secretSize The length of @p secret, in bytes.
1964 * @param seed The 64-bit seed to alter the hash result predictably.
1965 *
1966 * These variants generate hash values using either:
1967 * - @p seed for "short" keys (< @ref XXH3_MIDSIZE_MAX = 240 bytes)
1968 * - @p secret for "large" keys (>= @ref XXH3_MIDSIZE_MAX).
1969 *
1970 * This generally benefits speed, compared to `_withSeed()` or `_withSecret()`.
1971 * `_withSeed()` has to generate the secret on the fly for "large" keys.
1972 * It's fast, but can be perceptible for "not so large" keys (< 1 KB).
1973 * `_withSecret()` has to generate the masks on the fly for "small" keys,
1974 * which requires more instructions than _withSeed() variants.
1975 * Therefore, _withSecretandSeed variant combines the best of both worlds.
1976 *
1977 * When @p secret has been generated by XXH3_generateSecret_fromSeed(),
1978 * this variant produces *exactly* the same results as `_withSeed()` variant,
1979 * hence offering only a pure speed benefit on "large" input,
1980 * by skipping the need to regenerate the secret for every large input.
1981 *
1982 * Another usage scenario is to hash the secret to a 64-bit hash value,
1983 * for example with XXH3_64bits(), which then becomes the seed,
1984 * and then employ both the seed and the secret in _withSecretandSeed().
1985 * On top of speed, an added benefit is that each bit in the secret
1986 * has a 50% chance to swap each bit in the output, via its impact to the seed.
1987 *
1988 * This is not guaranteed when using the secret directly in "small data" scenarios,
1989 * because only portions of the secret are employed for small data.
1990 */
1991 XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits_withSecretandSeed(
1992 XXH_NOESCAPE const void *data,
1993 size_t len,
1994 XXH_NOESCAPE const void *secret,
1995 size_t secretSize,
1996 XXH64_hash_t seed);
1997
1998 /*!
1999 * @brief Calculates 128-bit seeded variant of XXH3 hash of @p data.
2000 *
2001 * @param input The memory segment to be hashed, at least @p len bytes in size.
2002 * @param length The length of @p data, in bytes.
2003 * @param secret The secret used to alter hash result predictably.
2004 * @param secretSize The length of @p secret, in bytes (must be >= XXH3_SECRET_SIZE_MIN)
2005 * @param seed64 The 64-bit seed to alter the hash result predictably.
2006 *
2007 * @return @ref XXH_OK on success.
2008 * @return @ref XXH_ERROR on failure.
2009 *
2010 * @see XXH3_64bits_withSecretandSeed(): contract is the same.
2011 */
2012 XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits_withSecretandSeed(
2013 XXH_NOESCAPE const void *input,
2014 size_t length,
2015 XXH_NOESCAPE const void *secret,
2016 size_t secretSize,
2017 XXH64_hash_t seed64);
2018
2019 # ifndef XXH_NO_STREAM
2020 /*!
2021 * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash.
2022 *
2023 * @param statePtr A pointer to an @ref XXH3_state_t allocated with @ref XXH3_createState().
2024 * @param secret The secret data.
2025 * @param secretSize The length of @p secret, in bytes.
2026 * @param seed64 The 64-bit seed to alter the hash result predictably.
2027 *
2028 * @return @ref XXH_OK on success.
2029 * @return @ref XXH_ERROR on failure.
2030 *
2031 * @see XXH3_64bits_withSecretandSeed(). Contract is identical.
2032 */
2033 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSecretandSeed(
2034 XXH_NOESCAPE XXH3_state_t *statePtr,
2035 XXH_NOESCAPE const void *secret,
2036 size_t secretSize,
2037 XXH64_hash_t seed64);
2038
2039 /*!
2040 * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash.
2041 *
2042 * @param statePtr A pointer to an @ref XXH3_state_t allocated with @ref XXH3_createState().
2043 * @param secret The secret data.
2044 * @param secretSize The length of @p secret, in bytes.
2045 * @param seed64 The 64-bit seed to alter the hash result predictably.
2046 *
2047 * @return @ref XXH_OK on success.
2048 * @return @ref XXH_ERROR on failure.
2049 *
2050 * @see XXH3_64bits_withSecretandSeed(). Contract is identical.
2051 *
2052 * Note: there was a bug in an earlier version of this function (<= v0.8.2)
2053 * that would make it generate an incorrect hash value
2054 * when @p seed == 0 and @p length < XXH3_MIDSIZE_MAX
2055 * and @p secret is different from XXH3_generateSecret_fromSeed().
2056 * As stated in the contract, the correct hash result must be
2057 * the same as XXH3_128bits_withSeed() when @p length <= XXH3_MIDSIZE_MAX.
2058 * Results generated by this older version are wrong, hence not comparable.
2059 */
2060 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSecretandSeed(
2061 XXH_NOESCAPE XXH3_state_t *statePtr,
2062 XXH_NOESCAPE const void *secret,
2063 size_t secretSize,
2064 XXH64_hash_t seed64);
2065
2066 # endif /* !XXH_NO_STREAM */
2067
2068 # endif /* !XXH_NO_XXH3 */
2069 # endif /* XXH_NO_LONG_LONG */
2070 # if defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API)
2071 # define XXH_IMPLEMENTATION
2072 # endif
2073
2074 #endif /* defined(XXH_STATIC_LINKING_ONLY) && !defined(XXHASH_H_STATIC_13879238742) */
2075
2076 /* ======================================================================== */
2077 /* ======================================================================== */
2078 /* ======================================================================== */
2079
2080 /*-**********************************************************************
2081 * xxHash implementation
2082 *-**********************************************************************
2083 * xxHash's implementation used to be hosted inside xxhash.c.
2084 *
2085 * However, inlining requires implementation to be visible to the compiler,
2086 * hence be included alongside the header.
2087 * Previously, implementation was hosted inside xxhash.c,
2088 * which was then #included when inlining was activated.
2089 * This construction created issues with a few build and install systems,
2090 * as it required xxhash.c to be stored in /include directory.
2091 *
2092 * xxHash implementation is now directly integrated within xxhash.h.
2093 * As a consequence, xxhash.c is no longer needed in /include.
2094 *
2095 * xxhash.c is still available and is still useful.
2096 * In a "normal" setup, when xxhash is not inlined,
2097 * xxhash.h only exposes the prototypes and public symbols,
2098 * while xxhash.c can be built into an object file xxhash.o
2099 * which can then be linked into the final binary.
2100 ************************************************************************/
2101
2102 #if (defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API) || defined(XXH_IMPLEMENTATION)) && \
2103 !defined(XXH_IMPLEM_13a8737387)
2104 # define XXH_IMPLEM_13a8737387
2105
2106 /* *************************************
2107 * Tuning parameters
2108 ***************************************/
2109
2110 /*!
2111 * @defgroup tuning Tuning parameters
2112 * @{
2113 *
2114 * Various macros to control xxHash's behavior.
2115 */
2116 # ifdef XXH_DOXYGEN
2117 /*!
2118 * @brief Define this to disable 64-bit code.
2119 *
2120 * Useful if only using the @ref XXH32_family and you have a strict C90 compiler.
2121 */
2122 # define XXH_NO_LONG_LONG
2123 # undef XXH_NO_LONG_LONG /* don't actually */
2124 /*!
2125 * @brief Controls how unaligned memory is accessed.
2126 *
2127 * By default, access to unaligned memory is controlled by `memcpy()`, which is
2128 * safe and portable.
2129 *
2130 * Unfortunately, on some target/compiler combinations, the generated assembly
2131 * is sub-optimal.
2132 *
2133 * The below switch allow selection of a different access method
2134 * in the search for improved performance.
2135 *
2136 * @par Possible options:
2137 *
2138 * - `XXH_FORCE_MEMORY_ACCESS=0` (default): `memcpy`
2139 * @par
2140 * Use `memcpy()`. Safe and portable. Note that most modern compilers will
2141 * eliminate the function call and treat it as an unaligned access.
2142 *
2143 * - `XXH_FORCE_MEMORY_ACCESS=1`: `__attribute__((aligned(1)))`
2144 * @par
2145 * Depends on compiler extensions and is therefore not portable.
2146 * This method is safe _if_ your compiler supports it,
2147 * and *generally* as fast or faster than `memcpy`.
2148 *
2149 * - `XXH_FORCE_MEMORY_ACCESS=2`: Direct cast
2150 * @par
2151 * Casts directly and dereferences. This method doesn't depend on the
2152 * compiler, but it violates the C standard as it directly dereferences an
2153 * unaligned pointer. It can generate buggy code on targets which do not
2154 * support unaligned memory accesses, but in some circumstances, it's the
2155 * only known way to get the most performance.
2156 *
2157 * - `XXH_FORCE_MEMORY_ACCESS=3`: Byteshift
2158 * @par
2159 * Also portable. This can generate the best code on old compilers which don't
2160 * inline small `memcpy()` calls, and it might also be faster on big-endian
2161 * systems which lack a native byteswap instruction. However, some compilers
2162 * will emit literal byteshifts even if the target supports unaligned access.
2163 *
2164 *
2165 * @warning
2166 * Methods 1 and 2 rely on implementation-defined behavior. Use these with
2167 * care, as what works on one compiler/platform/optimization level may cause
2168 * another to read garbage data or even crash.
2169 *
2170 * See https://fastcompression.blogspot.com/2015/08/accessing-unaligned-memory.html for details.
2171 *
2172 * Prefer these methods in priority order (0 > 3 > 1 > 2)
2173 */
2174 # define XXH_FORCE_MEMORY_ACCESS 0
2175
2176 /*!
2177 * @def XXH_SIZE_OPT
2178 * @brief Controls how much xxHash optimizes for size.
2179 *
2180 * xxHash, when compiled, tends to result in a rather large binary size. This
2181 * is mostly due to heavy usage to forced inlining and constant folding of the
2182 * @ref XXH3_family to increase performance.
2183 *
2184 * However, some developers prefer size over speed. This option can
2185 * significantly reduce the size of the generated code. When using the `-Os`
2186 * or `-Oz` options on GCC or Clang, this is defined to 1 by default,
2187 * otherwise it is defined to 0.
2188 *
2189 * Most of these size optimizations can be controlled manually.
2190 *
2191 * This is a number from 0-2.
2192 * - `XXH_SIZE_OPT` == 0: Default. xxHash makes no size optimizations. Speed
2193 * comes first.
2194 * - `XXH_SIZE_OPT` == 1: Default for `-Os` and `-Oz`. xxHash is more
2195 * conservative and disables hacks that increase code size. It implies the
2196 * options @ref XXH_NO_INLINE_HINTS == 1, @ref XXH_FORCE_ALIGN_CHECK == 0,
2197 * and @ref XXH3_NEON_LANES == 8 if they are not already defined.
2198 * - `XXH_SIZE_OPT` == 2: xxHash tries to make itself as small as possible.
2199 * Performance may cry. For example, the single shot functions just use the
2200 * streaming API.
2201 */
2202 # define XXH_SIZE_OPT 0
2203
2204 /*!
2205 * @def XXH_FORCE_ALIGN_CHECK
2206 * @brief If defined to non-zero, adds a special path for aligned inputs (XXH32()
2207 * and XXH64() only).
2208 *
2209 * This is an important performance trick for architectures without decent
2210 * unaligned memory access performance.
2211 *
2212 * It checks for input alignment, and when conditions are met, uses a "fast
2213 * path" employing direct 32-bit/64-bit reads, resulting in _dramatically
2214 * faster_ read speed.
2215 *
2216 * The check costs one initial branch per hash, which is generally negligible,
2217 * but not zero.
2218 *
2219 * Moreover, it's not useful to generate an additional code path if memory
2220 * access uses the same instruction for both aligned and unaligned
2221 * addresses (e.g. x86 and aarch64).
2222 *
2223 * In these cases, the alignment check can be removed by setting this macro to 0.
2224 * Then the code will always use unaligned memory access.
2225 * Align check is automatically disabled on x86, x64, ARM64, and some ARM chips
2226 * which are platforms known to offer good unaligned memory accesses performance.
2227 *
2228 * It is also disabled by default when @ref XXH_SIZE_OPT >= 1.
2229 *
2230 * This option does not affect XXH3 (only XXH32 and XXH64).
2231 */
2232 # define XXH_FORCE_ALIGN_CHECK 0
2233
2234 /*!
2235 * @def XXH_NO_INLINE_HINTS
2236 * @brief When non-zero, sets all functions to `static`.
2237 *
2238 * By default, xxHash tries to force the compiler to inline almost all internal
2239 * functions.
2240 *
2241 * This can usually improve performance due to reduced jumping and improved
2242 * constant folding, but significantly increases the size of the binary which
2243 * might not be favorable.
2244 *
2245 * Additionally, sometimes the forced inlining can be detrimental to performance,
2246 * depending on the architecture.
2247 *
2248 * XXH_NO_INLINE_HINTS marks all internal functions as static, giving the
2249 * compiler full control on whether to inline or not.
2250 *
2251 * When not optimizing (-O0), using `-fno-inline` with GCC or Clang, or if
2252 * @ref XXH_SIZE_OPT >= 1, this will automatically be defined.
2253 */
2254 # define XXH_NO_INLINE_HINTS 0
2255
2256 /*!
2257 * @def XXH3_INLINE_SECRET
2258 * @brief Determines whether to inline the XXH3 withSecret code.
2259 *
2260 * When the secret size is known, the compiler can improve the performance
2261 * of XXH3_64bits_withSecret() and XXH3_128bits_withSecret().
2262 *
2263 * However, if the secret size is not known, it doesn't have any benefit. This
2264 * happens when xxHash is compiled into a global symbol. Therefore, if
2265 * @ref XXH_INLINE_ALL is *not* defined, this will be defined to 0.
2266 *
2267 * Additionally, this defaults to 0 on GCC 12+, which has an issue with function pointers
2268 * that are *sometimes* force inline on -Og, and it is impossible to automatically
2269 * detect this optimization level.
2270 */
2271 # define XXH3_INLINE_SECRET 0
2272
2273 /*!
2274 * @def XXH32_ENDJMP
2275 * @brief Whether to use a jump for `XXH32_finalize`.
2276 *
2277 * For performance, `XXH32_finalize` uses multiple branches in the finalizer.
2278 * This is generally preferable for performance,
2279 * but depending on exact architecture, a jmp may be preferable.
2280 *
2281 * This setting is only possibly making a difference for very small inputs.
2282 */
2283 # define XXH32_ENDJMP 0
2284
2285 /*!
2286 * @internal
2287 * @brief Redefines old internal names.
2288 *
2289 * For compatibility with code that uses xxHash's internals before the names
2290 * were changed to improve namespacing. There is no other reason to use this.
2291 */
2292 # define XXH_OLD_NAMES
2293 # undef XXH_OLD_NAMES /* don't actually use, it is ugly. */
2294
2295 /*!
2296 * @def XXH_NO_STREAM
2297 * @brief Disables the streaming API.
2298 *
2299 * When xxHash is not inlined and the streaming functions are not used, disabling
2300 * the streaming functions can improve code size significantly, especially with
2301 * the @ref XXH3_family which tends to make constant folded copies of itself.
2302 */
2303 # define XXH_NO_STREAM
2304 # undef XXH_NO_STREAM /* don't actually */
2305 # endif /* XXH_DOXYGEN */
2306 /*!
2307 * @}
2308 */
2309
2310 # ifndef XXH_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */
2311 /* prefer __packed__ structures (method 1) for GCC
2312 * < ARMv7 with unaligned access (e.g. Raspbian armhf) still uses byte shifting, so we use memcpy
2313 * which for some reason does unaligned loads. */
2314 # if defined(__GNUC__) && !(defined(__ARM_ARCH) && __ARM_ARCH < 7 && defined(__ARM_FEATURE_UNALIGNED))
2315 # define XXH_FORCE_MEMORY_ACCESS 1
2316 # endif
2317 # endif
2318
2319 # ifndef XXH_SIZE_OPT
2320 /* default to 1 for -Os or -Oz */
2321 # if (defined(__GNUC__) || defined(__clang__)) && defined(__OPTIMIZE_SIZE__)
2322 # define XXH_SIZE_OPT 1
2323 # else
2324 # define XXH_SIZE_OPT 0
2325 # endif
2326 # endif
2327
2328 # ifndef XXH_FORCE_ALIGN_CHECK /* can be defined externally */
2329 /* don't check on sizeopt, x86, aarch64, or arm when unaligned access is available */
2330 # if XXH_SIZE_OPT >= 1 || defined(__i386) || defined(__x86_64__) || defined(__aarch64__) || \
2331 defined(__ARM_FEATURE_UNALIGNED) || defined(_M_IX86) || defined(_M_X64) || defined(_M_ARM64) || \
2332 defined(_M_ARM) /* visual */
2333 # define XXH_FORCE_ALIGN_CHECK 0
2334 # else
2335 # define XXH_FORCE_ALIGN_CHECK 1
2336 # endif
2337 # endif
2338
2339 # ifndef XXH_NO_INLINE_HINTS
2340 # if XXH_SIZE_OPT >= 1 || defined(__NO_INLINE__) /* -O0, -fno-inline */
2341 # define XXH_NO_INLINE_HINTS 1
2342 # else
2343 # define XXH_NO_INLINE_HINTS 0
2344 # endif
2345 # endif
2346
2347 # ifndef XXH3_INLINE_SECRET
2348 # if (defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 12) || !defined(XXH_INLINE_ALL)
2349 # define XXH3_INLINE_SECRET 0
2350 # else
2351 # define XXH3_INLINE_SECRET 1
2352 # endif
2353 # endif
2354
2355 # ifndef XXH32_ENDJMP
2356 /* generally preferable for performance */
2357 # define XXH32_ENDJMP 0
2358 # endif
2359
2360 /*!
2361 * @defgroup impl Implementation
2362 * @{
2363 */
2364
2365 /* *************************************
2366 * Includes & Memory related functions
2367 ***************************************/
2368 # if defined(XXH_NO_STREAM)
2369 /* nothing */
2370 # elif defined(XXH_NO_STDLIB)
2371
2372 /* When requesting to disable any mention of stdlib,
2373 * the library loses the ability to invoked malloc / free.
2374 * In practice, it means that functions like `XXH*_createState()`
2375 * will always fail, and return NULL.
2376 * This flag is useful in situations where
2377 * xxhash.h is integrated into some kernel, embedded or limited environment
2378 * without access to dynamic allocation.
2379 */
2380
2381 static XXH_CONSTF void *XXH_malloc(size_t s) {
2382 (void)s;
2383 return NULL;
2384 }
2385 static void XXH_free(void *p) {
2386 (void)p;
2387 }
2388
2389 # else
2390
2391 /*
2392 * Modify the local functions below should you wish to use
2393 * different memory routines for malloc() and free()
2394 */
2395 # include <stdlib.h>
2396
2397
2398 /*************************
2399 * Note: this version has been modified to pass custom allocator for all mem allocations.
2400 * Remainder of the code is unchanged.
2401 * Affected section will have a similar disclaimer.
2402 */
2403
2404
2405 /************** CRT modifications start */
2406 #include <aws/common/allocator.h>
2407
2408 static struct aws_allocator *s_xxh_allocator = NULL;
2409
2410 XXH_PUBLIC_API void XXH_set_allocator(struct aws_allocator *allocator) {
2411 s_xxh_allocator = allocator;
2412 }
2413
2414 /*!
2415 * @internal
2416 * @brief Modify this function to use a different routine than malloc().
2417 */
2418 static XXH_MALLOCF void *XXH_malloc(size_t s) {
2419 if (AWS_UNLIKELY(s_xxh_allocator)) {
2420 return malloc(s);
2421 } else {
2422 return aws_mem_calloc(s_xxh_allocator, 1, s);
2423 }
2424 }
2425
2426 /*!
2427 * @internal
2428 * @brief Modify this function to use a different routine than free().
2429 */
2430 static void XXH_free(void *p) {
2431 if (AWS_UNLIKELY(s_xxh_allocator)) {
2432 free(p);
2433 } else {
2434 aws_mem_release(s_xxh_allocator, p);
2435 }
2436 }
2437
2438 /************** CRT modifications end */
2439
2440 # endif /* XXH_NO_STDLIB */
2441
2442 # ifndef XXH_memcpy
2443 /*!
2444 * @internal
2445 * @brief XXH_memcpy() macro can be redirected at compile time
2446 */
2447 # include <string.h>
2448 # define XXH_memcpy memcpy
2449 # endif
2450
2451 # ifndef XXH_memset
2452 /*!
2453 * @internal
2454 * @brief XXH_memset() macro can be redirected at compile time
2455 */
2456 # include <string.h>
2457 # define XXH_memset memset
2458 # endif
2459
2460 # ifndef XXH_memcmp
2461 /*!
2462 * @internal
2463 * @brief XXH_memcmp() macro can be redirected at compile time
2464 * Note: only needed by XXH128.
2465 */
2466 # include <string.h>
2467 # define XXH_memcmp memcmp
2468 # endif
2469
2470 # include <limits.h> /* ULLONG_MAX */
2471
2472 /* *************************************
2473 * Compiler Specific Options
2474 ***************************************/
2475 # ifdef _MSC_VER /* Visual Studio warning fix */
2476 # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
2477 # endif
2478
2479 # if XXH_NO_INLINE_HINTS /* disable inlining hints */
2480 # if defined(__GNUC__) || defined(__clang__)
2481 # define XXH_FORCE_INLINE static __attribute__((__unused__))
2482 # else
2483 # define XXH_FORCE_INLINE static
2484 # endif
2485 # define XXH_NO_INLINE static
2486 /* enable inlining hints */
2487 # elif defined(__GNUC__) || defined(__clang__)
2488 # define XXH_FORCE_INLINE static __inline__ __attribute__((__always_inline__, __unused__))
2489 # define XXH_NO_INLINE static __attribute__((__noinline__))
2490 # elif defined(_MSC_VER) /* Visual Studio */
2491 # define XXH_FORCE_INLINE static __forceinline
2492 # define XXH_NO_INLINE static __declspec(noinline)
2493 # elif defined(__cplusplus) || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) /* C99 */
2494 # define XXH_FORCE_INLINE static inline
2495 # define XXH_NO_INLINE static
2496 # else
2497 # define XXH_FORCE_INLINE static
2498 # define XXH_NO_INLINE static
2499 # endif
2500
2501 # if defined(XXH_INLINE_ALL)
2502 # define XXH_STATIC XXH_FORCE_INLINE
2503 # else
2504 # define XXH_STATIC static
2505 # endif
2506
2507 # if XXH3_INLINE_SECRET
2508 # define XXH3_WITH_SECRET_INLINE XXH_FORCE_INLINE
2509 # else
2510 # define XXH3_WITH_SECRET_INLINE XXH_NO_INLINE
2511 # endif
2512
2513 # if ((defined(sun) || defined(__sun)) && __cplusplus) /* Solaris includes __STDC_VERSION__ with C++. Tested with \
2514 GCC 5.5 */
2515 # define XXH_RESTRICT /* disable */
2516 # elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* >= C99 */
2517 # define XXH_RESTRICT restrict
2518 # elif (defined(__GNUC__) && ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))) || (defined(__clang__)) || \
2519 (defined(_MSC_VER) && (_MSC_VER >= 1400)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1300))
2520 /*
2521 * There are a LOT more compilers that recognize __restrict but this
2522 * covers the major ones.
2523 */
2524 # define XXH_RESTRICT __restrict
2525 # else
2526 # define XXH_RESTRICT /* disable */
2527 # endif
2528
2529 /* *************************************
2530 * Debug
2531 ***************************************/
2532 /*!
2533 * @ingroup tuning
2534 * @def XXH_DEBUGLEVEL
2535 * @brief Sets the debugging level.
2536 *
2537 * XXH_DEBUGLEVEL is expected to be defined externally, typically via the
2538 * compiler's command line options. The value must be a number.
2539 */
2540 # ifndef XXH_DEBUGLEVEL
2541 # ifdef DEBUGLEVEL /* backwards compat */
2542 # define XXH_DEBUGLEVEL DEBUGLEVEL
2543 # else
2544 # define XXH_DEBUGLEVEL 0
2545 # endif
2546 # endif
2547
2548 # if (XXH_DEBUGLEVEL >= 1)
2549 # include <assert.h> /* note: can still be disabled with NDEBUG */
2550 # define XXH_ASSERT(c) assert(c)
2551 # else
2552 # if defined(__INTEL_COMPILER)
2553 # define XXH_ASSERT(c) XXH_ASSUME((unsigned char)(c))
2554 # else
2555 # define XXH_ASSERT(c) XXH_ASSUME(c)
2556 # endif
2557 # endif
2558
2559 /* note: use after variable declarations */
2560 # ifndef XXH_STATIC_ASSERT
2561 # if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */
2562 # define XXH_STATIC_ASSERT_WITH_MESSAGE(c, m) \
2563 do { \
2564 _Static_assert((c), m); \
2565 } while (0)
2566 # elif defined(__cplusplus) && (__cplusplus >= 201103L) /* C++11 */
2567 # define XXH_STATIC_ASSERT_WITH_MESSAGE(c, m) \
2568 do { \
2569 static_assert((c), m); \
2570 } while (0)
2571 # else
2572 # define XXH_STATIC_ASSERT_WITH_MESSAGE(c, m) \
2573 do { \
2574 struct xxh_sa { \
2575 char x[(c) ? 1 : -1]; \
2576 }; \
2577 } while (0)
2578 # endif
2579 # define XXH_STATIC_ASSERT(c) XXH_STATIC_ASSERT_WITH_MESSAGE((c), #c)
2580 # endif
2581
2582 /*!
2583 * @internal
2584 * @def XXH_COMPILER_GUARD(var)
2585 * @brief Used to prevent unwanted optimizations for @p var.
2586 *
2587 * It uses an empty GCC inline assembly statement with a register constraint
2588 * which forces @p var into a general purpose register (eg eax, ebx, ecx
2589 * on x86) and marks it as modified.
2590 *
2591 * This is used in a few places to avoid unwanted autovectorization (e.g.
2592 * XXH32_round()). All vectorization we want is explicit via intrinsics,
2593 * and _usually_ isn't wanted elsewhere.
2594 *
2595 * We also use it to prevent unwanted constant folding for AArch64 in
2596 * XXH3_initCustomSecret_scalar().
2597 */
2598 # if defined(__GNUC__) || defined(__clang__)
2599 # define XXH_COMPILER_GUARD(var) __asm__("" : "+r"(var))
2600 # else
2601 # define XXH_COMPILER_GUARD(var) ((void)0)
2602 # endif
2603
2604 /* Specifically for NEON vectors which use the "w" constraint, on
2605 * Clang. */
2606 # if defined(__clang__) && defined(__ARM_ARCH) && !defined(__wasm__)
2607 # define XXH_COMPILER_GUARD_CLANG_NEON(var) __asm__("" : "+w"(var))
2608 # else
2609 # define XXH_COMPILER_GUARD_CLANG_NEON(var) ((void)0)
2610 # endif
2611
2612 /* *************************************
2613 * Basic Types
2614 ***************************************/
2615 # if !defined(__VMS) && \
2616 (defined(__cplusplus) || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */))
2617 # ifdef _AIX
2618 # include <inttypes.h>
2619 # else
2620 # include <stdint.h>
2621 # endif
2622 typedef uint8_t xxh_u8;
2623 # else
2624 typedef unsigned char xxh_u8;
2625 # endif
2626 typedef XXH32_hash_t xxh_u32;
2627
2628 # ifdef XXH_OLD_NAMES
2629 # warning \
2630 "XXH_OLD_NAMES is planned to be removed starting v0.9. If the program depends on it, consider moving away from it by employing newer type names directly"
2631 # define BYTE xxh_u8
2632 # define U8 xxh_u8
2633 # define U32 xxh_u32
2634 # endif
2635
2636 /* *** Memory access *** */
2637
2638 /*!
2639 * @internal
2640 * @fn xxh_u32 XXH_read32(const void* ptr)
2641 * @brief Reads an unaligned 32-bit integer from @p ptr in native endianness.
2642 *
2643 * Affected by @ref XXH_FORCE_MEMORY_ACCESS.
2644 *
2645 * @param ptr The pointer to read from.
2646 * @return The 32-bit native endian integer from the bytes at @p ptr.
2647 */
2648
2649 /*!
2650 * @internal
2651 * @fn xxh_u32 XXH_readLE32(const void* ptr)
2652 * @brief Reads an unaligned 32-bit little endian integer from @p ptr.
2653 *
2654 * Affected by @ref XXH_FORCE_MEMORY_ACCESS.
2655 *
2656 * @param ptr The pointer to read from.
2657 * @return The 32-bit little endian integer from the bytes at @p ptr.
2658 */
2659
2660 /*!
2661 * @internal
2662 * @fn xxh_u32 XXH_readBE32(const void* ptr)
2663 * @brief Reads an unaligned 32-bit big endian integer from @p ptr.
2664 *
2665 * Affected by @ref XXH_FORCE_MEMORY_ACCESS.
2666 *
2667 * @param ptr The pointer to read from.
2668 * @return The 32-bit big endian integer from the bytes at @p ptr.
2669 */
2670
2671 /*!
2672 * @internal
2673 * @fn xxh_u32 XXH_readLE32_align(const void* ptr, XXH_alignment align)
2674 * @brief Like @ref XXH_readLE32(), but has an option for aligned reads.
2675 *
2676 * Affected by @ref XXH_FORCE_MEMORY_ACCESS.
2677 * Note that when @ref XXH_FORCE_ALIGN_CHECK == 0, the @p align parameter is
2678 * always @ref XXH_alignment::XXH_unaligned.
2679 *
2680 * @param ptr The pointer to read from.
2681 * @param align Whether @p ptr is aligned.
2682 * @pre
2683 * If @p align == @ref XXH_alignment::XXH_aligned, @p ptr must be 4 byte
2684 * aligned.
2685 * @return The 32-bit little endian integer from the bytes at @p ptr.
2686 */
2687
2688 # if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS == 3))
2689 /*
2690 * Manual byteshift. Best for old compilers which don't inline memcpy.
2691 * We actually directly use XXH_readLE32 and XXH_readBE32.
2692 */
2693 # elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS == 2))
2694
2695 /*
2696 * Force direct memory access. Only works on CPU which support unaligned memory
2697 * access in hardware.
2698 */
2699 static xxh_u32 XXH_read32(const void *memPtr) {
2700 return *(const xxh_u32 *)memPtr;
2701 }
2702
2703 # elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS == 1))
2704
2705 /*
2706 * __attribute__((aligned(1))) is supported by gcc and clang. Originally the
2707 * documentation claimed that it only increased the alignment, but actually it
2708 * can decrease it on gcc, clang, and icc:
2709 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69502,
2710 * https://gcc.godbolt.org/z/xYez1j67Y.
2711 */
2712 # ifdef XXH_OLD_NAMES
2713 typedef union {
2714 xxh_u32 u32;
2715 } __attribute__((__packed__)) unalign;
2716 # endif
2717 static xxh_u32 XXH_read32(const void *ptr) {
2718 typedef __attribute__((__aligned__(1))) __attribute__((__may_alias__)) xxh_u32 xxh_unalign32;
2719 return *((const xxh_unalign32 *)ptr);
2720 }
2721
2722 # else
2723
2724 /*
2725 * Portable and safe solution. Generally efficient.
2726 * see: https://fastcompression.blogspot.com/2015/08/accessing-unaligned-memory.html
2727 */
2728 static xxh_u32 XXH_read32(const void *memPtr) {
2729 xxh_u32 val;
2730 XXH_memcpy(&val, memPtr, sizeof(val));
2731 return val;
2732 }
2733
2734 # endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */
2735
2736 /* *** Endianness *** */
2737
2738 /*!
2739 * @ingroup tuning
2740 * @def XXH_CPU_LITTLE_ENDIAN
2741 * @brief Whether the target is little endian.
2742 *
2743 * Defined to 1 if the target is little endian, or 0 if it is big endian.
2744 * It can be defined externally, for example on the compiler command line.
2745 *
2746 * If it is not defined,
2747 * a runtime check (which is usually constant folded) is used instead.
2748 *
2749 * @note
2750 * This is not necessarily defined to an integer constant.
2751 *
2752 * @see XXH_isLittleEndian() for the runtime check.
2753 */
2754 # ifndef XXH_CPU_LITTLE_ENDIAN
2755 /*
2756 * Try to detect endianness automatically, to avoid the nonstandard behavior
2757 * in `XXH_isLittleEndian()`
2758 */
2759 # if defined(_WIN32) /* Windows is always little endian */ \
2760 || defined(__LITTLE_ENDIAN__) || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
2761 # define XXH_CPU_LITTLE_ENDIAN 1
2762 # elif defined(__BIG_ENDIAN__) || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
2763 # define XXH_CPU_LITTLE_ENDIAN 0
2764 # else
2765 /*!
2766 * @internal
2767 * @brief Runtime check for @ref XXH_CPU_LITTLE_ENDIAN.
2768 *
2769 * Most compilers will constant fold this.
2770 */
2771 static int XXH_isLittleEndian(void) {
2772 /*
2773 * Portable and well-defined behavior.
2774 * Don't use static: it is detrimental to performance.
2775 */
2776 const union {
2777 xxh_u32 u;
2778 xxh_u8 c[4];
2779 } one = {1};
2780 return one.c[0];
2781 }
2782 # define XXH_CPU_LITTLE_ENDIAN XXH_isLittleEndian()
2783 # endif
2784 # endif
2785
2786 /* ****************************************
2787 * Compiler-specific Functions and Macros
2788 ******************************************/
2789 # define XXH_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
2790
2791 # ifdef __has_builtin
2792 # define XXH_HAS_BUILTIN(x) __has_builtin(x)
2793 # else
2794 # define XXH_HAS_BUILTIN(x) 0
2795 # endif
2796
2797 /*
2798 * C23 and future versions have standard "unreachable()".
2799 * Once it has been implemented reliably we can add it as an
2800 * additional case:
2801 *
2802 * ```
2803 * #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L)
2804 * # include <stddef.h>
2805 * # ifdef unreachable
2806 * # define XXH_UNREACHABLE() unreachable()
2807 * # endif
2808 * #endif
2809 * ```
2810 *
2811 * Note C++23 also has std::unreachable() which can be detected
2812 * as follows:
2813 * ```
2814 * #if defined(__cpp_lib_unreachable) && (__cpp_lib_unreachable >= 202202L)
2815 * # include <utility>
2816 * # define XXH_UNREACHABLE() std::unreachable()
2817 * #endif
2818 * ```
2819 * NB: `__cpp_lib_unreachable` is defined in the `<version>` header.
2820 * We don't use that as including `<utility>` in `extern "C"` blocks
2821 * doesn't work on GCC12
2822 */
2823
2824 # if XXH_HAS_BUILTIN(__builtin_unreachable)
2825 # define XXH_UNREACHABLE() __builtin_unreachable()
2826
2827 # elif defined(_MSC_VER)
2828 # define XXH_UNREACHABLE() __assume(0)
2829
2830 # else
2831 # define XXH_UNREACHABLE()
2832 # endif
2833
2834 # if XXH_HAS_BUILTIN(__builtin_assume)
2835 # define XXH_ASSUME(c) __builtin_assume(c)
2836 # else
2837 # define XXH_ASSUME(c) \
2838 if (!(c)) { \
2839 XXH_UNREACHABLE(); \
2840 }
2841 # endif
2842
2843 /*!
2844 * @internal
2845 * @def XXH_rotl32(x,r)
2846 * @brief 32-bit rotate left.
2847 *
2848 * @param x The 32-bit integer to be rotated.
2849 * @param r The number of bits to rotate.
2850 * @pre
2851 * @p r > 0 && @p r < 32
2852 * @note
2853 * @p x and @p r may be evaluated multiple times.
2854 * @return The rotated result.
2855 */
2856 # if !defined(NO_CLANG_BUILTIN) && XXH_HAS_BUILTIN(__builtin_rotateleft32) && XXH_HAS_BUILTIN(__builtin_rotateleft64)
2857 # define XXH_rotl32 __builtin_rotateleft32
2858 # define XXH_rotl64 __builtin_rotateleft64
2859 # elif XXH_HAS_BUILTIN(__builtin_stdc_rotate_left)
2860 # define XXH_rotl32 __builtin_stdc_rotate_left
2861 # define XXH_rotl64 __builtin_stdc_rotate_left
2862 /* Note: although _rotl exists for minGW (GCC under windows), performance seems poor */
2863 # elif defined(_MSC_VER)
2864 # define XXH_rotl32(x, r) _rotl(x, r)
2865 # define XXH_rotl64(x, r) _rotl64(x, r)
2866 # else
2867 # define XXH_rotl32(x, r) (((x) << (r)) | ((x) >> (32 - (r))))
2868 # define XXH_rotl64(x, r) (((x) << (r)) | ((x) >> (64 - (r))))
2869 # endif
2870
2871 /*!
2872 * @internal
2873 * @fn xxh_u32 XXH_swap32(xxh_u32 x)
2874 * @brief A 32-bit byteswap.
2875 *
2876 * @param x The 32-bit integer to byteswap.
2877 * @return @p x, byteswapped.
2878 */
2879 # if defined(_MSC_VER) /* Visual Studio */
2880 # define XXH_swap32 _byteswap_ulong
2881 # elif XXH_GCC_VERSION >= 403
2882 # define XXH_swap32 __builtin_bswap32
2883 # else
2884 static xxh_u32 XXH_swap32(xxh_u32 x) {
2885 return ((x << 24) & 0xff000000) | ((x << 8) & 0x00ff0000) | ((x >> 8) & 0x0000ff00) | ((x >> 24) & 0x000000ff);
2886 }
2887 # endif
2888
2889 /* ***************************
2890 * Memory reads
2891 *****************************/
2892
2893 /*!
2894 * @internal
2895 * @brief Enum to indicate whether a pointer is aligned.
2896 */
2897 typedef enum {
2898 XXH_aligned, /*!< Aligned */
2899 XXH_unaligned /*!< Possibly unaligned */
2900 } XXH_alignment;
2901
2902 /*
2903 * XXH_FORCE_MEMORY_ACCESS==3 is an endian-independent byteshift load.
2904 *
2905 * This is ideal for older compilers which don't inline memcpy.
2906 */
2907 # if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS == 3))
2908
2909 XXH_FORCE_INLINE xxh_u32 XXH_readLE32(const void *memPtr) {
2910 const xxh_u8 *bytePtr = (const xxh_u8 *)memPtr;
2911 return bytePtr[0] | ((xxh_u32)bytePtr[1] << 8) | ((xxh_u32)bytePtr[2] << 16) | ((xxh_u32)bytePtr[3] << 24);
2912 }
2913
2914 XXH_FORCE_INLINE xxh_u32 XXH_readBE32(const void *memPtr) {
2915 const xxh_u8 *bytePtr = (const xxh_u8 *)memPtr;
2916 return bytePtr[3] | ((xxh_u32)bytePtr[2] << 8) | ((xxh_u32)bytePtr[1] << 16) | ((xxh_u32)bytePtr[0] << 24);
2917 }
2918
2919 # else
2920 XXH_FORCE_INLINE xxh_u32 XXH_readLE32(const void *ptr) {
2921 return XXH_CPU_LITTLE_ENDIAN ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr));
2922 }
2923
2924 static xxh_u32 XXH_readBE32(const void *ptr) {
2925 return XXH_CPU_LITTLE_ENDIAN ? XXH_swap32(XXH_read32(ptr)) : XXH_read32(ptr);
2926 }
2927 # endif
2928
2929 XXH_FORCE_INLINE xxh_u32 XXH_readLE32_align(const void *ptr, XXH_alignment align) {
2930 if (align == XXH_unaligned) {
2931 return XXH_readLE32(ptr);
2932 } else {
2933 return XXH_CPU_LITTLE_ENDIAN ? *(const xxh_u32 *)ptr : XXH_swap32(*(const xxh_u32 *)ptr);
2934 }
2935 }
2936
2937 /* *************************************
2938 * Misc
2939 ***************************************/
2940 /*! @ingroup public */
2941 XXH_PUBLIC_API unsigned XXH_versionNumber(void) {
2942 return XXH_VERSION_NUMBER;
2943 }
2944
2945 /* *******************************************************************
2946 * 32-bit hash functions
2947 *********************************************************************/
2948 /*!
2949 * @}
2950 * @defgroup XXH32_impl XXH32 implementation
2951 * @ingroup impl
2952 *
2953 * Details on the XXH32 implementation.
2954 * @{
2955 */
2956 /* #define instead of static const, to be used as initializers */
2957 # define XXH_PRIME32_1 0x9E3779B1U /*!< 0b10011110001101110111100110110001 */
2958 # define XXH_PRIME32_2 0x85EBCA77U /*!< 0b10000101111010111100101001110111 */
2959 # define XXH_PRIME32_3 0xC2B2AE3DU /*!< 0b11000010101100101010111000111101 */
2960 # define XXH_PRIME32_4 0x27D4EB2FU /*!< 0b00100111110101001110101100101111 */
2961 # define XXH_PRIME32_5 0x165667B1U /*!< 0b00010110010101100110011110110001 */
2962
2963 # ifdef XXH_OLD_NAMES
2964 # define PRIME32_1 XXH_PRIME32_1
2965 # define PRIME32_2 XXH_PRIME32_2
2966 # define PRIME32_3 XXH_PRIME32_3
2967 # define PRIME32_4 XXH_PRIME32_4
2968 # define PRIME32_5 XXH_PRIME32_5
2969 # endif
2970
2971 /*!
2972 * @internal
2973 * @brief Normal stripe processing routine.
2974 *
2975 * This shuffles the bits so that any bit from @p input impacts several bits in
2976 * @p acc.
2977 *
2978 * @param acc The accumulator lane.
2979 * @param input The stripe of input to mix.
2980 * @return The mixed accumulator lane.
2981 */
2982 static xxh_u32 XXH32_round(xxh_u32 acc, xxh_u32 input) {
2983 acc += input * XXH_PRIME32_2;
2984 acc = XXH_rotl32(acc, 13);
2985 acc *= XXH_PRIME32_1;
2986 # if (defined(__SSE4_1__) || defined(__aarch64__) || defined(__wasm_simd128__)) && !defined(XXH_ENABLE_AUTOVECTORIZE)
2987 /*
2988 * UGLY HACK:
2989 * A compiler fence is used to prevent GCC and Clang from
2990 * autovectorizing the XXH32 loop (pragmas and attributes don't work for some
2991 * reason) without globally disabling SSE4.1.
2992 *
2993 * The reason we want to avoid vectorization is because despite working on
2994 * 4 integers at a time, there are multiple factors slowing XXH32 down on
2995 * SSE4:
2996 * - There's a ridiculous amount of lag from pmulld (10 cycles of latency on
2997 * newer chips!) making it slightly slower to multiply four integers at
2998 * once compared to four integers independently. Even when pmulld was
2999 * fastest, Sandy/Ivy Bridge, it is still not worth it to go into SSE
3000 * just to multiply unless doing a long operation.
3001 *
3002 * - Four instructions are required to rotate,
3003 * movqda tmp, v // not required with VEX encoding
3004 * pslld tmp, 13 // tmp <<= 13
3005 * psrld v, 19 // x >>= 19
3006 * por v, tmp // x |= tmp
3007 * compared to one for scalar:
3008 * roll v, 13 // reliably fast across the board
3009 * shldl v, v, 13 // Sandy Bridge and later prefer this for some reason
3010 *
3011 * - Instruction level parallelism is actually more beneficial here because
3012 * the SIMD actually serializes this operation: While v1 is rotating, v2
3013 * can load data, while v3 can multiply. SSE forces them to operate
3014 * together.
3015 *
3016 * This is also enabled on AArch64, as Clang is *very aggressive* in vectorizing
3017 * the loop. NEON is only faster on the A53, and with the newer cores, it is less
3018 * than half the speed.
3019 *
3020 * Additionally, this is used on WASM SIMD128 because it JITs to the same
3021 * SIMD instructions and has the same issue.
3022 */
3023 XXH_COMPILER_GUARD(acc);
3024 # endif
3025 return acc;
3026 }
3027
3028 /*!
3029 * @internal
3030 * @brief Mixes all bits to finalize the hash.
3031 *
3032 * The final mix ensures that all input bits have a chance to impact any bit in
3033 * the output digest, resulting in an unbiased distribution.
3034 *
3035 * @param hash The hash to avalanche.
3036 * @return The avalanched hash.
3037 */
3038 static xxh_u32 XXH32_avalanche(xxh_u32 hash) {
3039 hash ^= hash >> 15;
3040 hash *= XXH_PRIME32_2;
3041 hash ^= hash >> 13;
3042 hash *= XXH_PRIME32_3;
3043 hash ^= hash >> 16;
3044 return hash;
3045 }
3046
3047 # define XXH_get32bits(p) XXH_readLE32_align(p, align)
3048
3049 /*!
3050 * @internal
3051 * @brief Sets up the initial accumulator state for XXH32().
3052 */
3053 XXH_FORCE_INLINE void XXH32_initAccs(xxh_u32 *acc, xxh_u32 seed) {
3054 XXH_ASSERT(acc != NULL);
3055 acc[0] = seed + XXH_PRIME32_1 + XXH_PRIME32_2;
3056 acc[1] = seed + XXH_PRIME32_2;
3057 acc[2] = seed + 0;
3058 acc[3] = seed - XXH_PRIME32_1;
3059 }
3060
3061 /*!
3062 * @internal
3063 * @brief Consumes a block of data for XXH32().
3064 *
3065 * @return the end input pointer.
3066 */
3067 XXH_FORCE_INLINE const xxh_u8 *XXH32_consumeLong(
3068 xxh_u32 *XXH_RESTRICT acc,
3069 xxh_u8 const *XXH_RESTRICT input,
3070 size_t len,
3071 XXH_alignment align) {
3072 const xxh_u8 *const bEnd = input + len;
3073 const xxh_u8 *const limit = bEnd - 15;
3074 XXH_ASSERT(acc != NULL);
3075 XXH_ASSERT(input != NULL);
3076 XXH_ASSERT(len >= 16);
3077 do {
3078 acc[0] = XXH32_round(acc[0], XXH_get32bits(input));
3079 input += 4;
3080 acc[1] = XXH32_round(acc[1], XXH_get32bits(input));
3081 input += 4;
3082 acc[2] = XXH32_round(acc[2], XXH_get32bits(input));
3083 input += 4;
3084 acc[3] = XXH32_round(acc[3], XXH_get32bits(input));
3085 input += 4;
3086 } while (input < limit);
3087
3088 return input;
3089 }
3090
3091 /*!
3092 * @internal
3093 * @brief Merges the accumulator lanes together for XXH32()
3094 */
3095 XXH_FORCE_INLINE XXH_PUREF xxh_u32 XXH32_mergeAccs(const xxh_u32 *acc) {
3096 XXH_ASSERT(acc != NULL);
3097 return XXH_rotl32(acc[0], 1) + XXH_rotl32(acc[1], 7) + XXH_rotl32(acc[2], 12) + XXH_rotl32(acc[3], 18);
3098 }
3099
3100 /*!
3101 * @internal
3102 * @brief Processes the last 0-15 bytes of @p ptr.
3103 *
3104 * There may be up to 15 bytes remaining to consume from the input.
3105 * This final stage will digest them to ensure that all input bytes are present
3106 * in the final mix.
3107 *
3108 * @param hash The hash to finalize.
3109 * @param ptr The pointer to the remaining input.
3110 * @param len The remaining length, modulo 16.
3111 * @param align Whether @p ptr is aligned.
3112 * @return The finalized hash.
3113 * @see XXH64_finalize().
3114 */
3115 static XXH_PUREF xxh_u32 XXH32_finalize(xxh_u32 hash, const xxh_u8 *ptr, size_t len, XXH_alignment align) {
3116 # define XXH_PROCESS1 \
3117 do { \
3118 hash += (*ptr++) * XXH_PRIME32_5; \
3119 hash = XXH_rotl32(hash, 11) * XXH_PRIME32_1; \
3120 } while (0)
3121
3122 # define XXH_PROCESS4 \
3123 do { \
3124 hash += XXH_get32bits(ptr) * XXH_PRIME32_3; \
3125 ptr += 4; \
3126 hash = XXH_rotl32(hash, 17) * XXH_PRIME32_4; \
3127 } while (0)
3128
3129 if (ptr == NULL)
3130 XXH_ASSERT(len == 0);
3131
3132 /* Compact rerolled version; generally faster */
3133 if (!XXH32_ENDJMP) {
3134 len &= 15;
3135 while (len >= 4) {
3136 XXH_PROCESS4;
3137 len -= 4;
3138 }
3139 while (len > 0) {
3140 XXH_PROCESS1;
3141 --len;
3142 }
3143 return XXH32_avalanche(hash);
3144 } else {
3145 switch (len & 15) /* or switch(bEnd - p) */ {
3146 case 12:
3147 XXH_PROCESS4;
3148 XXH_FALLTHROUGH; /* fallthrough */
3149 case 8:
3150 XXH_PROCESS4;
3151 XXH_FALLTHROUGH; /* fallthrough */
3152 case 4:
3153 XXH_PROCESS4;
3154 return XXH32_avalanche(hash);
3155
3156 case 13:
3157 XXH_PROCESS4;
3158 XXH_FALLTHROUGH; /* fallthrough */
3159 case 9:
3160 XXH_PROCESS4;
3161 XXH_FALLTHROUGH; /* fallthrough */
3162 case 5:
3163 XXH_PROCESS4;
3164 XXH_PROCESS1;
3165 return XXH32_avalanche(hash);
3166
3167 case 14:
3168 XXH_PROCESS4;
3169 XXH_FALLTHROUGH; /* fallthrough */
3170 case 10:
3171 XXH_PROCESS4;
3172 XXH_FALLTHROUGH; /* fallthrough */
3173 case 6:
3174 XXH_PROCESS4;
3175 XXH_PROCESS1;
3176 XXH_PROCESS1;
3177 return XXH32_avalanche(hash);
3178
3179 case 15:
3180 XXH_PROCESS4;
3181 XXH_FALLTHROUGH; /* fallthrough */
3182 case 11:
3183 XXH_PROCESS4;
3184 XXH_FALLTHROUGH; /* fallthrough */
3185 case 7:
3186 XXH_PROCESS4;
3187 XXH_FALLTHROUGH; /* fallthrough */
3188 case 3:
3189 XXH_PROCESS1;
3190 XXH_FALLTHROUGH; /* fallthrough */
3191 case 2:
3192 XXH_PROCESS1;
3193 XXH_FALLTHROUGH; /* fallthrough */
3194 case 1:
3195 XXH_PROCESS1;
3196 XXH_FALLTHROUGH; /* fallthrough */
3197 case 0:
3198 return XXH32_avalanche(hash);
3199 }
3200 XXH_ASSERT(0);
3201 return hash; /* reaching this point is deemed impossible */
3202 }
3203 }
3204
3205 # ifdef XXH_OLD_NAMES
3206 # define PROCESS1 XXH_PROCESS1
3207 # define PROCESS4 XXH_PROCESS4
3208 # else
3209 # undef XXH_PROCESS1
3210 # undef XXH_PROCESS4
3211 # endif
3212
3213 /*!
3214 * @internal
3215 * @brief The implementation for @ref XXH32().
3216 *
3217 * @param input , len , seed Directly passed from @ref XXH32().
3218 * @param align Whether @p input is aligned.
3219 * @return The calculated hash.
3220 */
3221 XXH_FORCE_INLINE XXH_PUREF xxh_u32
3222 XXH32_endian_align(const xxh_u8 *input, size_t len, xxh_u32 seed, XXH_alignment align) {
3223 xxh_u32 h32;
3224
3225 if (input == NULL)
3226 XXH_ASSERT(len == 0);
3227
3228 if (len >= 16) {
3229 xxh_u32 acc[4];
3230 XXH32_initAccs(acc, seed);
3231
3232 input = XXH32_consumeLong(acc, input, len, align);
3233
3234 h32 = XXH32_mergeAccs(acc);
3235 } else {
3236 h32 = seed + XXH_PRIME32_5;
3237 }
3238
3239 h32 += (xxh_u32)len;
3240
3241 return XXH32_finalize(h32, input, len & 15, align);
3242 }
3243
3244 /*! @ingroup XXH32_family */
3245 XXH_PUBLIC_API XXH32_hash_t XXH32(const void *input, size_t len, XXH32_hash_t seed) {
3246 # if !defined(XXH_NO_STREAM) && XXH_SIZE_OPT >= 2
3247 /* Simple version, good for code maintenance, but unfortunately slow for small inputs */
3248 XXH32_state_t state;
3249 XXH32_reset(&state, seed);
3250 XXH32_update(&state, (const xxh_u8 *)input, len);
3251 return XXH32_digest(&state);
3252 # else
3253 if (XXH_FORCE_ALIGN_CHECK) {
3254 if ((((size_t)input) & 3) == 0) { /* Input is 4-bytes aligned, leverage the speed benefit */
3255 return XXH32_endian_align((const xxh_u8 *)input, len, seed, XXH_aligned);
3256 }
3257 }
3258
3259 return XXH32_endian_align((const xxh_u8 *)input, len, seed, XXH_unaligned);
3260 # endif
3261 }
3262
3263 /******* Hash streaming *******/
3264 # ifndef XXH_NO_STREAM
3265 /*! @ingroup XXH32_family */
3266 XXH_PUBLIC_API XXH32_state_t *XXH32_createState(void) {
3267 return (XXH32_state_t *)XXH_malloc(sizeof(XXH32_state_t));
3268 }
3269 /*! @ingroup XXH32_family */
3270 XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t *statePtr) {
3271 XXH_free(statePtr);
3272 return XXH_OK;
3273 }
3274
3275 /*! @ingroup XXH32_family */
3276 XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t *dstState, const XXH32_state_t *srcState) {
3277 XXH_memcpy(dstState, srcState, sizeof(*dstState));
3278 }
3279
3280 /*! @ingroup XXH32_family */
3281 XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t *statePtr, XXH32_hash_t seed) {
3282 XXH_ASSERT(statePtr != NULL);
3283 XXH_memset(statePtr, 0, sizeof(*statePtr));
3284 XXH32_initAccs(statePtr->acc, seed);
3285 return XXH_OK;
3286 }
3287
3288 /*! @ingroup XXH32_family */
3289 XXH_PUBLIC_API XXH_errorcode XXH32_update(XXH32_state_t *state, const void *input, size_t len) {
3290 if (input == NULL) {
3291 XXH_ASSERT(len == 0);
3292 return XXH_OK;
3293 }
3294
3295 state->total_len_32 += (XXH32_hash_t)len;
3296 state->large_len |= (XXH32_hash_t)((len >= 16) | (state->total_len_32 >= 16));
3297
3298 XXH_ASSERT(state->bufferedSize < sizeof(state->buffer));
3299 if (len < sizeof(state->buffer) - state->bufferedSize) { /* fill in tmp buffer */
3300 XXH_memcpy(state->buffer + state->bufferedSize, input, len);
3301 state->bufferedSize += (XXH32_hash_t)len;
3302 return XXH_OK;
3303 }
3304
3305 {
3306 const xxh_u8 *xinput = (const xxh_u8 *)input;
3307 const xxh_u8 *const bEnd = xinput + len;
3308
3309 if (state->bufferedSize) { /* non-empty buffer: complete first */
3310 XXH_memcpy(state->buffer + state->bufferedSize, xinput, sizeof(state->buffer) - state->bufferedSize);
3311 xinput += sizeof(state->buffer) - state->bufferedSize;
3312 /* then process one round */
3313 (void)XXH32_consumeLong(state->acc, state->buffer, sizeof(state->buffer), XXH_aligned);
3314 state->bufferedSize = 0;
3315 }
3316
3317 XXH_ASSERT(xinput <= bEnd);
3318 if ((size_t)(bEnd - xinput) >= sizeof(state->buffer)) {
3319 /* Process the remaining data */
3320 xinput = XXH32_consumeLong(state->acc, xinput, (size_t)(bEnd - xinput), XXH_unaligned);
3321 }
3322
3323 if (xinput < bEnd) {
3324 /* Copy the leftover to the tmp buffer */
3325 XXH_memcpy(state->buffer, xinput, (size_t)(bEnd - xinput));
3326 state->bufferedSize = (unsigned)(bEnd - xinput);
3327 }
3328 }
3329
3330 return XXH_OK;
3331 }
3332
3333 /*! @ingroup XXH32_family */
3334 XXH_PUBLIC_API XXH32_hash_t XXH32_digest(const XXH32_state_t *state) {
3335 xxh_u32 h32;
3336
3337 if (state->large_len) {
3338 h32 = XXH32_mergeAccs(state->acc);
3339 } else {
3340 h32 = state->acc[2] /* == seed */ + XXH_PRIME32_5;
3341 }
3342
3343 h32 += state->total_len_32;
3344
3345 return XXH32_finalize(h32, state->buffer, state->bufferedSize, XXH_aligned);
3346 }
3347 # endif /* !XXH_NO_STREAM */
3348
3349 /******* Canonical representation *******/
3350
3351 /*! @ingroup XXH32_family */
3352 XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t *dst, XXH32_hash_t hash) {
3353 XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t));
3354 if (XXH_CPU_LITTLE_ENDIAN)
3355 hash = XXH_swap32(hash);
3356 XXH_memcpy(dst, &hash, sizeof(*dst));
3357 }
3358 /*! @ingroup XXH32_family */
3359 XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t *src) {
3360 return XXH_readBE32(src);
3361 }
3362
3363 # ifndef XXH_NO_LONG_LONG
3364
3365 /* *******************************************************************
3366 * 64-bit hash functions
3367 *********************************************************************/
3368 /*!
3369 * @}
3370 * @ingroup impl
3371 * @{
3372 */
3373 /******* Memory access *******/
3374
3375 typedef XXH64_hash_t xxh_u64;
3376
3377 # ifdef XXH_OLD_NAMES
3378 # define U64 xxh_u64
3379 # endif
3380
3381 # if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS == 3))
3382 /*
3383 * Manual byteshift. Best for old compilers which don't inline memcpy.
3384 * We actually directly use XXH_readLE64 and XXH_readBE64.
3385 */
3386 # elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS == 2))
3387
3388 /* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */
3389 static xxh_u64 XXH_read64(const void *memPtr) {
3390 return *(const xxh_u64 *)memPtr;
3391 }
3392
3393 # elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS == 1))
3394
3395 /*
3396 * __attribute__((aligned(1))) is supported by gcc and clang. Originally the
3397 * documentation claimed that it only increased the alignment, but actually it
3398 * can decrease it on gcc, clang, and icc:
3399 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69502,
3400 * https://gcc.godbolt.org/z/xYez1j67Y.
3401 */
3402 # ifdef XXH_OLD_NAMES
3403 typedef union {
3404 xxh_u32 u32;
3405 xxh_u64 u64;
3406 } __attribute__((__packed__)) unalign64;
3407 # endif
3408 static xxh_u64 XXH_read64(const void *ptr) {
3409 typedef __attribute__((__aligned__(1))) __attribute__((__may_alias__)) xxh_u64 xxh_unalign64;
3410 return *((const xxh_unalign64 *)ptr);
3411 }
3412
3413 # else
3414
3415 /*
3416 * Portable and safe solution. Generally efficient.
3417 * see: https://fastcompression.blogspot.com/2015/08/accessing-unaligned-memory.html
3418 */
3419 static xxh_u64 XXH_read64(const void *memPtr) {
3420 xxh_u64 val;
3421 XXH_memcpy(&val, memPtr, sizeof(val));
3422 return val;
3423 }
3424
3425 # endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */
3426
3427 # if defined(_MSC_VER) /* Visual Studio */
3428 # define XXH_swap64 _byteswap_uint64
3429 # elif XXH_GCC_VERSION >= 403
3430 # define XXH_swap64 __builtin_bswap64
3431 # else
3432 static xxh_u64 XXH_swap64(xxh_u64 x) {
3433 return ((x << 56) & 0xff00000000000000ULL) | ((x << 40) & 0x00ff000000000000ULL) |
3434 ((x << 24) & 0x0000ff0000000000ULL) | ((x << 8) & 0x000000ff00000000ULL) |
3435 ((x >> 8) & 0x00000000ff000000ULL) | ((x >> 24) & 0x0000000000ff0000ULL) |
3436 ((x >> 40) & 0x000000000000ff00ULL) | ((x >> 56) & 0x00000000000000ffULL);
3437 }
3438 # endif
3439
3440 /* XXH_FORCE_MEMORY_ACCESS==3 is an endian-independent byteshift load. */
3441 # if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS == 3))
3442
3443 XXH_FORCE_INLINE xxh_u64 XXH_readLE64(const void *memPtr) {
3444 const xxh_u8 *bytePtr = (const xxh_u8 *)memPtr;
3445 return bytePtr[0] | ((xxh_u64)bytePtr[1] << 8) | ((xxh_u64)bytePtr[2] << 16) | ((xxh_u64)bytePtr[3] << 24) |
3446 ((xxh_u64)bytePtr[4] << 32) | ((xxh_u64)bytePtr[5] << 40) | ((xxh_u64)bytePtr[6] << 48) |
3447 ((xxh_u64)bytePtr[7] << 56);
3448 }
3449
3450 XXH_FORCE_INLINE xxh_u64 XXH_readBE64(const void *memPtr) {
3451 const xxh_u8 *bytePtr = (const xxh_u8 *)memPtr;
3452 return bytePtr[7] | ((xxh_u64)bytePtr[6] << 8) | ((xxh_u64)bytePtr[5] << 16) | ((xxh_u64)bytePtr[4] << 24) |
3453 ((xxh_u64)bytePtr[3] << 32) | ((xxh_u64)bytePtr[2] << 40) | ((xxh_u64)bytePtr[1] << 48) |
3454 ((xxh_u64)bytePtr[0] << 56);
3455 }
3456
3457 # else
3458 XXH_FORCE_INLINE xxh_u64 XXH_readLE64(const void *ptr) {
3459 return XXH_CPU_LITTLE_ENDIAN ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr));
3460 }
3461
3462 static xxh_u64 XXH_readBE64(const void *ptr) {
3463 return XXH_CPU_LITTLE_ENDIAN ? XXH_swap64(XXH_read64(ptr)) : XXH_read64(ptr);
3464 }
3465 # endif
3466
3467 XXH_FORCE_INLINE xxh_u64 XXH_readLE64_align(const void *ptr, XXH_alignment align) {
3468 if (align == XXH_unaligned)
3469 return XXH_readLE64(ptr);
3470 else
3471 return XXH_CPU_LITTLE_ENDIAN ? *(const xxh_u64 *)ptr : XXH_swap64(*(const xxh_u64 *)ptr);
3472 }
3473
3474 /******* xxh64 *******/
3475 /*!
3476 * @}
3477 * @defgroup XXH64_impl XXH64 implementation
3478 * @ingroup impl
3479 *
3480 * Details on the XXH64 implementation.
3481 * @{
3482 */
3483 /* #define rather that static const, to be used as initializers */
3484 # define XXH_PRIME64_1 \
3485 0x9E3779B185EBCA87ULL /*!< 0b1001111000110111011110011011000110000101111010111100101010000111 */
3486 # define XXH_PRIME64_2 \
3487 0xC2B2AE3D27D4EB4FULL /*!< 0b1100001010110010101011100011110100100111110101001110101101001111 */
3488 # define XXH_PRIME64_3 \
3489 0x165667B19E3779F9ULL /*!< 0b0001011001010110011001111011000110011110001101110111100111111001 */
3490 # define XXH_PRIME64_4 \
3491 0x85EBCA77C2B2AE63ULL /*!< 0b1000010111101011110010100111011111000010101100101010111001100011 */
3492 # define XXH_PRIME64_5 \
3493 0x27D4EB2F165667C5ULL /*!< 0b0010011111010100111010110010111100010110010101100110011111000101 */
3494
3495 # ifdef XXH_OLD_NAMES
3496 # define PRIME64_1 XXH_PRIME64_1
3497 # define PRIME64_2 XXH_PRIME64_2
3498 # define PRIME64_3 XXH_PRIME64_3
3499 # define PRIME64_4 XXH_PRIME64_4
3500 # define PRIME64_5 XXH_PRIME64_5
3501 # endif
3502
3503 /*! @copydoc XXH32_round */
3504 static xxh_u64 XXH64_round(xxh_u64 acc, xxh_u64 input) {
3505 acc += input * XXH_PRIME64_2;
3506 acc = XXH_rotl64(acc, 31);
3507 acc *= XXH_PRIME64_1;
3508 # if (defined(__AVX512F__)) && !defined(XXH_ENABLE_AUTOVECTORIZE)
3509 /*
3510 * DISABLE AUTOVECTORIZATION:
3511 * A compiler fence is used to prevent GCC and Clang from
3512 * autovectorizing the XXH64 loop (pragmas and attributes don't work for some
3513 * reason) without globally disabling AVX512.
3514 *
3515 * Autovectorization of XXH64 tends to be detrimental,
3516 * though the exact outcome may change depending on exact cpu and compiler version.
3517 * For information, it has been reported as detrimental for Skylake-X,
3518 * but possibly beneficial for Zen4.
3519 *
3520 * The default is to disable auto-vectorization,
3521 * but you can select to enable it instead using `XXH_ENABLE_AUTOVECTORIZE` build variable.
3522 */
3523 XXH_COMPILER_GUARD(acc);
3524 # endif
3525 return acc;
3526 }
3527
3528 static xxh_u64 XXH64_mergeRound(xxh_u64 acc, xxh_u64 val) {
3529 val = XXH64_round(0, val);
3530 acc ^= val;
3531 acc = acc * XXH_PRIME64_1 + XXH_PRIME64_4;
3532 return acc;
3533 }
3534
3535 /*! @copydoc XXH32_avalanche */
3536 static xxh_u64 XXH64_avalanche(xxh_u64 hash) {
3537 hash ^= hash >> 33;
3538 hash *= XXH_PRIME64_2;
3539 hash ^= hash >> 29;
3540 hash *= XXH_PRIME64_3;
3541 hash ^= hash >> 32;
3542 return hash;
3543 }
3544
3545 # define XXH_get64bits(p) XXH_readLE64_align(p, align)
3546
3547 /*!
3548 * @internal
3549 * @brief Sets up the initial accumulator state for XXH64().
3550 */
3551 XXH_FORCE_INLINE void XXH64_initAccs(xxh_u64 *acc, xxh_u64 seed) {
3552 XXH_ASSERT(acc != NULL);
3553 acc[0] = seed + XXH_PRIME64_1 + XXH_PRIME64_2;
3554 acc[1] = seed + XXH_PRIME64_2;
3555 acc[2] = seed + 0;
3556 acc[3] = seed - XXH_PRIME64_1;
3557 }
3558
3559 /*!
3560 * @internal
3561 * @brief Consumes a block of data for XXH64().
3562 *
3563 * @return the end input pointer.
3564 */
3565 XXH_FORCE_INLINE const xxh_u8 *XXH64_consumeLong(
3566 xxh_u64 *XXH_RESTRICT acc,
3567 xxh_u8 const *XXH_RESTRICT input,
3568 size_t len,
3569 XXH_alignment align) {
3570 const xxh_u8 *const bEnd = input + len;
3571 const xxh_u8 *const limit = bEnd - 31;
3572 XXH_ASSERT(acc != NULL);
3573 XXH_ASSERT(input != NULL);
3574 XXH_ASSERT(len >= 32);
3575 do {
3576 /* reroll on 32-bit */
3577 if (sizeof(void *) < sizeof(xxh_u64)) {
3578 size_t i;
3579 for (i = 0; i < 4; i++) {
3580 acc[i] = XXH64_round(acc[i], XXH_get64bits(input));
3581 input += 8;
3582 }
3583 } else {
3584 acc[0] = XXH64_round(acc[0], XXH_get64bits(input));
3585 input += 8;
3586 acc[1] = XXH64_round(acc[1], XXH_get64bits(input));
3587 input += 8;
3588 acc[2] = XXH64_round(acc[2], XXH_get64bits(input));
3589 input += 8;
3590 acc[3] = XXH64_round(acc[3], XXH_get64bits(input));
3591 input += 8;
3592 }
3593 } while (input < limit);
3594
3595 return input;
3596 }
3597
3598 /*!
3599 * @internal
3600 * @brief Merges the accumulator lanes together for XXH64()
3601 */
3602 XXH_FORCE_INLINE XXH_PUREF xxh_u64 XXH64_mergeAccs(const xxh_u64 *acc) {
3603 XXH_ASSERT(acc != NULL);
3604 {
3605 xxh_u64 h64 = XXH_rotl64(acc[0], 1) + XXH_rotl64(acc[1], 7) + XXH_rotl64(acc[2], 12) + XXH_rotl64(acc[3], 18);
3606 /* reroll on 32-bit */
3607 if (sizeof(void *) < sizeof(xxh_u64)) {
3608 size_t i;
3609 for (i = 0; i < 4; i++) {
3610 h64 = XXH64_mergeRound(h64, acc[i]);
3611 }
3612 } else {
3613 h64 = XXH64_mergeRound(h64, acc[0]);
3614 h64 = XXH64_mergeRound(h64, acc[1]);
3615 h64 = XXH64_mergeRound(h64, acc[2]);
3616 h64 = XXH64_mergeRound(h64, acc[3]);
3617 }
3618 return h64;
3619 }
3620 }
3621
3622 /*!
3623 * @internal
3624 * @brief Processes the last 0-31 bytes of @p ptr.
3625 *
3626 * There may be up to 31 bytes remaining to consume from the input.
3627 * This final stage will digest them to ensure that all input bytes are present
3628 * in the final mix.
3629 *
3630 * @param hash The hash to finalize.
3631 * @param ptr The pointer to the remaining input.
3632 * @param len The remaining length, modulo 32.
3633 * @param align Whether @p ptr is aligned.
3634 * @return The finalized hash
3635 * @see XXH32_finalize().
3636 */
3637 XXH_STATIC XXH_PUREF xxh_u64 XXH64_finalize(xxh_u64 hash, const xxh_u8 *ptr, size_t len, XXH_alignment align) {
3638 if (ptr == NULL)
3639 XXH_ASSERT(len == 0);
3640 len &= 31;
3641 while (len >= 8) {
3642 xxh_u64 const k1 = XXH64_round(0, XXH_get64bits(ptr));
3643 ptr += 8;
3644 hash ^= k1;
3645 hash = XXH_rotl64(hash, 27) * XXH_PRIME64_1 + XXH_PRIME64_4;
3646 len -= 8;
3647 }
3648 if (len >= 4) {
3649 hash ^= (xxh_u64)(XXH_get32bits(ptr)) * XXH_PRIME64_1;
3650 ptr += 4;
3651 hash = XXH_rotl64(hash, 23) * XXH_PRIME64_2 + XXH_PRIME64_3;
3652 len -= 4;
3653 }
3654 while (len > 0) {
3655 hash ^= (*ptr++) * XXH_PRIME64_5;
3656 hash = XXH_rotl64(hash, 11) * XXH_PRIME64_1;
3657 --len;
3658 }
3659 return XXH64_avalanche(hash);
3660 }
3661
3662 # ifdef XXH_OLD_NAMES
3663 # define PROCESS1_64 XXH_PROCESS1_64
3664 # define PROCESS4_64 XXH_PROCESS4_64
3665 # define PROCESS8_64 XXH_PROCESS8_64
3666 # else
3667 # undef XXH_PROCESS1_64
3668 # undef XXH_PROCESS4_64
3669 # undef XXH_PROCESS8_64
3670 # endif
3671
3672 /*!
3673 * @internal
3674 * @brief The implementation for @ref XXH64().
3675 *
3676 * @param input , len , seed Directly passed from @ref XXH64().
3677 * @param align Whether @p input is aligned.
3678 * @return The calculated hash.
3679 */
3680 XXH_FORCE_INLINE XXH_PUREF xxh_u64
3681 XXH64_endian_align(const xxh_u8 *input, size_t len, xxh_u64 seed, XXH_alignment align) {
3682 xxh_u64 h64;
3683 if (input == NULL)
3684 XXH_ASSERT(len == 0);
3685
3686 if (len >= 32) { /* Process a large block of data */
3687 xxh_u64 acc[4];
3688 XXH64_initAccs(acc, seed);
3689
3690 input = XXH64_consumeLong(acc, input, len, align);
3691
3692 h64 = XXH64_mergeAccs(acc);
3693 } else {
3694 h64 = seed + XXH_PRIME64_5;
3695 }
3696
3697 h64 += (xxh_u64)len;
3698
3699 return XXH64_finalize(h64, input, len, align);
3700 }
3701
3702 /*! @ingroup XXH64_family */
3703 XXH_PUBLIC_API XXH64_hash_t XXH64(XXH_NOESCAPE const void *input, size_t len, XXH64_hash_t seed) {
3704 # if !defined(XXH_NO_STREAM) && XXH_SIZE_OPT >= 2
3705 /* Simple version, good for code maintenance, but unfortunately slow for small inputs */
3706 XXH64_state_t state;
3707 XXH64_reset(&state, seed);
3708 XXH64_update(&state, (const xxh_u8 *)input, len);
3709 return XXH64_digest(&state);
3710 # else
3711 if (XXH_FORCE_ALIGN_CHECK) {
3712 if ((((size_t)input) & 7) == 0) { /* Input is aligned, let's leverage the speed advantage */
3713 return XXH64_endian_align((const xxh_u8 *)input, len, seed, XXH_aligned);
3714 }
3715 }
3716
3717 return XXH64_endian_align((const xxh_u8 *)input, len, seed, XXH_unaligned);
3718
3719 # endif
3720 }
3721
3722 /******* Hash Streaming *******/
3723 # ifndef XXH_NO_STREAM
3724 /*! @ingroup XXH64_family*/
3725 XXH_PUBLIC_API XXH64_state_t *XXH64_createState(void) {
3726 return (XXH64_state_t *)XXH_malloc(sizeof(XXH64_state_t));
3727 }
3728 /*! @ingroup XXH64_family */
3729 XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t *statePtr) {
3730 XXH_free(statePtr);
3731 return XXH_OK;
3732 }
3733
3734 /*! @ingroup XXH64_family */
3735 XXH_PUBLIC_API void XXH64_copyState(XXH_NOESCAPE XXH64_state_t *dstState, const XXH64_state_t *srcState) {
3736 XXH_memcpy(dstState, srcState, sizeof(*dstState));
3737 }
3738
3739 /*! @ingroup XXH64_family */
3740 XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH_NOESCAPE XXH64_state_t *statePtr, XXH64_hash_t seed) {
3741 XXH_ASSERT(statePtr != NULL);
3742 XXH_memset(statePtr, 0, sizeof(*statePtr));
3743 XXH64_initAccs(statePtr->acc, seed);
3744 return XXH_OK;
3745 }
3746
3747 /*! @ingroup XXH64_family */
3748 XXH_PUBLIC_API XXH_errorcode
3749 XXH64_update(XXH_NOESCAPE XXH64_state_t *state, XXH_NOESCAPE const void *input, size_t len) {
3750 if (input == NULL) {
3751 XXH_ASSERT(len == 0);
3752 return XXH_OK;
3753 }
3754
3755 state->total_len += len;
3756
3757 XXH_ASSERT(state->bufferedSize <= sizeof(state->buffer));
3758 if (len < sizeof(state->buffer) - state->bufferedSize) { /* fill in tmp buffer */
3759 XXH_memcpy(state->buffer + state->bufferedSize, input, len);
3760 state->bufferedSize += (XXH32_hash_t)len;
3761 return XXH_OK;
3762 }
3763
3764 {
3765 const xxh_u8 *xinput = (const xxh_u8 *)input;
3766 const xxh_u8 *const bEnd = xinput + len;
3767
3768 if (state->bufferedSize) { /* non-empty buffer => complete first */
3769 XXH_memcpy(state->buffer + state->bufferedSize, xinput, sizeof(state->buffer) - state->bufferedSize);
3770 xinput += sizeof(state->buffer) - state->bufferedSize;
3771 /* and process one round */
3772 (void)XXH64_consumeLong(state->acc, state->buffer, sizeof(state->buffer), XXH_aligned);
3773 state->bufferedSize = 0;
3774 }
3775
3776 XXH_ASSERT(xinput <= bEnd);
3777 if ((size_t)(bEnd - xinput) >= sizeof(state->buffer)) {
3778 /* Process the remaining data */
3779 xinput = XXH64_consumeLong(state->acc, xinput, (size_t)(bEnd - xinput), XXH_unaligned);
3780 }
3781
3782 if (xinput < bEnd) {
3783 /* Copy the leftover to the tmp buffer */
3784 XXH_memcpy(state->buffer, xinput, (size_t)(bEnd - xinput));
3785 state->bufferedSize = (unsigned)(bEnd - xinput);
3786 }
3787 }
3788
3789 return XXH_OK;
3790 }
3791
3792 /*! @ingroup XXH64_family */
3793 XXH_PUBLIC_API XXH64_hash_t XXH64_digest(XXH_NOESCAPE const XXH64_state_t *state) {
3794 xxh_u64 h64;
3795
3796 if (state->total_len >= 32) {
3797 h64 = XXH64_mergeAccs(state->acc);
3798 } else {
3799 h64 = state->acc[2] /*seed*/ + XXH_PRIME64_5;
3800 }
3801
3802 h64 += (xxh_u64)state->total_len;
3803
3804 return XXH64_finalize(h64, state->buffer, (size_t)state->total_len, XXH_aligned);
3805 }
3806 # endif /* !XXH_NO_STREAM */
3807
3808 /******* Canonical representation *******/
3809
3810 /*! @ingroup XXH64_family */
3811 XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH_NOESCAPE XXH64_canonical_t *dst, XXH64_hash_t hash) {
3812 XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t));
3813 if (XXH_CPU_LITTLE_ENDIAN)
3814 hash = XXH_swap64(hash);
3815 XXH_memcpy(dst, &hash, sizeof(*dst));
3816 }
3817
3818 /*! @ingroup XXH64_family */
3819 XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(XXH_NOESCAPE const XXH64_canonical_t *src) {
3820 return XXH_readBE64(src);
3821 }
3822
3823 # ifndef XXH_NO_XXH3
3824
3825 /* *********************************************************************
3826 * XXH3
3827 * New generation hash designed for speed on small keys and vectorization
3828 ************************************************************************ */
3829 /*!
3830 * @}
3831 * @defgroup XXH3_impl XXH3 implementation
3832 * @ingroup impl
3833 * @{
3834 */
3835
3836 /* === Compiler specifics === */
3837
3838 # if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || \
3839 defined(__clang__)
3840 # define XXH_likely(x) __builtin_expect(x, 1)
3841 # define XXH_unlikely(x) __builtin_expect(x, 0)
3842 # else
3843 # define XXH_likely(x) (x)
3844 # define XXH_unlikely(x) (x)
3845 # endif
3846
3847 # ifndef XXH_HAS_INCLUDE
3848 # ifdef __has_include
3849 /*
3850 * Not defined as XXH_HAS_INCLUDE(x) (function-like) because
3851 * this causes segfaults in Apple Clang 4.2 (on Mac OS X 10.7 Lion)
3852 */
3853 # define XXH_HAS_INCLUDE __has_include
3854 # else
3855 # define XXH_HAS_INCLUDE(x) 0
3856 # endif
3857 # endif
3858
3859 # if defined(__GNUC__) || defined(__clang__)
3860 # if defined(__ARM_FEATURE_SVE)
3861 # include <arm_sve.h>
3862 # endif
3863 # if defined(__ARM_NEON__) || defined(__ARM_NEON) || (defined(_M_ARM) && _M_ARM >= 7) || \
3864 defined(_M_ARM64) || defined(_M_ARM64EC) || \
3865 (defined(__wasm_simd128__) && XXH_HAS_INCLUDE(<arm_neon.h>)) /* WASM SIMD128 via SIMDe */
3866 # define inline __inline__ /* circumvent a clang bug */
3867 # include <arm_neon.h>
3868 # undef inline
3869 # elif defined(__AVX2__)
3870 # include <immintrin.h>
3871 # elif defined(__SSE2__)
3872 # include <emmintrin.h>
3873 # elif defined(__loongarch_asx)
3874 # include <lasxintrin.h>
3875 # include <lsxintrin.h>
3876 # elif defined(__loongarch_sx)
3877 # include <lsxintrin.h>
3878 # elif defined(__riscv_vector)
3879 # include <riscv_vector.h>
3880 # endif
3881 # endif
3882
3883 # if defined(_MSC_VER)
3884 # include <intrin.h>
3885 # endif
3886
3887 /*
3888 * One goal of XXH3 is to make it fast on both 32-bit and 64-bit, while
3889 * remaining a true 64-bit/128-bit hash function.
3890 *
3891 * This is done by prioritizing a subset of 64-bit operations that can be
3892 * emulated without too many steps on the average 32-bit machine.
3893 *
3894 * For example, these two lines seem similar, and run equally fast on 64-bit:
3895 *
3896 * xxh_u64 x;
3897 * x ^= (x >> 47); // good
3898 * x ^= (x >> 13); // bad
3899 *
3900 * However, to a 32-bit machine, there is a major difference.
3901 *
3902 * x ^= (x >> 47) looks like this:
3903 *
3904 * x.lo ^= (x.hi >> (47 - 32));
3905 *
3906 * while x ^= (x >> 13) looks like this:
3907 *
3908 * // note: funnel shifts are not usually cheap.
3909 * x.lo ^= (x.lo >> 13) | (x.hi << (32 - 13));
3910 * x.hi ^= (x.hi >> 13);
3911 *
3912 * The first one is significantly faster than the second, simply because the
3913 * shift is larger than 32. This means:
3914 * - All the bits we need are in the upper 32 bits, so we can ignore the lower
3915 * 32 bits in the shift.
3916 * - The shift result will always fit in the lower 32 bits, and therefore,
3917 * we can ignore the upper 32 bits in the xor.
3918 *
3919 * Thanks to this optimization, XXH3 only requires these features to be efficient:
3920 *
3921 * - Usable unaligned access
3922 * - A 32-bit or 64-bit ALU
3923 * - If 32-bit, a decent ADC instruction
3924 * - A 32 or 64-bit multiply with a 64-bit result
3925 * - For the 128-bit variant, a decent byteswap helps short inputs.
3926 *
3927 * The first two are already required by XXH32, and almost all 32-bit and 64-bit
3928 * platforms which can run XXH32 can run XXH3 efficiently.
3929 *
3930 * Thumb-1, the classic 16-bit only subset of ARM's instruction set, is one
3931 * notable exception.
3932 *
3933 * First of all, Thumb-1 lacks support for the UMULL instruction which
3934 * performs the important long multiply. This means numerous __aeabi_lmul
3935 * calls.
3936 *
3937 * Second of all, the 8 functional registers are just not enough.
3938 * Setup for __aeabi_lmul, byteshift loads, pointers, and all arithmetic need
3939 * Lo registers, and this shuffling results in thousands more MOVs than A32.
3940 *
3941 * A32 and T32 don't have this limitation. They can access all 14 registers,
3942 * do a 32->64 multiply with UMULL, and the flexible operand allowing free
3943 * shifts is helpful, too.
3944 *
3945 * Therefore, we do a quick sanity check.
3946 *
3947 * If compiling Thumb-1 for a target which supports ARM instructions, we will
3948 * emit a warning, as it is not a "sane" platform to compile for.
3949 *
3950 * Usually, if this happens, it is because of an accident and you probably need
3951 * to specify -march, as you likely meant to compile for a newer architecture.
3952 *
3953 * Credit: large sections of the vectorial and asm source code paths
3954 * have been contributed by @easyaspi314
3955 */
3956 # if defined(__thumb__) && !defined(__thumb2__) && defined(__ARM_ARCH_ISA_ARM)
3957 # warning "XXH3 is highly inefficient without ARM or Thumb-2."
3958 # endif
3959
3960 /* ==========================================
3961 * Vectorization detection
3962 * ========================================== */
3963
3964 # ifdef XXH_DOXYGEN
3965 /*!
3966 * @ingroup tuning
3967 * @brief Overrides the vectorization implementation chosen for XXH3.
3968 *
3969 * Can be defined to 0 to disable SIMD,
3970 * or any other authorized value of @ref XXH_VECTOR.
3971 *
3972 * If this is not defined, it uses predefined macros to determine the best
3973 * implementation.
3974 */
3975 # define XXH_VECTOR XXH_SCALAR
3976 /*!
3977 * @ingroup tuning
3978 * @brief Selects the minimum alignment for XXH3's accumulators.
3979 *
3980 * When using SIMD, this should match the alignment required for said vector
3981 * type, so, for example, 32 for AVX2.
3982 *
3983 * Default: Auto detected.
3984 */
3985 # define XXH_ACC_ALIGN 8
3986 # endif
3987
3988 /* Actual definition */
3989 # ifndef XXH_DOXYGEN
3990 # endif
3991
3992 # ifndef XXH_VECTOR /* can be defined on command line */
3993 # if ( \
3994 defined(__ARM_NEON__) || defined(__ARM_NEON) /* gcc */ \
3995 || defined(_M_ARM) || defined(_M_ARM64) || defined(_M_ARM64EC) /* msvc */ \
3996 || (defined(__wasm_simd128__) && XXH_HAS_INCLUDE(<arm_neon.h>)) /* wasm simd128 via SIMDe */ \
3997 ) && \
3998 (defined(_WIN32) || defined(__LITTLE_ENDIAN__) /* little endian only */ \
3999 || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__))
4000 # define XXH_VECTOR XXH_NEON
4001 # elif defined(__ARM_FEATURE_SVE)
4002 # define XXH_VECTOR XXH_SVE
4003 # elif defined(__AVX512F__)
4004 # define XXH_VECTOR XXH_AVX512
4005 # elif defined(__AVX2__)
4006 # define XXH_VECTOR XXH_AVX2
4007 # elif defined(__SSE2__) || defined(_M_X64) || (defined(_M_IX86_FP) && (_M_IX86_FP == 2))
4008 # define XXH_VECTOR XXH_SSE2
4009 # elif (defined(__PPC64__) && defined(__POWER8_VECTOR__)) || \
4010 (defined(__s390x__) && defined(__VEC__)) && defined(__GNUC__) /* TODO: IBM XL */
4011 # define XXH_VECTOR XXH_VSX
4012 # elif defined(__loongarch_asx)
4013 # define XXH_VECTOR XXH_LASX
4014 # elif defined(__loongarch_sx)
4015 # define XXH_VECTOR XXH_LSX
4016 # elif defined(__riscv_vector)
4017 # define XXH_VECTOR XXH_RVV
4018 # else
4019 # define XXH_VECTOR XXH_SCALAR
4020 # endif
4021 # endif
4022
4023 /* __ARM_FEATURE_SVE is only supported by GCC & Clang. */
4024 # if (XXH_VECTOR == XXH_SVE) && !defined(__ARM_FEATURE_SVE)
4025 # ifdef _MSC_VER
4026 # pragma warning(once : 4606)
4027 # else
4028 # warning "__ARM_FEATURE_SVE isn't supported. Use SCALAR instead."
4029 # endif
4030 # undef XXH_VECTOR
4031 # define XXH_VECTOR XXH_SCALAR
4032 # endif
4033
4034 /*
4035 * Controls the alignment of the accumulator,
4036 * for compatibility with aligned vector loads, which are usually faster.
4037 */
4038 # ifndef XXH_ACC_ALIGN
4039 # if defined(XXH_X86DISPATCH)
4040 # define XXH_ACC_ALIGN 64 /* for compatibility with avx512 */
4041 # elif XXH_VECTOR == XXH_SCALAR /* scalar */
4042 # define XXH_ACC_ALIGN 8
4043 # elif XXH_VECTOR == XXH_SSE2 /* sse2 */
4044 # define XXH_ACC_ALIGN 16
4045 # elif XXH_VECTOR == XXH_AVX2 /* avx2 */
4046 # define XXH_ACC_ALIGN 32
4047 # elif XXH_VECTOR == XXH_NEON /* neon */
4048 # define XXH_ACC_ALIGN 16
4049 # elif XXH_VECTOR == XXH_VSX /* vsx */
4050 # define XXH_ACC_ALIGN 16
4051 # elif XXH_VECTOR == XXH_AVX512 /* avx512 */
4052 # define XXH_ACC_ALIGN 64
4053 # elif XXH_VECTOR == XXH_SVE /* sve */
4054 # define XXH_ACC_ALIGN 64
4055 # elif XXH_VECTOR == XXH_LASX /* lasx */
4056 # define XXH_ACC_ALIGN 64
4057 # elif XXH_VECTOR == XXH_LSX /* lsx */
4058 # define XXH_ACC_ALIGN 64
4059 # elif XXH_VECTOR == XXH_RVV /* rvv */
4060 # define XXH_ACC_ALIGN 64 /* could be 8, but 64 may be faster */
4061 # endif
4062 # endif
4063
4064 # if defined(XXH_X86DISPATCH) || XXH_VECTOR == XXH_SSE2 || XXH_VECTOR == XXH_AVX2 || XXH_VECTOR == XXH_AVX512
4065 # define XXH_SEC_ALIGN XXH_ACC_ALIGN
4066 # elif XXH_VECTOR == XXH_SVE
4067 # define XXH_SEC_ALIGN XXH_ACC_ALIGN
4068 # elif XXH_VECTOR == XXH_RVV
4069 # define XXH_SEC_ALIGN XXH_ACC_ALIGN
4070 # else
4071 # define XXH_SEC_ALIGN 8
4072 # endif
4073
4074 # if defined(__GNUC__) || defined(__clang__)
4075 # define XXH_ALIASING __attribute__((__may_alias__))
4076 # else
4077 # define XXH_ALIASING /* nothing */
4078 # endif
4079
4080 /*
4081 * UGLY HACK:
4082 * GCC usually generates the best code with -O3 for xxHash.
4083 *
4084 * However, when targeting AVX2, it is overzealous in its unrolling resulting
4085 * in code roughly 3/4 the speed of Clang.
4086 *
4087 * There are other issues, such as GCC splitting _mm256_loadu_si256 into
4088 * _mm_loadu_si128 + _mm256_inserti128_si256. This is an optimization which
4089 * only applies to Sandy and Ivy Bridge... which don't even support AVX2.
4090 *
4091 * That is why when compiling the AVX2 version, it is recommended to use either
4092 * -O2 -mavx2 -march=haswell
4093 * or
4094 * -O2 -mavx2 -mno-avx256-split-unaligned-load
4095 * for decent performance, or to use Clang instead.
4096 *
4097 * Fortunately, we can control the first one with a pragma that forces GCC into
4098 * -O2, but the other one we can't control without "failed to inline always
4099 * inline function due to target mismatch" warnings.
4100 */
4101 # if XXH_VECTOR == XXH_AVX2 /* AVX2 */ \
4102 && defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \
4103 && defined(__OPTIMIZE__) && XXH_SIZE_OPT <= 0 /* respect -O0 and -Os */
4104 # pragma GCC push_options
4105 # pragma GCC optimize("-O2")
4106 # endif
4107
4108 # if XXH_VECTOR == XXH_NEON
4109
4110 /*
4111 * UGLY HACK: While AArch64 GCC on Linux does not seem to care, on macOS, GCC -O3
4112 * optimizes out the entire hashLong loop because of the aliasing violation.
4113 *
4114 * However, GCC is also inefficient at load-store optimization with vld1q/vst1q,
4115 * so the only option is to mark it as aliasing.
4116 */
4117 typedef uint64x2_t xxh_aliasing_uint64x2_t XXH_ALIASING;
4118
4119 /*!
4120 * @internal
4121 * @brief `vld1q_u64` but faster and alignment-safe.
4122 *
4123 * On AArch64, unaligned access is always safe, but on ARMv7-a, it is only
4124 * *conditionally* safe (`vld1` has an alignment bit like `movdq[ua]` in x86).
4125 *
4126 * GCC for AArch64 sees `vld1q_u8` as an intrinsic instead of a load, so it
4127 * prohibits load-store optimizations. Therefore, a direct dereference is used.
4128 *
4129 * Otherwise, `vld1q_u8` is used with `vreinterpretq_u8_u64` to do a safe
4130 * unaligned load.
4131 */
4132 # if defined(__aarch64__) && defined(__GNUC__) && !defined(__clang__)
4133 XXH_FORCE_INLINE uint64x2_t XXH_vld1q_u64(void const *ptr) /* silence -Wcast-align */
4134 {
4135 return *(xxh_aliasing_uint64x2_t const *)ptr;
4136 }
4137 # else
4138 XXH_FORCE_INLINE uint64x2_t XXH_vld1q_u64(void const *ptr) {
4139 return vreinterpretq_u64_u8(vld1q_u8((uint8_t const *)ptr));
4140 }
4141 # endif
4142
4143 /*!
4144 * @internal
4145 * @brief `vmlal_u32` on low and high halves of a vector.
4146 *
4147 * This is a workaround for AArch64 GCC < 11 which implemented arm_neon.h with
4148 * inline assembly and were therefore incapable of merging the `vget_{low, high}_u32`
4149 * with `vmlal_u32`.
4150 */
4151 # if defined(__aarch64__) && defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 11
4152 XXH_FORCE_INLINE uint64x2_t XXH_vmlal_low_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs) {
4153 /* Inline assembly is the only way */
4154 __asm__("umlal %0.2d, %1.2s, %2.2s" : "+w"(acc) : "w"(lhs), "w"(rhs));
4155 return acc;
4156 }
4157 XXH_FORCE_INLINE uint64x2_t XXH_vmlal_high_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs) {
4158 /* This intrinsic works as expected */
4159 return vmlal_high_u32(acc, lhs, rhs);
4160 }
4161 # else
4162 /* Portable intrinsic versions */
4163 XXH_FORCE_INLINE uint64x2_t XXH_vmlal_low_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs) {
4164 return vmlal_u32(acc, vget_low_u32(lhs), vget_low_u32(rhs));
4165 }
4166 /*! @copydoc XXH_vmlal_low_u32
4167 * Assume the compiler converts this to vmlal_high_u32 on aarch64 */
4168 XXH_FORCE_INLINE uint64x2_t XXH_vmlal_high_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs) {
4169 return vmlal_u32(acc, vget_high_u32(lhs), vget_high_u32(rhs));
4170 }
4171 # endif
4172
4173 /*!
4174 * @ingroup tuning
4175 * @brief Controls the NEON to scalar ratio for XXH3
4176 *
4177 * This can be set to 2, 4, 6, or 8.
4178 *
4179 * ARM Cortex CPUs are _very_ sensitive to how their pipelines are used.
4180 *
4181 * For example, the Cortex-A73 can dispatch 3 micro-ops per cycle, but only 2 of those
4182 * can be NEON. If you are only using NEON instructions, you are only using 2/3 of the CPU
4183 * bandwidth.
4184 *
4185 * This is even more noticeable on the more advanced cores like the Cortex-A76 which
4186 * can dispatch 8 micro-ops per cycle, but still only 2 NEON micro-ops at once.
4187 *
4188 * Therefore, to make the most out of the pipeline, it is beneficial to run 6 NEON lanes
4189 * and 2 scalar lanes, which is chosen by default.
4190 *
4191 * This does not apply to Apple processors or 32-bit processors, which run better with
4192 * full NEON. These will default to 8. Additionally, size-optimized builds run 8 lanes.
4193 *
4194 * This change benefits CPUs with large micro-op buffers without negatively affecting
4195 * most other CPUs:
4196 *
4197 * | Chipset | Dispatch type | NEON only | 6:2 hybrid | Diff. |
4198 * |:----------------------|:--------------------|----------:|-----------:|------:|
4199 * | Snapdragon 730 (A76) | 2 NEON/8 micro-ops | 8.8 GB/s | 10.1 GB/s | ~16% |
4200 * | Snapdragon 835 (A73) | 2 NEON/3 micro-ops | 5.1 GB/s | 5.3 GB/s | ~5% |
4201 * | Marvell PXA1928 (A53) | In-order dual-issue | 1.9 GB/s | 1.9 GB/s | 0% |
4202 * | Apple M1 | 4 NEON/8 micro-ops | 37.3 GB/s | 36.1 GB/s | ~-3% |
4203 *
4204 * It also seems to fix some bad codegen on GCC, making it almost as fast as clang.
4205 *
4206 * When using WASM SIMD128, if this is 2 or 6, SIMDe will scalarize 2 of the lanes meaning
4207 * it effectively becomes worse 4.
4208 *
4209 * @see XXH3_accumulate_512_neon()
4210 */
4211 # ifndef XXH3_NEON_LANES
4212 # if (defined(__aarch64__) || defined(__arm64__) || defined(_M_ARM64) || defined(_M_ARM64EC)) && \
4213 !defined(__APPLE__) && XXH_SIZE_OPT <= 0
4214 # define XXH3_NEON_LANES 6
4215 # else
4216 # define XXH3_NEON_LANES XXH_ACC_NB
4217 # endif
4218 # endif
4219 # endif /* XXH_VECTOR == XXH_NEON */
4220
4221 /*
4222 * VSX and Z Vector helpers.
4223 *
4224 * This is very messy, and any pull requests to clean this up are welcome.
4225 *
4226 * There are a lot of problems with supporting VSX and s390x, due to
4227 * inconsistent intrinsics, spotty coverage, and multiple endiannesses.
4228 */
4229 # if XXH_VECTOR == XXH_VSX
4230 /* Annoyingly, these headers _may_ define three macros: `bool`, `vector`,
4231 * and `pixel`. This is a problem for obvious reasons.
4232 *
4233 * These keywords are unnecessary; the spec literally says they are
4234 * equivalent to `__bool`, `__vector`, and `__pixel` and may be undef'd
4235 * after including the header.
4236 *
4237 * We use pragma push_macro/pop_macro to keep the namespace clean. */
4238 # pragma push_macro("bool")
4239 # pragma push_macro("vector")
4240 # pragma push_macro("pixel")
4241 /* silence potential macro redefined warnings */
4242 # undef bool
4243 # undef vector
4244 # undef pixel
4245
4246 # if defined(__s390x__)
4247 # include <s390intrin.h>
4248 # else
4249 # include <altivec.h>
4250 # endif
4251
4252 /* Restore the original macro values, if applicable. */
4253 # pragma pop_macro("pixel")
4254 # pragma pop_macro("vector")
4255 # pragma pop_macro("bool")
4256
4257 typedef __vector unsigned long long xxh_u64x2;
4258 typedef __vector unsigned char xxh_u8x16;
4259 typedef __vector unsigned xxh_u32x4;
4260
4261 /*
4262 * UGLY HACK: Similar to aarch64 macOS GCC, s390x GCC has the same aliasing issue.
4263 */
4264 typedef xxh_u64x2 xxh_aliasing_u64x2 XXH_ALIASING;
4265
4266 # ifndef XXH_VSX_BE
4267 # if defined(__BIG_ENDIAN__) || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
4268 # define XXH_VSX_BE 1
4269 # elif defined(__VEC_ELEMENT_REG_ORDER__) && __VEC_ELEMENT_REG_ORDER__ == __ORDER_BIG_ENDIAN__
4270 # warning "-maltivec=be is not recommended. Please use native endianness."
4271 # define XXH_VSX_BE 1
4272 # else
4273 # define XXH_VSX_BE 0
4274 # endif
4275 # endif /* !defined(XXH_VSX_BE) */
4276
4277 # if XXH_VSX_BE
4278 # if defined(__POWER9_VECTOR__) || (defined(__clang__) && defined(__s390x__))
4279 # define XXH_vec_revb vec_revb
4280 # else
4281 /*!
4282 * A polyfill for POWER9's vec_revb().
4283 */
4284 XXH_FORCE_INLINE xxh_u64x2 XXH_vec_revb(xxh_u64x2 val) {
4285 xxh_u8x16 const vByteSwap = {
4286 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08};
4287 return vec_perm(val, val, vByteSwap);
4288 }
4289 # endif
4290 # endif /* XXH_VSX_BE */
4291
4292 /*!
4293 * Performs an unaligned vector load and byte swaps it on big endian.
4294 */
4295 XXH_FORCE_INLINE xxh_u64x2 XXH_vec_loadu(const void *ptr) {
4296 xxh_u64x2 ret;
4297 XXH_memcpy(&ret, ptr, sizeof(xxh_u64x2));
4298 # if XXH_VSX_BE
4299 ret = XXH_vec_revb(ret);
4300 # endif
4301 return ret;
4302 }
4303
4304 /*
4305 * vec_mulo and vec_mule are very problematic intrinsics on PowerPC
4306 *
4307 * These intrinsics weren't added until GCC 8, despite existing for a while,
4308 * and they are endian dependent. Also, their meaning swap depending on version.
4309 * */
4310 # if defined(__s390x__)
4311 /* s390x is always big endian, no issue on this platform */
4312 # define XXH_vec_mulo vec_mulo
4313 # define XXH_vec_mule vec_mule
4314 # elif defined(__clang__) && XXH_HAS_BUILTIN(__builtin_altivec_vmuleuw) && !defined(__ibmxl__)
4315 /* Clang has a better way to control this, we can just use the builtin which doesn't swap. */
4316 /* The IBM XL Compiler (which defined __clang__) only implements the vec_* operations */
4317 # define XXH_vec_mulo __builtin_altivec_vmulouw
4318 # define XXH_vec_mule __builtin_altivec_vmuleuw
4319 # else
4320 /* gcc needs inline assembly */
4321 /* Adapted from https://github.com/google/highwayhash/blob/master/highwayhash/hh_vsx.h. */
4322 XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mulo(xxh_u32x4 a, xxh_u32x4 b) {
4323 xxh_u64x2 result;
4324 __asm__("vmulouw %0, %1, %2" : "=v"(result) : "v"(a), "v"(b));
4325 return result;
4326 }
4327 XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mule(xxh_u32x4 a, xxh_u32x4 b) {
4328 xxh_u64x2 result;
4329 __asm__("vmuleuw %0, %1, %2" : "=v"(result) : "v"(a), "v"(b));
4330 return result;
4331 }
4332 # endif /* XXH_vec_mulo, XXH_vec_mule */
4333 # endif /* XXH_VECTOR == XXH_VSX */
4334
4335 # if XXH_VECTOR == XXH_SVE
4336 # define ACCRND(acc, offset) \
4337 do { \
4338 svuint64_t input_vec = svld1_u64(mask, xinput + offset); \
4339 svuint64_t secret_vec = svld1_u64(mask, xsecret + offset); \
4340 svuint64_t mixed = sveor_u64_x(mask, secret_vec, input_vec); \
4341 svuint64_t swapped = svtbl_u64(input_vec, kSwap); \
4342 svuint64_t mixed_lo = svextw_u64_x(mask, mixed); \
4343 svuint64_t mixed_hi = svlsr_n_u64_x(mask, mixed, 32); \
4344 svuint64_t mul = svmad_u64_x(mask, mixed_lo, mixed_hi, swapped); \
4345 acc = svadd_u64_x(mask, acc, mul); \
4346 } while (0)
4347 # endif /* XXH_VECTOR == XXH_SVE */
4348
4349 /* prefetch
4350 * can be disabled, by declaring XXH_NO_PREFETCH build macro */
4351 # if defined(XXH_NO_PREFETCH)
4352 # define XXH_PREFETCH(ptr) (void)(ptr) /* disabled */
4353 # else
4354 # if XXH_SIZE_OPT >= 1
4355 # define XXH_PREFETCH(ptr) (void)(ptr)
4356 # elif defined(_MSC_VER) && \
4357 (defined(_M_X64) || defined(_M_IX86)) /* _mm_prefetch() not defined outside of x86/x64 */
4358 # include <mmintrin.h> /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */
4359 # define XXH_PREFETCH(ptr) _mm_prefetch((const char *)(ptr), _MM_HINT_T0)
4360 # elif defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
4361 # define XXH_PREFETCH(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 3 /* locality */)
4362 # else
4363 # define XXH_PREFETCH(ptr) (void)(ptr) /* disabled */
4364 # endif
4365 # endif /* XXH_NO_PREFETCH */
4366
4367 /* ==========================================
4368 * XXH3 default settings
4369 * ========================================== */
4370
4371 # define XXH_SECRET_DEFAULT_SIZE 192 /* minimum XXH3_SECRET_SIZE_MIN */
4372
4373 # if (XXH_SECRET_DEFAULT_SIZE < XXH3_SECRET_SIZE_MIN)
4374 # error "default keyset is not large enough"
4375 # endif
4376
4377 /*!
4378 * @internal
4379 * @def XXH3_kSecret
4380 * @brief Pseudorandom secret taken directly from FARSH. */
4381 XXH_ALIGN(64)
4382 static const xxh_u8 XXH3_kSecret[XXH_SECRET_DEFAULT_SIZE] = {
4383 0xb8, 0xfe, 0x6c, 0x39, 0x23, 0xa4, 0x4b, 0xbe, 0x7c, 0x01, 0x81, 0x2c, 0xf7, 0x21, 0xad, 0x1c, 0xde, 0xd4,
4384 0x6d, 0xe9, 0x83, 0x90, 0x97, 0xdb, 0x72, 0x40, 0xa4, 0xa4, 0xb7, 0xb3, 0x67, 0x1f, 0xcb, 0x79, 0xe6, 0x4e,
4385 0xcc, 0xc0, 0xe5, 0x78, 0x82, 0x5a, 0xd0, 0x7d, 0xcc, 0xff, 0x72, 0x21, 0xb8, 0x08, 0x46, 0x74, 0xf7, 0x43,
4386 0x24, 0x8e, 0xe0, 0x35, 0x90, 0xe6, 0x81, 0x3a, 0x26, 0x4c, 0x3c, 0x28, 0x52, 0xbb, 0x91, 0xc3, 0x00, 0xcb,
4387 0x88, 0xd0, 0x65, 0x8b, 0x1b, 0x53, 0x2e, 0xa3, 0x71, 0x64, 0x48, 0x97, 0xa2, 0x0d, 0xf9, 0x4e, 0x38, 0x19,
4388 0xef, 0x46, 0xa9, 0xde, 0xac, 0xd8, 0xa8, 0xfa, 0x76, 0x3f, 0xe3, 0x9c, 0x34, 0x3f, 0xf9, 0xdc, 0xbb, 0xc7,
4389 0xc7, 0x0b, 0x4f, 0x1d, 0x8a, 0x51, 0xe0, 0x4b, 0xcd, 0xb4, 0x59, 0x31, 0xc8, 0x9f, 0x7e, 0xc9, 0xd9, 0x78,
4390 0x73, 0x64, 0xea, 0xc5, 0xac, 0x83, 0x34, 0xd3, 0xeb, 0xc3, 0xc5, 0x81, 0xa0, 0xff, 0xfa, 0x13, 0x63, 0xeb,
4391 0x17, 0x0d, 0xdd, 0x51, 0xb7, 0xf0, 0xda, 0x49, 0xd3, 0x16, 0x55, 0x26, 0x29, 0xd4, 0x68, 0x9e, 0x2b, 0x16,
4392 0xbe, 0x58, 0x7d, 0x47, 0xa1, 0xfc, 0x8f, 0xf8, 0xb8, 0xd1, 0x7a, 0xd0, 0x31, 0xce, 0x45, 0xcb, 0x3a, 0x8f,
4393 0x95, 0x16, 0x04, 0x28, 0xaf, 0xd7, 0xfb, 0xca, 0xbb, 0x4b, 0x40, 0x7e,
4394 };
4395
4396 static const xxh_u64 PRIME_MX1 =
4397 0x165667919E3779F9ULL; /*!< 0b0001011001010110011001111001000110011110001101110111100111111001 */
4398 static const xxh_u64 PRIME_MX2 =
4399 0x9FB21C651E98DF25ULL; /*!< 0b1001111110110010000111000110010100011110100110001101111100100101 */
4400
4401 # ifdef XXH_OLD_NAMES
4402 # define kSecret XXH3_kSecret
4403 # endif
4404
4405 # ifdef XXH_DOXYGEN
4406 /*!
4407 * @brief Calculates a 32-bit to 64-bit long multiply.
4408 *
4409 * Implemented as a macro.
4410 *
4411 * Wraps `__emulu` on MSVC x86 because it tends to call `__allmul` when it doesn't
4412 * need to (but it shouldn't need to anyways, it is about 7 instructions to do
4413 * a 64x64 multiply...). Since we know that this will _always_ emit `MULL`, we
4414 * use that instead of the normal method.
4415 *
4416 * If you are compiling for platforms like Thumb-1 and don't have a better option,
4417 * you may also want to write your own long multiply routine here.
4418 *
4419 * @param x, y Numbers to be multiplied
4420 * @return 64-bit product of the low 32 bits of @p x and @p y.
4421 */
4422 XXH_FORCE_INLINE xxh_u64 XXH_mult32to64(xxh_u64 x, xxh_u64 y) {
4423 return (x & 0xFFFFFFFF) * (y & 0xFFFFFFFF);
4424 }
4425 # elif defined(_MSC_VER) && defined(_M_IX86)
4426 # define XXH_mult32to64(x, y) __emulu((unsigned)(x), (unsigned)(y))
4427 # else
4428 /*
4429 * Downcast + upcast is usually better than masking on older compilers like
4430 * GCC 4.2 (especially 32-bit ones), all without affecting newer compilers.
4431 *
4432 * The other method, (x & 0xFFFFFFFF) * (y & 0xFFFFFFFF), will AND both operands
4433 * and perform a full 64x64 multiply -- entirely redundant on 32-bit.
4434 */
4435 # define XXH_mult32to64(x, y) ((xxh_u64)(xxh_u32)(x) * (xxh_u64)(xxh_u32)(y))
4436 # endif
4437
4438 /*!
4439 * @brief Calculates a 64->128-bit long multiply.
4440 *
4441 * Uses `__uint128_t` and `_umul128` if available, otherwise uses a scalar
4442 * version.
4443 *
4444 * @param lhs , rhs The 64-bit integers to be multiplied
4445 * @return The 128-bit result represented in an @ref XXH128_hash_t.
4446 */
4447 static XXH128_hash_t XXH_mult64to128(xxh_u64 lhs, xxh_u64 rhs) {
4448 /*
4449 * GCC/Clang __uint128_t method.
4450 *
4451 * On most 64-bit targets, GCC and Clang define a __uint128_t type.
4452 * This is usually the best way as it usually uses a native long 64-bit
4453 * multiply, such as MULQ on x86_64 or MUL + UMULH on aarch64.
4454 *
4455 * Usually.
4456 *
4457 * Despite being a 32-bit platform, Clang (and emscripten) define this type
4458 * despite not having the arithmetic for it. This results in a laggy
4459 * compiler builtin call which calculates a full 128-bit multiply.
4460 * In that case it is best to use the portable one.
4461 * https://github.com/Cyan4973/xxHash/issues/211#issuecomment-515575677
4462 */
4463 # if (defined(__GNUC__) || defined(__clang__)) && !defined(__wasm__) && defined(__SIZEOF_INT128__) || \
4464 (defined(_INTEGRAL_MAX_BITS) && _INTEGRAL_MAX_BITS >= 128)
4465
4466 __uint128_t const product = (__uint128_t)lhs * (__uint128_t)rhs;
4467 XXH128_hash_t r128;
4468 r128.low64 = (xxh_u64)(product);
4469 r128.high64 = (xxh_u64)(product >> 64);
4470 return r128;
4471
4472 /*
4473 * MSVC for x64's _umul128 method.
4474 *
4475 * xxh_u64 _umul128(xxh_u64 Multiplier, xxh_u64 Multiplicand, xxh_u64 *HighProduct);
4476 *
4477 * This compiles to single operand MUL on x64.
4478 */
4479 # elif (defined(_M_X64) || defined(_M_IA64)) && !defined(_M_ARM64EC)
4480
4481 # ifndef _MSC_VER
4482 # pragma intrinsic(_umul128)
4483 # endif
4484 xxh_u64 product_high;
4485 xxh_u64 const product_low = _umul128(lhs, rhs, &product_high);
4486 XXH128_hash_t r128;
4487 r128.low64 = product_low;
4488 r128.high64 = product_high;
4489 return r128;
4490
4491 /*
4492 * MSVC for ARM64's __umulh method.
4493 *
4494 * This compiles to the same MUL + UMULH as GCC/Clang's __uint128_t method.
4495 */
4496 # elif defined(_M_ARM64) || defined(_M_ARM64EC)
4497
4498 # ifndef _MSC_VER
4499 # pragma intrinsic(__umulh)
4500 # endif
4501 XXH128_hash_t r128;
4502 r128.low64 = lhs * rhs;
4503 r128.high64 = __umulh(lhs, rhs);
4504 return r128;
4505
4506 # else
4507 /*
4508 * Portable scalar method. Optimized for 32-bit and 64-bit ALUs.
4509 *
4510 * This is a fast and simple grade school multiply, which is shown below
4511 * with base 10 arithmetic instead of base 0x100000000.
4512 *
4513 * 9 3 // D2 lhs = 93
4514 * x 7 5 // D2 rhs = 75
4515 * ----------
4516 * 1 5 // D2 lo_lo = (93 % 10) * (75 % 10) = 15
4517 * 4 5 | // D2 hi_lo = (93 / 10) * (75 % 10) = 45
4518 * 2 1 | // D2 lo_hi = (93 % 10) * (75 / 10) = 21
4519 * + 6 3 | | // D2 hi_hi = (93 / 10) * (75 / 10) = 63
4520 * ---------
4521 * 2 7 | // D2 cross = (15 / 10) + (45 % 10) + 21 = 27
4522 * + 6 7 | | // D2 upper = (27 / 10) + (45 / 10) + 63 = 67
4523 * ---------
4524 * 6 9 7 5 // D4 res = (27 * 10) + (15 % 10) + (67 * 100) = 6975
4525 *
4526 * The reasons for adding the products like this are:
4527 * 1. It avoids manual carry tracking. Just like how
4528 * (9 * 9) + 9 + 9 = 99, the same applies with this for UINT64_MAX.
4529 * This avoids a lot of complexity.
4530 *
4531 * 2. It hints for, and on Clang, compiles to, the powerful UMAAL
4532 * instruction available in ARM's Digital Signal Processing extension
4533 * in 32-bit ARMv6 and later, which is shown below:
4534 *
4535 * void UMAAL(xxh_u32 *RdLo, xxh_u32 *RdHi, xxh_u32 Rn, xxh_u32 Rm)
4536 * {
4537 * xxh_u64 product = (xxh_u64)*RdLo * (xxh_u64)*RdHi + Rn + Rm;
4538 * *RdLo = (xxh_u32)(product & 0xFFFFFFFF);
4539 * *RdHi = (xxh_u32)(product >> 32);
4540 * }
4541 *
4542 * This instruction was designed for efficient long multiplication, and
4543 * allows this to be calculated in only 4 instructions at speeds
4544 * comparable to some 64-bit ALUs.
4545 *
4546 * 3. It isn't terrible on other platforms. Usually this will be a couple
4547 * of 32-bit ADD/ADCs.
4548 */
4549
4550 /* First calculate all of the cross products. */
4551 xxh_u64 const lo_lo = XXH_mult32to64(lhs & 0xFFFFFFFF, rhs & 0xFFFFFFFF);
4552 xxh_u64 const hi_lo = XXH_mult32to64(lhs >> 32, rhs & 0xFFFFFFFF);
4553 xxh_u64 const lo_hi = XXH_mult32to64(lhs & 0xFFFFFFFF, rhs >> 32);
4554 xxh_u64 const hi_hi = XXH_mult32to64(lhs >> 32, rhs >> 32);
4555
4556 /* Now add the products together. These will never overflow. */
4557 xxh_u64 const cross = (lo_lo >> 32) + (hi_lo & 0xFFFFFFFF) + lo_hi;
4558 xxh_u64 const upper = (hi_lo >> 32) + (cross >> 32) + hi_hi;
4559 xxh_u64 const lower = (cross << 32) | (lo_lo & 0xFFFFFFFF);
4560
4561 XXH128_hash_t r128;
4562 r128.low64 = lower;
4563 r128.high64 = upper;
4564 return r128;
4565 # endif
4566 }
4567
4568 /*!
4569 * @brief Calculates a 64-bit to 128-bit multiply, then XOR folds it.
4570 *
4571 * The reason for the separate function is to prevent passing too many structs
4572 * around by value. This will hopefully inline the multiply, but we don't force it.
4573 *
4574 * @param lhs , rhs The 64-bit integers to multiply
4575 * @return The low 64 bits of the product XOR'd by the high 64 bits.
4576 * @see XXH_mult64to128()
4577 */
4578 static xxh_u64 XXH3_mul128_fold64(xxh_u64 lhs, xxh_u64 rhs) {
4579 XXH128_hash_t product = XXH_mult64to128(lhs, rhs);
4580 return product.low64 ^ product.high64;
4581 }
4582
4583 /*! Seems to produce slightly better code on GCC for some reason. */
4584 XXH_FORCE_INLINE XXH_CONSTF xxh_u64 XXH_xorshift64(xxh_u64 v64, int shift) {
4585 XXH_ASSERT(0 <= shift && shift < 64);
4586 return v64 ^ (v64 >> shift);
4587 }
4588
4589 /*
4590 * This is a fast avalanche stage,
4591 * suitable when input bits are already partially mixed
4592 */
4593 static XXH64_hash_t XXH3_avalanche(xxh_u64 h64) {
4594 h64 = XXH_xorshift64(h64, 37);
4595 h64 *= PRIME_MX1;
4596 h64 = XXH_xorshift64(h64, 32);
4597 return h64;
4598 }
4599
4600 /*
4601 * This is a stronger avalanche,
4602 * inspired by Pelle Evensen's rrmxmx
4603 * preferable when input has not been previously mixed
4604 */
4605 static XXH64_hash_t XXH3_rrmxmx(xxh_u64 h64, xxh_u64 len) {
4606 /* this mix is inspired by Pelle Evensen's rrmxmx */
4607 h64 ^= XXH_rotl64(h64, 49) ^ XXH_rotl64(h64, 24);
4608 h64 *= PRIME_MX2;
4609 h64 ^= (h64 >> 35) + len;
4610 h64 *= PRIME_MX2;
4611 return XXH_xorshift64(h64, 28);
4612 }
4613
4614 /* ==========================================
4615 * Short keys
4616 * ==========================================
4617 * One of the shortcomings of XXH32 and XXH64 was that their performance was
4618 * sub-optimal on short lengths. It used an iterative algorithm which strongly
4619 * favored lengths that were a multiple of 4 or 8.
4620 *
4621 * Instead of iterating over individual inputs, we use a set of single shot
4622 * functions which piece together a range of lengths and operate in constant time.
4623 *
4624 * Additionally, the number of multiplies has been significantly reduced. This
4625 * reduces latency, especially when emulating 64-bit multiplies on 32-bit.
4626 *
4627 * Depending on the platform, this may or may not be faster than XXH32, but it
4628 * is almost guaranteed to be faster than XXH64.
4629 */
4630
4631 /*
4632 * At very short lengths, there isn't enough input to fully hide secrets, or use
4633 * the entire secret.
4634 *
4635 * There is also only a limited amount of mixing we can do before significantly
4636 * impacting performance.
4637 *
4638 * Therefore, we use different sections of the secret and always mix two secret
4639 * samples with an XOR. This should have no effect on performance on the
4640 * seedless or withSeed variants because everything _should_ be constant folded
4641 * by modern compilers.
4642 *
4643 * The XOR mixing hides individual parts of the secret and increases entropy.
4644 *
4645 * This adds an extra layer of strength for custom secrets.
4646 */
4647 XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t
4648 XXH3_len_1to3_64b(const xxh_u8 *input, size_t len, const xxh_u8 *secret, XXH64_hash_t seed) {
4649 XXH_ASSERT(input != NULL);
4650 XXH_ASSERT(1 <= len && len <= 3);
4651 XXH_ASSERT(secret != NULL);
4652 /*
4653 * len = 1: combined = { input[0], 0x01, input[0], input[0] }
4654 * len = 2: combined = { input[1], 0x02, input[0], input[1] }
4655 * len = 3: combined = { input[2], 0x03, input[0], input[1] }
4656 */
4657 {
4658 xxh_u8 const c1 = input[0];
4659 xxh_u8 const c2 = input[len >> 1];
4660 xxh_u8 const c3 = input[len - 1];
4661 xxh_u32 const combined = ((xxh_u32)c1 << 16) | ((xxh_u32)c2 << 24) | ((xxh_u32)c3 << 0) | ((xxh_u32)len << 8);
4662 xxh_u64 const bitflip = (XXH_readLE32(secret) ^ XXH_readLE32(secret + 4)) + seed;
4663 xxh_u64 const keyed = (xxh_u64)combined ^ bitflip;
4664 return XXH64_avalanche(keyed);
4665 }
4666 }
4667
4668 XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t
4669 XXH3_len_4to8_64b(const xxh_u8 *input, size_t len, const xxh_u8 *secret, XXH64_hash_t seed) {
4670 XXH_ASSERT(input != NULL);
4671 XXH_ASSERT(secret != NULL);
4672 XXH_ASSERT(4 <= len && len <= 8);
4673 seed ^= (xxh_u64)XXH_swap32((xxh_u32)seed) << 32;
4674 {
4675 xxh_u32 const input1 = XXH_readLE32(input);
4676 xxh_u32 const input2 = XXH_readLE32(input + len - 4);
4677 xxh_u64 const bitflip = (XXH_readLE64(secret + 8) ^ XXH_readLE64(secret + 16)) - seed;
4678 xxh_u64 const input64 = input2 + (((xxh_u64)input1) << 32);
4679 xxh_u64 const keyed = input64 ^ bitflip;
4680 return XXH3_rrmxmx(keyed, len);
4681 }
4682 }
4683
4684 XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t
4685 XXH3_len_9to16_64b(const xxh_u8 *input, size_t len, const xxh_u8 *secret, XXH64_hash_t seed) {
4686 XXH_ASSERT(input != NULL);
4687 XXH_ASSERT(secret != NULL);
4688 XXH_ASSERT(9 <= len && len <= 16);
4689 {
4690 xxh_u64 const bitflip1 = (XXH_readLE64(secret + 24) ^ XXH_readLE64(secret + 32)) + seed;
4691 xxh_u64 const bitflip2 = (XXH_readLE64(secret + 40) ^ XXH_readLE64(secret + 48)) - seed;
4692 xxh_u64 const input_lo = XXH_readLE64(input) ^ bitflip1;
4693 xxh_u64 const input_hi = XXH_readLE64(input + len - 8) ^ bitflip2;
4694 xxh_u64 const acc = len + XXH_swap64(input_lo) + input_hi + XXH3_mul128_fold64(input_lo, input_hi);
4695 return XXH3_avalanche(acc);
4696 }
4697 }
4698
4699 XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t
4700 XXH3_len_0to16_64b(const xxh_u8 *input, size_t len, const xxh_u8 *secret, XXH64_hash_t seed) {
4701 XXH_ASSERT(len <= 16);
4702 {
4703 if (XXH_likely(len > 8))
4704 return XXH3_len_9to16_64b(input, len, secret, seed);
4705 if (XXH_likely(len >= 4))
4706 return XXH3_len_4to8_64b(input, len, secret, seed);
4707 if (len)
4708 return XXH3_len_1to3_64b(input, len, secret, seed);
4709 return XXH64_avalanche(seed ^ (XXH_readLE64(secret + 56) ^ XXH_readLE64(secret + 64)));
4710 }
4711 }
4712
4713 /*
4714 * DISCLAIMER: There are known *seed-dependent* multicollisions here due to
4715 * multiplication by zero, affecting hashes of lengths 17 to 240.
4716 *
4717 * However, they are very unlikely.
4718 *
4719 * Keep this in mind when using the unseeded XXH3_64bits() variant: As with all
4720 * unseeded non-cryptographic hashes, it does not attempt to defend itself
4721 * against specially crafted inputs, only random inputs.
4722 *
4723 * Compared to classic UMAC where a 1 in 2^31 chance of 4 consecutive bytes
4724 * cancelling out the secret is taken an arbitrary number of times (addressed
4725 * in XXH3_accumulate_512), this collision is very unlikely with random inputs
4726 * and/or proper seeding:
4727 *
4728 * This only has a 1 in 2^63 chance of 8 consecutive bytes cancelling out, in a
4729 * function that is only called up to 16 times per hash with up to 240 bytes of
4730 * input.
4731 *
4732 * This is not too bad for a non-cryptographic hash function, especially with
4733 * only 64 bit outputs.
4734 *
4735 * The 128-bit variant (which trades some speed for strength) is NOT affected
4736 * by this, although it is always a good idea to use a proper seed if you care
4737 * about strength.
4738 */
4739 XXH_FORCE_INLINE xxh_u64
4740 XXH3_mix16B(const xxh_u8 *XXH_RESTRICT input, const xxh_u8 *XXH_RESTRICT secret, xxh_u64 seed64) {
4741 # if defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \
4742 && defined(__i386__) && defined(__SSE2__) /* x86 + SSE2 */ \
4743 && !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable like XXH32 hack */
4744 /*
4745 * UGLY HACK:
4746 * GCC for x86 tends to autovectorize the 128-bit multiply, resulting in
4747 * slower code.
4748 *
4749 * By forcing seed64 into a register, we disrupt the cost model and
4750 * cause it to scalarize. See `XXH32_round()`
4751 *
4752 * FIXME: Clang's output is still _much_ faster -- On an AMD Ryzen 3600,
4753 * XXH3_64bits @ len=240 runs at 4.6 GB/s with Clang 9, but 3.3 GB/s on
4754 * GCC 9.2, despite both emitting scalar code.
4755 *
4756 * GCC generates much better scalar code than Clang for the rest of XXH3,
4757 * which is why finding a more optimal codepath is an interest.
4758 */
4759 XXH_COMPILER_GUARD(seed64);
4760 # endif
4761 {
4762 xxh_u64 const input_lo = XXH_readLE64(input);
4763 xxh_u64 const input_hi = XXH_readLE64(input + 8);
4764 return XXH3_mul128_fold64(
4765 input_lo ^ (XXH_readLE64(secret) + seed64), input_hi ^ (XXH_readLE64(secret + 8) - seed64));
4766 }
4767 }
4768
4769 /* For mid range keys, XXH3 uses a Mum-hash variant. */
4770 XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t XXH3_len_17to128_64b(
4771 const xxh_u8 *XXH_RESTRICT input,
4772 size_t len,
4773 const xxh_u8 *XXH_RESTRICT secret,
4774 size_t secretSize,
4775 XXH64_hash_t seed) {
4776 XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
4777 (void)secretSize;
4778 XXH_ASSERT(16 < len && len <= 128);
4779
4780 {
4781 xxh_u64 acc = len * XXH_PRIME64_1;
4782 # if XXH_SIZE_OPT >= 1
4783 /* Smaller and cleaner, but slightly slower. */
4784 unsigned int i = (unsigned int)(len - 1) / 32;
4785 do {
4786 acc += XXH3_mix16B(input + 16 * i, secret + 32 * i, seed);
4787 acc += XXH3_mix16B(input + len - 16 * (i + 1), secret + 32 * i + 16, seed);
4788 } while (i-- != 0);
4789 # else
4790 if (len > 32) {
4791 if (len > 64) {
4792 if (len > 96) {
4793 acc += XXH3_mix16B(input + 48, secret + 96, seed);
4794 acc += XXH3_mix16B(input + len - 64, secret + 112, seed);
4795 }
4796 acc += XXH3_mix16B(input + 32, secret + 64, seed);
4797 acc += XXH3_mix16B(input + len - 48, secret + 80, seed);
4798 }
4799 acc += XXH3_mix16B(input + 16, secret + 32, seed);
4800 acc += XXH3_mix16B(input + len - 32, secret + 48, seed);
4801 }
4802 acc += XXH3_mix16B(input + 0, secret + 0, seed);
4803 acc += XXH3_mix16B(input + len - 16, secret + 16, seed);
4804 # endif
4805 return XXH3_avalanche(acc);
4806 }
4807 }
4808
4809 XXH_NO_INLINE XXH_PUREF XXH64_hash_t XXH3_len_129to240_64b(
4810 const xxh_u8 *XXH_RESTRICT input,
4811 size_t len,
4812 const xxh_u8 *XXH_RESTRICT secret,
4813 size_t secretSize,
4814 XXH64_hash_t seed) {
4815 XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
4816 (void)secretSize;
4817 XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX);
4818
4819 # define XXH3_MIDSIZE_STARTOFFSET 3
4820 # define XXH3_MIDSIZE_LASTOFFSET 17
4821
4822 {
4823 xxh_u64 acc = len * XXH_PRIME64_1;
4824 xxh_u64 acc_end;
4825 unsigned int const nbRounds = (unsigned int)len / 16;
4826 unsigned int i;
4827 XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX);
4828 for (i = 0; i < 8; i++) {
4829 acc += XXH3_mix16B(input + (16 * i), secret + (16 * i), seed);
4830 }
4831 /* last bytes */
4832 acc_end = XXH3_mix16B(input + len - 16, secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET, seed);
4833 XXH_ASSERT(nbRounds >= 8);
4834 acc = XXH3_avalanche(acc);
4835 # if defined(__clang__) /* Clang */ \
4836 && (defined(__ARM_NEON) || defined(__ARM_NEON__)) /* NEON */ \
4837 && !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable */
4838 /*
4839 * UGLY HACK:
4840 * Clang for ARMv7-A tries to vectorize this loop, similar to GCC x86.
4841 * In everywhere else, it uses scalar code.
4842 *
4843 * For 64->128-bit multiplies, even if the NEON was 100% optimal, it
4844 * would still be slower than UMAAL (see XXH_mult64to128).
4845 *
4846 * Unfortunately, Clang doesn't handle the long multiplies properly and
4847 * converts them to the nonexistent "vmulq_u64" intrinsic, which is then
4848 * scalarized into an ugly mess of VMOV.32 instructions.
4849 *
4850 * This mess is difficult to avoid without turning autovectorization
4851 * off completely, but they are usually relatively minor and/or not
4852 * worth it to fix.
4853 *
4854 * This loop is the easiest to fix, as unlike XXH32, this pragma
4855 * _actually works_ because it is a loop vectorization instead of an
4856 * SLP vectorization.
4857 */
4858 # pragma clang loop vectorize(disable)
4859 # endif
4860 for (i = 8; i < nbRounds; i++) {
4861 /*
4862 * Prevents clang for unrolling the acc loop and interleaving with this one.
4863 */
4864 XXH_COMPILER_GUARD(acc);
4865 acc_end += XXH3_mix16B(input + (16 * i), secret + (16 * (i - 8)) + XXH3_MIDSIZE_STARTOFFSET, seed);
4866 }
4867 return XXH3_avalanche(acc + acc_end);
4868 }
4869 }
4870
4871 /* ======= Long Keys ======= */
4872
4873 # define XXH_STRIPE_LEN 64
4874 # define XXH_SECRET_CONSUME_RATE 8 /* nb of secret bytes consumed at each accumulation */
4875 # define XXH_ACC_NB (XXH_STRIPE_LEN / sizeof(xxh_u64))
4876
4877 # ifdef XXH_OLD_NAMES
4878 # define STRIPE_LEN XXH_STRIPE_LEN
4879 # define ACC_NB XXH_ACC_NB
4880 # endif
4881
4882 # ifndef XXH_PREFETCH_DIST
4883 # ifdef __clang__
4884 # define XXH_PREFETCH_DIST 320
4885 # else
4886 # if (XXH_VECTOR == XXH_AVX512)
4887 # define XXH_PREFETCH_DIST 512
4888 # else
4889 # define XXH_PREFETCH_DIST 384
4890 # endif
4891 # endif /* __clang__ */
4892 # endif /* XXH_PREFETCH_DIST */
4893
4894 /*
4895 * These macros are to generate an XXH3_accumulate() function.
4896 * The two arguments select the name suffix and target attribute.
4897 *
4898 * The name of this symbol is XXH3_accumulate_<name>() and it calls
4899 * XXH3_accumulate_512_<name>().
4900 *
4901 * It may be useful to hand implement this function if the compiler fails to
4902 * optimize the inline function.
4903 */
4904 # define XXH3_ACCUMULATE_TEMPLATE(name) \
4905 void XXH3_accumulate_##name( \
4906 xxh_u64 *XXH_RESTRICT acc, \
4907 const xxh_u8 *XXH_RESTRICT input, \
4908 const xxh_u8 *XXH_RESTRICT secret, \
4909 size_t nbStripes) { \
4910 size_t n; \
4911 for (n = 0; n < nbStripes; n++) { \
4912 const xxh_u8 *const in = input + n * XXH_STRIPE_LEN; \
4913 XXH_PREFETCH(in + XXH_PREFETCH_DIST); \
4914 XXH3_accumulate_512_##name(acc, in, secret + n * XXH_SECRET_CONSUME_RATE); \
4915 } \
4916 }
4917
4918 XXH_FORCE_INLINE void XXH_writeLE64(void *dst, xxh_u64 v64) {
4919 if (!XXH_CPU_LITTLE_ENDIAN)
4920 v64 = XXH_swap64(v64);
4921 XXH_memcpy(dst, &v64, sizeof(v64));
4922 }
4923
4924 /* Several intrinsic functions below are supposed to accept __int64 as argument,
4925 * as documented in https://software.intel.com/sites/landingpage/IntrinsicsGuide/ .
4926 * However, several environments do not define __int64 type,
4927 * requiring a workaround.
4928 */
4929 # if !defined(__VMS) && \
4930 (defined(__cplusplus) || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */))
4931 typedef int64_t xxh_i64;
4932 # else
4933 /* the following type must have a width of 64-bit */
4934 typedef long long xxh_i64;
4935 # endif
4936
4937 /*
4938 * XXH3_accumulate_512 is the tightest loop for long inputs, and it is the most optimized.
4939 *
4940 * It is a hardened version of UMAC, based off of FARSH's implementation.
4941 *
4942 * This was chosen because it adapts quite well to 32-bit, 64-bit, and SIMD
4943 * implementations, and it is ridiculously fast.
4944 *
4945 * We harden it by mixing the original input to the accumulators as well as the product.
4946 *
4947 * This means that in the (relatively likely) case of a multiply by zero, the
4948 * original input is preserved.
4949 *
4950 * On 128-bit inputs, we swap 64-bit pairs when we add the input to improve
4951 * cross-pollination, as otherwise the upper and lower halves would be
4952 * essentially independent.
4953 *
4954 * This doesn't matter on 64-bit hashes since they all get merged together in
4955 * the end, so we skip the extra step.
4956 *
4957 * Both XXH3_64bits and XXH3_128bits use this subroutine.
4958 */
4959
4960 # if (XXH_VECTOR == XXH_AVX512) || (defined(XXH_DISPATCH_AVX512) && XXH_DISPATCH_AVX512 != 0)
4961
4962 # ifndef XXH_TARGET_AVX512
4963 # define XXH_TARGET_AVX512 /* disable attribute target */
4964 # endif
4965
4966 XXH_FORCE_INLINE XXH_TARGET_AVX512 void XXH3_accumulate_512_avx512(
4967 void *XXH_RESTRICT acc,
4968 const void *XXH_RESTRICT input,
4969 const void *XXH_RESTRICT secret) {
4970 __m512i *const xacc = (__m512i *)acc;
4971 XXH_ASSERT((((size_t)acc) & 63) == 0);
4972 XXH_STATIC_ASSERT(XXH_STRIPE_LEN == sizeof(__m512i));
4973
4974 {
4975 /* data_vec = input[0]; */
4976 __m512i const data_vec = _mm512_loadu_si512(input);
4977 /* key_vec = secret[0]; */
4978 __m512i const key_vec = _mm512_loadu_si512(secret);
4979 /* data_key = data_vec ^ key_vec; */
4980 __m512i const data_key = _mm512_xor_si512(data_vec, key_vec);
4981 /* data_key_lo = data_key >> 32; */
4982 __m512i const data_key_lo = _mm512_srli_epi64(data_key, 32);
4983 /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */
4984 __m512i const product = _mm512_mul_epu32(data_key, data_key_lo);
4985 /* xacc[0] += swap(data_vec); */
4986 __m512i const data_swap = _mm512_shuffle_epi32(data_vec, (_MM_PERM_ENUM)_MM_SHUFFLE(1, 0, 3, 2));
4987 __m512i const sum = _mm512_add_epi64(*xacc, data_swap);
4988 /* xacc[0] += product; */
4989 *xacc = _mm512_add_epi64(product, sum);
4990 }
4991 }
4992 XXH_FORCE_INLINE XXH_TARGET_AVX512 XXH3_ACCUMULATE_TEMPLATE(avx512)
4993
4994 /*
4995 * XXH3_scrambleAcc: Scrambles the accumulators to improve mixing.
4996 *
4997 * Multiplication isn't perfect, as explained by Google in HighwayHash:
4998 *
4999 * // Multiplication mixes/scrambles bytes 0-7 of the 64-bit result to
5000 * // varying degrees. In descending order of goodness, bytes
5001 * // 3 4 2 5 1 6 0 7 have quality 228 224 164 160 100 96 36 32.
5002 * // As expected, the upper and lower bytes are much worse.
5003 *
5004 * Source: https://github.com/google/highwayhash/blob/0aaf66b/highwayhash/hh_avx2.h#L291
5005 *
5006 * Since our algorithm uses a pseudorandom secret to add some variance into the
5007 * mix, we don't need to (or want to) mix as often or as much as HighwayHash does.
5008 *
5009 * This isn't as tight as XXH3_accumulate, but still written in SIMD to avoid
5010 * extraction.
5011 *
5012 * Both XXH3_64bits and XXH3_128bits use this subroutine.
5013 */
5014
5015 XXH_FORCE_INLINE XXH_TARGET_AVX512
5016 void XXH3_scrambleAcc_avx512(void *XXH_RESTRICT acc, const void *XXH_RESTRICT secret) {
5017 XXH_ASSERT((((size_t)acc) & 63) == 0);
5018 XXH_STATIC_ASSERT(XXH_STRIPE_LEN == sizeof(__m512i));
5019 {
5020 __m512i *const xacc = (__m512i *)acc;
5021 const __m512i prime32 = _mm512_set1_epi32((int)XXH_PRIME32_1);
5022
5023 /* xacc[0] ^= (xacc[0] >> 47) */
5024 __m512i const acc_vec = *xacc;
5025 __m512i const shifted = _mm512_srli_epi64(acc_vec, 47);
5026 /* xacc[0] ^= secret; */
5027 __m512i const key_vec = _mm512_loadu_si512(secret);
5028 __m512i const data_key =
5029 _mm512_ternarylogic_epi32(key_vec, acc_vec, shifted, 0x96 /* key_vec ^ acc_vec ^ shifted */);
5030
5031 /* xacc[0] *= XXH_PRIME32_1; */
5032 __m512i const data_key_hi = _mm512_srli_epi64(data_key, 32);
5033 __m512i const prod_lo = _mm512_mul_epu32(data_key, prime32);
5034 __m512i const prod_hi = _mm512_mul_epu32(data_key_hi, prime32);
5035 *xacc = _mm512_add_epi64(prod_lo, _mm512_slli_epi64(prod_hi, 32));
5036 }
5037 }
5038
5039 XXH_FORCE_INLINE XXH_TARGET_AVX512 void XXH3_initCustomSecret_avx512(void *XXH_RESTRICT customSecret, xxh_u64 seed64) {
5040 XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 63) == 0);
5041 XXH_STATIC_ASSERT(XXH_SEC_ALIGN == 64);
5042 XXH_ASSERT(((size_t)customSecret & 63) == 0);
5043 (void)(&XXH_writeLE64);
5044 {
5045 int const nbRounds = XXH_SECRET_DEFAULT_SIZE / sizeof(__m512i);
5046 __m512i const seed_pos = _mm512_set1_epi64((xxh_i64)seed64);
5047 __m512i const seed = _mm512_mask_sub_epi64(seed_pos, 0xAA, _mm512_set1_epi8(0), seed_pos);
5048
5049 const __m512i *const src = (const __m512i *)((const void *)XXH3_kSecret);
5050 __m512i *const dest = (__m512i *)customSecret;
5051 int i;
5052 XXH_ASSERT(((size_t)src & 63) == 0); /* control alignment */
5053 XXH_ASSERT(((size_t)dest & 63) == 0);
5054 for (i = 0; i < nbRounds; ++i) {
5055 dest[i] = _mm512_add_epi64(_mm512_load_si512(src + i), seed);
5056 }
5057 }
5058 }
5059
5060 # endif
5061
5062 # if (XXH_VECTOR == XXH_AVX2) || (defined(XXH_DISPATCH_AVX2) && XXH_DISPATCH_AVX2 != 0)
5063
5064 # ifndef XXH_TARGET_AVX2
5065 # define XXH_TARGET_AVX2 /* disable attribute target */
5066 # endif
5067
5068 XXH_FORCE_INLINE XXH_TARGET_AVX2 void XXH3_accumulate_512_avx2(
5069 void *XXH_RESTRICT acc,
5070 const void *XXH_RESTRICT input,
5071 const void *XXH_RESTRICT secret) {
5072 XXH_ASSERT((((size_t)acc) & 31) == 0);
5073 {
5074 __m256i *const xacc = (__m256i *)acc;
5075 /* Unaligned. This is mainly for pointer arithmetic, and because
5076 * _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */
5077 const __m256i *const xinput = (const __m256i *)input;
5078 /* Unaligned. This is mainly for pointer arithmetic, and because
5079 * _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */
5080 const __m256i *const xsecret = (const __m256i *)secret;
5081
5082 size_t i;
5083 for (i = 0; i < XXH_STRIPE_LEN / sizeof(__m256i); i++) {
5084 /* data_vec = xinput[i]; */
5085 __m256i const data_vec = _mm256_loadu_si256(xinput + i);
5086 /* key_vec = xsecret[i]; */
5087 __m256i const key_vec = _mm256_loadu_si256(xsecret + i);
5088 /* data_key = data_vec ^ key_vec; */
5089 __m256i const data_key = _mm256_xor_si256(data_vec, key_vec);
5090 /* data_key_lo = data_key >> 32; */
5091 __m256i const data_key_lo = _mm256_srli_epi64(data_key, 32);
5092 /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */
5093 __m256i const product = _mm256_mul_epu32(data_key, data_key_lo);
5094 /* xacc[i] += swap(data_vec); */
5095 __m256i const data_swap = _mm256_shuffle_epi32(data_vec, _MM_SHUFFLE(1, 0, 3, 2));
5096 __m256i const sum = _mm256_add_epi64(xacc[i], data_swap);
5097 /* xacc[i] += product; */
5098 xacc[i] = _mm256_add_epi64(product, sum);
5099 }
5100 }
5101 }
5102 XXH_FORCE_INLINE XXH_TARGET_AVX2 XXH3_ACCUMULATE_TEMPLATE(avx2)
5103
5104 XXH_FORCE_INLINE XXH_TARGET_AVX2
5105 void XXH3_scrambleAcc_avx2(void *XXH_RESTRICT acc, const void *XXH_RESTRICT secret) {
5106 XXH_ASSERT((((size_t)acc) & 31) == 0);
5107 {
5108 __m256i *const xacc = (__m256i *)acc;
5109 /* Unaligned. This is mainly for pointer arithmetic, and because
5110 * _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */
5111 const __m256i *const xsecret = (const __m256i *)secret;
5112 const __m256i prime32 = _mm256_set1_epi32((int)XXH_PRIME32_1);
5113
5114 size_t i;
5115 for (i = 0; i < XXH_STRIPE_LEN / sizeof(__m256i); i++) {
5116 /* xacc[i] ^= (xacc[i] >> 47) */
5117 __m256i const acc_vec = xacc[i];
5118 __m256i const shifted = _mm256_srli_epi64(acc_vec, 47);
5119 __m256i const data_vec = _mm256_xor_si256(acc_vec, shifted);
5120 /* xacc[i] ^= xsecret; */
5121 __m256i const key_vec = _mm256_loadu_si256(xsecret + i);
5122 __m256i const data_key = _mm256_xor_si256(data_vec, key_vec);
5123
5124 /* xacc[i] *= XXH_PRIME32_1; */
5125 __m256i const data_key_hi = _mm256_srli_epi64(data_key, 32);
5126 __m256i const prod_lo = _mm256_mul_epu32(data_key, prime32);
5127 __m256i const prod_hi = _mm256_mul_epu32(data_key_hi, prime32);
5128 xacc[i] = _mm256_add_epi64(prod_lo, _mm256_slli_epi64(prod_hi, 32));
5129 }
5130 }
5131 }
5132
5133 XXH_FORCE_INLINE XXH_TARGET_AVX2 void XXH3_initCustomSecret_avx2(void *XXH_RESTRICT customSecret, xxh_u64 seed64) {
5134 XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 31) == 0);
5135 XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE / sizeof(__m256i)) == 6);
5136 XXH_STATIC_ASSERT(XXH_SEC_ALIGN <= 64);
5137 (void)(&XXH_writeLE64);
5138 XXH_PREFETCH(customSecret);
5139 {
5140 __m256i const seed =
5141 _mm256_set_epi64x((xxh_i64)(0U - seed64), (xxh_i64)seed64, (xxh_i64)(0U - seed64), (xxh_i64)seed64);
5142
5143 const __m256i *const src = (const __m256i *)((const void *)XXH3_kSecret);
5144 __m256i *dest = (__m256i *)customSecret;
5145
5146 # if defined(__GNUC__) || defined(__clang__)
5147 /*
5148 * On GCC & Clang, marking 'dest' as modified will cause the compiler:
5149 * - do not extract the secret from sse registers in the internal loop
5150 * - use less common registers, and avoid pushing these reg into stack
5151 */
5152 XXH_COMPILER_GUARD(dest);
5153 # endif
5154 XXH_ASSERT(((size_t)src & 31) == 0); /* control alignment */
5155 XXH_ASSERT(((size_t)dest & 31) == 0);
5156
5157 /* GCC -O2 need unroll loop manually */
5158 dest[0] = _mm256_add_epi64(_mm256_load_si256(src + 0), seed);
5159 dest[1] = _mm256_add_epi64(_mm256_load_si256(src + 1), seed);
5160 dest[2] = _mm256_add_epi64(_mm256_load_si256(src + 2), seed);
5161 dest[3] = _mm256_add_epi64(_mm256_load_si256(src + 3), seed);
5162 dest[4] = _mm256_add_epi64(_mm256_load_si256(src + 4), seed);
5163 dest[5] = _mm256_add_epi64(_mm256_load_si256(src + 5), seed);
5164 }
5165 }
5166
5167 # endif
5168
5169 /* x86dispatch always generates SSE2 */
5170 # if (XXH_VECTOR == XXH_SSE2) || defined(XXH_X86DISPATCH)
5171
5172 # ifndef XXH_TARGET_SSE2
5173 # define XXH_TARGET_SSE2 /* disable attribute target */
5174 # endif
5175
5176 XXH_FORCE_INLINE XXH_TARGET_SSE2 void XXH3_accumulate_512_sse2(
5177 void *XXH_RESTRICT acc,
5178 const void *XXH_RESTRICT input,
5179 const void *XXH_RESTRICT secret) {
5180 /* SSE2 is just a half-scale version of the AVX2 version. */
5181 XXH_ASSERT((((size_t)acc) & 15) == 0);
5182 {
5183 __m128i *const xacc = (__m128i *)acc;
5184 /* Unaligned. This is mainly for pointer arithmetic, and because
5185 * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */
5186 const __m128i *const xinput = (const __m128i *)input;
5187 /* Unaligned. This is mainly for pointer arithmetic, and because
5188 * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */
5189 const __m128i *const xsecret = (const __m128i *)secret;
5190
5191 size_t i;
5192 for (i = 0; i < XXH_STRIPE_LEN / sizeof(__m128i); i++) {
5193 /* data_vec = xinput[i]; */
5194 __m128i const data_vec = _mm_loadu_si128(xinput + i);
5195 /* key_vec = xsecret[i]; */
5196 __m128i const key_vec = _mm_loadu_si128(xsecret + i);
5197 /* data_key = data_vec ^ key_vec; */
5198 __m128i const data_key = _mm_xor_si128(data_vec, key_vec);
5199 /* data_key_lo = data_key >> 32; */
5200 __m128i const data_key_lo = _mm_shuffle_epi32(data_key, _MM_SHUFFLE(0, 3, 0, 1));
5201 /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */
5202 __m128i const product = _mm_mul_epu32(data_key, data_key_lo);
5203 /* xacc[i] += swap(data_vec); */
5204 __m128i const data_swap = _mm_shuffle_epi32(data_vec, _MM_SHUFFLE(1, 0, 3, 2));
5205 __m128i const sum = _mm_add_epi64(xacc[i], data_swap);
5206 /* xacc[i] += product; */
5207 xacc[i] = _mm_add_epi64(product, sum);
5208 }
5209 }
5210 }
5211 XXH_FORCE_INLINE XXH_TARGET_SSE2 XXH3_ACCUMULATE_TEMPLATE(sse2)
5212
5213 XXH_FORCE_INLINE XXH_TARGET_SSE2
5214 void XXH3_scrambleAcc_sse2(void *XXH_RESTRICT acc, const void *XXH_RESTRICT secret) {
5215 XXH_ASSERT((((size_t)acc) & 15) == 0);
5216 {
5217 __m128i *const xacc = (__m128i *)acc;
5218 /* Unaligned. This is mainly for pointer arithmetic, and because
5219 * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */
5220 const __m128i *const xsecret = (const __m128i *)secret;
5221 const __m128i prime32 = _mm_set1_epi32((int)XXH_PRIME32_1);
5222
5223 size_t i;
5224 for (i = 0; i < XXH_STRIPE_LEN / sizeof(__m128i); i++) {
5225 /* xacc[i] ^= (xacc[i] >> 47) */
5226 __m128i const acc_vec = xacc[i];
5227 __m128i const shifted = _mm_srli_epi64(acc_vec, 47);
5228 __m128i const data_vec = _mm_xor_si128(acc_vec, shifted);
5229 /* xacc[i] ^= xsecret[i]; */
5230 __m128i const key_vec = _mm_loadu_si128(xsecret + i);
5231 __m128i const data_key = _mm_xor_si128(data_vec, key_vec);
5232
5233 /* xacc[i] *= XXH_PRIME32_1; */
5234 __m128i const data_key_hi = _mm_shuffle_epi32(data_key, _MM_SHUFFLE(0, 3, 0, 1));
5235 __m128i const prod_lo = _mm_mul_epu32(data_key, prime32);
5236 __m128i const prod_hi = _mm_mul_epu32(data_key_hi, prime32);
5237 xacc[i] = _mm_add_epi64(prod_lo, _mm_slli_epi64(prod_hi, 32));
5238 }
5239 }
5240 }
5241
5242 XXH_FORCE_INLINE XXH_TARGET_SSE2 void XXH3_initCustomSecret_sse2(void *XXH_RESTRICT customSecret, xxh_u64 seed64) {
5243 XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 15) == 0);
5244 (void)(&XXH_writeLE64);
5245 {
5246 int const nbRounds = XXH_SECRET_DEFAULT_SIZE / sizeof(__m128i);
5247
5248 # if defined(_MSC_VER) && defined(_M_IX86) && _MSC_VER <= 1900
5249 /* MSVC 32bit mode does not support _mm_set_epi64x before 2015
5250 * and some specific variants of 2015 may also lack it */
5251 /* Cast to unsigned 64-bit first to avoid signed arithmetic issues */
5252 xxh_u64 const seed64_unsigned = (xxh_u64)seed64;
5253 xxh_u64 const neg_seed64 = (xxh_u64)(0ULL - seed64_unsigned);
5254 __m128i const seed = _mm_set_epi32(
5255 (int)(neg_seed64 >> 32), /* high 32 bits of negated seed */
5256 (int)(neg_seed64), /* low 32 bits of negated seed */
5257 (int)(seed64_unsigned >> 32), /* high 32 bits of original seed */
5258 (int)(seed64_unsigned) /* low 32 bits of original seed */
5259 );
5260 # else
5261 __m128i const seed = _mm_set_epi64x((xxh_i64)(0U - seed64), (xxh_i64)seed64);
5262 # endif
5263 int i;
5264
5265 const void *const src16 = XXH3_kSecret;
5266 __m128i *dst16 = (__m128i *)customSecret;
5267 # if defined(__GNUC__) || defined(__clang__)
5268 /*
5269 * On GCC & Clang, marking 'dest' as modified will cause the compiler:
5270 * - do not extract the secret from sse registers in the internal loop
5271 * - use less common registers, and avoid pushing these reg into stack
5272 */
5273 XXH_COMPILER_GUARD(dst16);
5274 # endif
5275 XXH_ASSERT(((size_t)src16 & 15) == 0); /* control alignment */
5276 XXH_ASSERT(((size_t)dst16 & 15) == 0);
5277
5278 for (i = 0; i < nbRounds; ++i) {
5279 dst16[i] = _mm_add_epi64(_mm_load_si128((const __m128i *)src16 + i), seed);
5280 }
5281 }
5282 }
5283
5284 # endif
5285
5286 # if (XXH_VECTOR == XXH_NEON)
5287
5288 /* forward declarations for the scalar routines */
5289 XXH_FORCE_INLINE void XXH3_scalarRound(
5290 void *XXH_RESTRICT acc,
5291 void const *XXH_RESTRICT input,
5292 void const *XXH_RESTRICT secret,
5293 size_t lane);
5294
5295 XXH_FORCE_INLINE void XXH3_scalarScrambleRound(void *XXH_RESTRICT acc, void const *XXH_RESTRICT secret, size_t lane);
5296
5297 /*!
5298 * @internal
5299 * @brief The bulk processing loop for NEON and WASM SIMD128.
5300 *
5301 * The NEON code path is actually partially scalar when running on AArch64. This
5302 * is to optimize the pipelining and can have up to 15% speedup depending on the
5303 * CPU, and it also mitigates some GCC codegen issues.
5304 *
5305 * @see XXH3_NEON_LANES for configuring this and details about this optimization.
5306 *
5307 * NEON's 32-bit to 64-bit long multiply takes a half vector of 32-bit
5308 * integers instead of the other platforms which mask full 64-bit vectors,
5309 * so the setup is more complicated than just shifting right.
5310 *
5311 * Additionally, there is an optimization for 4 lanes at once noted below.
5312 *
5313 * Since, as stated, the most optimal amount of lanes for Cortexes is 6,
5314 * there needs to be *three* versions of the accumulate operation used
5315 * for the remaining 2 lanes.
5316 *
5317 * WASM's SIMD128 uses SIMDe's arm_neon.h polyfill because the intrinsics overlap
5318 * nearly perfectly.
5319 */
5320
5321 XXH_FORCE_INLINE void XXH3_accumulate_512_neon(
5322 void *XXH_RESTRICT acc,
5323 const void *XXH_RESTRICT input,
5324 const void *XXH_RESTRICT secret) {
5325 XXH_ASSERT((((size_t)acc) & 15) == 0);
5326 XXH_STATIC_ASSERT(XXH3_NEON_LANES > 0 && XXH3_NEON_LANES <= XXH_ACC_NB && XXH3_NEON_LANES % 2 == 0);
5327 { /* GCC for darwin arm64 does not like aliasing here */
5328 xxh_aliasing_uint64x2_t *const xacc = (xxh_aliasing_uint64x2_t *)acc;
5329 /* We don't use a uint32x4_t pointer because it causes bus errors on ARMv7. */
5330 uint8_t const *xinput = (const uint8_t *)input;
5331 uint8_t const *xsecret = (const uint8_t *)secret;
5332
5333 size_t i;
5334 # ifdef __wasm_simd128__
5335 /*
5336 * On WASM SIMD128, Clang emits direct address loads when XXH3_kSecret
5337 * is constant propagated, which results in it converting it to this
5338 * inside the loop:
5339 *
5340 * a = v128.load(XXH3_kSecret + 0 + $secret_offset, offset = 0)
5341 * b = v128.load(XXH3_kSecret + 16 + $secret_offset, offset = 0)
5342 * ...
5343 *
5344 * This requires a full 32-bit address immediate (and therefore a 6 byte
5345 * instruction) as well as an add for each offset.
5346 *
5347 * Putting an asm guard prevents it from folding (at the cost of losing
5348 * the alignment hint), and uses the free offset in `v128.load` instead
5349 * of adding secret_offset each time which overall reduces code size by
5350 * about a kilobyte and improves performance.
5351 */
5352 XXH_COMPILER_GUARD(xsecret);
5353 # endif
5354 /* Scalar lanes use the normal scalarRound routine */
5355 for (i = XXH3_NEON_LANES; i < XXH_ACC_NB; i++) {
5356 XXH3_scalarRound(acc, input, secret, i);
5357 }
5358 i = 0;
5359 /* 4 NEON lanes at a time. */
5360 for (; i + 1 < XXH3_NEON_LANES / 2; i += 2) {
5361 /* data_vec = xinput[i]; */
5362 uint64x2_t data_vec_1 = XXH_vld1q_u64(xinput + (i * 16));
5363 uint64x2_t data_vec_2 = XXH_vld1q_u64(xinput + ((i + 1) * 16));
5364 /* key_vec = xsecret[i]; */
5365 uint64x2_t key_vec_1 = XXH_vld1q_u64(xsecret + (i * 16));
5366 uint64x2_t key_vec_2 = XXH_vld1q_u64(xsecret + ((i + 1) * 16));
5367 /* data_swap = swap(data_vec) */
5368 uint64x2_t data_swap_1 = vextq_u64(data_vec_1, data_vec_1, 1);
5369 uint64x2_t data_swap_2 = vextq_u64(data_vec_2, data_vec_2, 1);
5370 /* data_key = data_vec ^ key_vec; */
5371 uint64x2_t data_key_1 = veorq_u64(data_vec_1, key_vec_1);
5372 uint64x2_t data_key_2 = veorq_u64(data_vec_2, key_vec_2);
5373
5374 /*
5375 * If we reinterpret the 64x2 vectors as 32x4 vectors, we can use a
5376 * de-interleave operation for 4 lanes in 1 step with `vuzpq_u32` to
5377 * get one vector with the low 32 bits of each lane, and one vector
5378 * with the high 32 bits of each lane.
5379 *
5380 * The intrinsic returns a double vector because the original ARMv7-a
5381 * instruction modified both arguments in place. AArch64 and SIMD128 emit
5382 * two instructions from this intrinsic.
5383 *
5384 * [ dk11L | dk11H | dk12L | dk12H ] -> [ dk11L | dk12L | dk21L | dk22L ]
5385 * [ dk21L | dk21H | dk22L | dk22H ] -> [ dk11H | dk12H | dk21H | dk22H ]
5386 */
5387 uint32x4x2_t unzipped = vuzpq_u32(vreinterpretq_u32_u64(data_key_1), vreinterpretq_u32_u64(data_key_2));
5388 /* data_key_lo = data_key & 0xFFFFFFFF */
5389 uint32x4_t data_key_lo = unzipped.val[0];
5390 /* data_key_hi = data_key >> 32 */
5391 uint32x4_t data_key_hi = unzipped.val[1];
5392 /*
5393 * Then, we can split the vectors horizontally and multiply which, as for most
5394 * widening intrinsics, have a variant that works on both high half vectors
5395 * for free on AArch64. A similar instruction is available on SIMD128.
5396 *
5397 * sum = data_swap + (u64x2) data_key_lo * (u64x2) data_key_hi
5398 */
5399 uint64x2_t sum_1 = XXH_vmlal_low_u32(data_swap_1, data_key_lo, data_key_hi);
5400 uint64x2_t sum_2 = XXH_vmlal_high_u32(data_swap_2, data_key_lo, data_key_hi);
5401 /*
5402 * Clang reorders
5403 * a += b * c; // umlal swap.2d, dkl.2s, dkh.2s
5404 * c += a; // add acc.2d, acc.2d, swap.2d
5405 * to
5406 * c += a; // add acc.2d, acc.2d, swap.2d
5407 * c += b * c; // umlal acc.2d, dkl.2s, dkh.2s
5408 *
5409 * While it would make sense in theory since the addition is faster,
5410 * for reasons likely related to umlal being limited to certain NEON
5411 * pipelines, this is worse. A compiler guard fixes this.
5412 */
5413 XXH_COMPILER_GUARD_CLANG_NEON(sum_1);
5414 XXH_COMPILER_GUARD_CLANG_NEON(sum_2);
5415 /* xacc[i] = acc_vec + sum; */
5416 xacc[i] = vaddq_u64(xacc[i], sum_1);
5417 xacc[i + 1] = vaddq_u64(xacc[i + 1], sum_2);
5418 }
5419 /* Operate on the remaining NEON lanes 2 at a time. */
5420 for (; i < XXH3_NEON_LANES / 2; i++) {
5421 /* data_vec = xinput[i]; */
5422 uint64x2_t data_vec = XXH_vld1q_u64(xinput + (i * 16));
5423 /* key_vec = xsecret[i]; */
5424 uint64x2_t key_vec = XXH_vld1q_u64(xsecret + (i * 16));
5425 /* acc_vec_2 = swap(data_vec) */
5426 uint64x2_t data_swap = vextq_u64(data_vec, data_vec, 1);
5427 /* data_key = data_vec ^ key_vec; */
5428 uint64x2_t data_key = veorq_u64(data_vec, key_vec);
5429 /* For two lanes, just use VMOVN and VSHRN. */
5430 /* data_key_lo = data_key & 0xFFFFFFFF; */
5431 uint32x2_t data_key_lo = vmovn_u64(data_key);
5432 /* data_key_hi = data_key >> 32; */
5433 uint32x2_t data_key_hi = vshrn_n_u64(data_key, 32);
5434 /* sum = data_swap + (u64x2) data_key_lo * (u64x2) data_key_hi; */
5435 uint64x2_t sum = vmlal_u32(data_swap, data_key_lo, data_key_hi);
5436 /* Same Clang workaround as before */
5437 XXH_COMPILER_GUARD_CLANG_NEON(sum);
5438 /* xacc[i] = acc_vec + sum; */
5439 xacc[i] = vaddq_u64(xacc[i], sum);
5440 }
5441 }
5442 }
5443 XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(neon)
5444
5445 XXH_FORCE_INLINE void XXH3_scrambleAcc_neon(void *XXH_RESTRICT acc, const void *XXH_RESTRICT secret) {
5446 XXH_ASSERT((((size_t)acc) & 15) == 0);
5447
5448 {
5449 xxh_aliasing_uint64x2_t *xacc = (xxh_aliasing_uint64x2_t *)acc;
5450 uint8_t const *xsecret = (uint8_t const *)secret;
5451
5452 size_t i;
5453 /* WASM uses operator overloads and doesn't need these. */
5454 # ifndef __wasm_simd128__
5455 /* { prime32_1, prime32_1 } */
5456 uint32x2_t const kPrimeLo = vdup_n_u32(XXH_PRIME32_1);
5457 /* { 0, prime32_1, 0, prime32_1 } */
5458 uint32x4_t const kPrimeHi = vreinterpretq_u32_u64(vdupq_n_u64((xxh_u64)XXH_PRIME32_1 << 32));
5459 # endif
5460
5461 /* AArch64 uses both scalar and neon at the same time */
5462 for (i = XXH3_NEON_LANES; i < XXH_ACC_NB; i++) {
5463 XXH3_scalarScrambleRound(acc, secret, i);
5464 }
5465 for (i = 0; i < XXH3_NEON_LANES / 2; i++) {
5466 /* xacc[i] ^= (xacc[i] >> 47); */
5467 uint64x2_t acc_vec = xacc[i];
5468 uint64x2_t shifted = vshrq_n_u64(acc_vec, 47);
5469 uint64x2_t data_vec = veorq_u64(acc_vec, shifted);
5470
5471 /* xacc[i] ^= xsecret[i]; */
5472 uint64x2_t key_vec = XXH_vld1q_u64(xsecret + (i * 16));
5473 uint64x2_t data_key = veorq_u64(data_vec, key_vec);
5474 /* xacc[i] *= XXH_PRIME32_1 */
5475 # ifdef __wasm_simd128__
5476 /* SIMD128 has multiply by u64x2, use it instead of expanding and scalarizing */
5477 xacc[i] = data_key * XXH_PRIME32_1;
5478 # else
5479 /*
5480 * Expanded version with portable NEON intrinsics
5481 *
5482 * lo(x) * lo(y) + (hi(x) * lo(y) << 32)
5483 *
5484 * prod_hi = hi(data_key) * lo(prime) << 32
5485 *
5486 * Since we only need 32 bits of this multiply a trick can be used, reinterpreting the vector
5487 * as a uint32x4_t and multiplying by { 0, prime, 0, prime } to cancel out the unwanted bits
5488 * and avoid the shift.
5489 */
5490 uint32x4_t prod_hi = vmulq_u32(vreinterpretq_u32_u64(data_key), kPrimeHi);
5491 /* Extract low bits for vmlal_u32 */
5492 uint32x2_t data_key_lo = vmovn_u64(data_key);
5493 /* xacc[i] = prod_hi + lo(data_key) * XXH_PRIME32_1; */
5494 xacc[i] = vmlal_u32(vreinterpretq_u64_u32(prod_hi), data_key_lo, kPrimeLo);
5495 # endif
5496 }
5497 }
5498 }
5499 # endif
5500
5501 # if (XXH_VECTOR == XXH_VSX)
5502
5503 XXH_FORCE_INLINE void XXH3_accumulate_512_vsx(
5504 void *XXH_RESTRICT acc,
5505 const void *XXH_RESTRICT input,
5506 const void *XXH_RESTRICT secret) {
5507 /* presumed aligned */
5508 xxh_aliasing_u64x2 *const xacc = (xxh_aliasing_u64x2 *)acc;
5509 xxh_u8 const *const xinput = (xxh_u8 const *)input; /* no alignment restriction */
5510 xxh_u8 const *const xsecret = (xxh_u8 const *)secret; /* no alignment restriction */
5511 xxh_u64x2 const v32 = {32, 32};
5512 size_t i;
5513 for (i = 0; i < XXH_STRIPE_LEN / sizeof(xxh_u64x2); i++) {
5514 /* data_vec = xinput[i]; */
5515 xxh_u64x2 const data_vec = XXH_vec_loadu(xinput + 16 * i);
5516 /* key_vec = xsecret[i]; */
5517 xxh_u64x2 const key_vec = XXH_vec_loadu(xsecret + 16 * i);
5518 xxh_u64x2 const data_key = data_vec ^ key_vec;
5519 /* shuffled = (data_key << 32) | (data_key >> 32); */
5520 xxh_u32x4 const shuffled = (xxh_u32x4)vec_rl(data_key, v32);
5521 /* product = ((xxh_u64x2)data_key & 0xFFFFFFFF) * ((xxh_u64x2)shuffled & 0xFFFFFFFF); */
5522 xxh_u64x2 const product = XXH_vec_mulo((xxh_u32x4)data_key, shuffled);
5523 /* acc_vec = xacc[i]; */
5524 xxh_u64x2 acc_vec = xacc[i];
5525 acc_vec += product;
5526
5527 /* swap high and low halves */
5528 # ifdef __s390x__
5529 acc_vec += vec_permi(data_vec, data_vec, 2);
5530 # else
5531 acc_vec += vec_xxpermdi(data_vec, data_vec, 2);
5532 # endif
5533 xacc[i] = acc_vec;
5534 }
5535 }
5536 XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(vsx)
5537
5538 XXH_FORCE_INLINE void XXH3_scrambleAcc_vsx(void *XXH_RESTRICT acc, const void *XXH_RESTRICT secret) {
5539 XXH_ASSERT((((size_t)acc) & 15) == 0);
5540
5541 {
5542 xxh_aliasing_u64x2 *const xacc = (xxh_aliasing_u64x2 *)acc;
5543 const xxh_u8 *const xsecret = (const xxh_u8 *)secret;
5544 /* constants */
5545 xxh_u64x2 const v32 = {32, 32};
5546 xxh_u64x2 const v47 = {47, 47};
5547 xxh_u32x4 const prime = {XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1};
5548 size_t i;
5549 for (i = 0; i < XXH_STRIPE_LEN / sizeof(xxh_u64x2); i++) {
5550 /* xacc[i] ^= (xacc[i] >> 47); */
5551 xxh_u64x2 const acc_vec = xacc[i];
5552 xxh_u64x2 const data_vec = acc_vec ^ (acc_vec >> v47);
5553
5554 /* xacc[i] ^= xsecret[i]; */
5555 xxh_u64x2 const key_vec = XXH_vec_loadu(xsecret + 16 * i);
5556 xxh_u64x2 const data_key = data_vec ^ key_vec;
5557
5558 /* xacc[i] *= XXH_PRIME32_1 */
5559 /* prod_lo = ((xxh_u64x2)data_key & 0xFFFFFFFF) * ((xxh_u64x2)prime & 0xFFFFFFFF); */
5560 xxh_u64x2 const prod_even = XXH_vec_mule((xxh_u32x4)data_key, prime);
5561 /* prod_hi = ((xxh_u64x2)data_key >> 32) * ((xxh_u64x2)prime >> 32); */
5562 xxh_u64x2 const prod_odd = XXH_vec_mulo((xxh_u32x4)data_key, prime);
5563 xacc[i] = prod_odd + (prod_even << v32);
5564 }
5565 }
5566 }
5567
5568 # endif
5569
5570 # if (XXH_VECTOR == XXH_SVE)
5571
5572 XXH_FORCE_INLINE void XXH3_accumulate_512_sve(
5573 void *XXH_RESTRICT acc,
5574 const void *XXH_RESTRICT input,
5575 const void *XXH_RESTRICT secret) {
5576 uint64_t *xacc = (uint64_t *)acc;
5577 const uint64_t *xinput = (const uint64_t *)(const void *)input;
5578 const uint64_t *xsecret = (const uint64_t *)(const void *)secret;
5579 svuint64_t kSwap = sveor_n_u64_z(svptrue_b64(), svindex_u64(0, 1), 1);
5580 uint64_t element_count = svcntd();
5581 if (element_count >= 8) {
5582 svbool_t mask = svptrue_pat_b64(SV_VL8);
5583 svuint64_t vacc = svld1_u64(mask, xacc);
5584 ACCRND(vacc, 0);
5585 svst1_u64(mask, xacc, vacc);
5586 } else if (element_count == 2) { /* sve128 */
5587 svbool_t mask = svptrue_pat_b64(SV_VL2);
5588 svuint64_t acc0 = svld1_u64(mask, xacc + 0);
5589 svuint64_t acc1 = svld1_u64(mask, xacc + 2);
5590 svuint64_t acc2 = svld1_u64(mask, xacc + 4);
5591 svuint64_t acc3 = svld1_u64(mask, xacc + 6);
5592 ACCRND(acc0, 0);
5593 ACCRND(acc1, 2);
5594 ACCRND(acc2, 4);
5595 ACCRND(acc3, 6);
5596 svst1_u64(mask, xacc + 0, acc0);
5597 svst1_u64(mask, xacc + 2, acc1);
5598 svst1_u64(mask, xacc + 4, acc2);
5599 svst1_u64(mask, xacc + 6, acc3);
5600 } else {
5601 svbool_t mask = svptrue_pat_b64(SV_VL4);
5602 svuint64_t acc0 = svld1_u64(mask, xacc + 0);
5603 svuint64_t acc1 = svld1_u64(mask, xacc + 4);
5604 ACCRND(acc0, 0);
5605 ACCRND(acc1, 4);
5606 svst1_u64(mask, xacc + 0, acc0);
5607 svst1_u64(mask, xacc + 4, acc1);
5608 }
5609 }
5610
5611 XXH_FORCE_INLINE void XXH3_accumulate_sve(
5612 xxh_u64 *XXH_RESTRICT acc,
5613 const xxh_u8 *XXH_RESTRICT input,
5614 const xxh_u8 *XXH_RESTRICT secret,
5615 size_t nbStripes) {
5616 if (nbStripes != 0) {
5617 uint64_t *xacc = (uint64_t *)acc;
5618 const uint64_t *xinput = (const uint64_t *)(const void *)input;
5619 const uint64_t *xsecret = (const uint64_t *)(const void *)secret;
5620 svuint64_t kSwap = sveor_n_u64_z(svptrue_b64(), svindex_u64(0, 1), 1);
5621 uint64_t element_count = svcntd();
5622 if (element_count >= 8) {
5623 svbool_t mask = svptrue_pat_b64(SV_VL8);
5624 svuint64_t vacc = svld1_u64(mask, xacc + 0);
5625 do {
5626 /* svprfd(svbool_t, void *, enum svfprop); */
5627 svprfd(mask, xinput + 128, SV_PLDL1STRM);
5628 ACCRND(vacc, 0);
5629 xinput += 8;
5630 xsecret += 1;
5631 nbStripes--;
5632 } while (nbStripes != 0);
5633
5634 svst1_u64(mask, xacc + 0, vacc);
5635 } else if (element_count == 2) { /* sve128 */
5636 svbool_t mask = svptrue_pat_b64(SV_VL2);
5637 svuint64_t acc0 = svld1_u64(mask, xacc + 0);
5638 svuint64_t acc1 = svld1_u64(mask, xacc + 2);
5639 svuint64_t acc2 = svld1_u64(mask, xacc + 4);
5640 svuint64_t acc3 = svld1_u64(mask, xacc + 6);
5641 do {
5642 svprfd(mask, xinput + 128, SV_PLDL1STRM);
5643 ACCRND(acc0, 0);
5644 ACCRND(acc1, 2);
5645 ACCRND(acc2, 4);
5646 ACCRND(acc3, 6);
5647 xinput += 8;
5648 xsecret += 1;
5649 nbStripes--;
5650 } while (nbStripes != 0);
5651
5652 svst1_u64(mask, xacc + 0, acc0);
5653 svst1_u64(mask, xacc + 2, acc1);
5654 svst1_u64(mask, xacc + 4, acc2);
5655 svst1_u64(mask, xacc + 6, acc3);
5656 } else {
5657 svbool_t mask = svptrue_pat_b64(SV_VL4);
5658 svuint64_t acc0 = svld1_u64(mask, xacc + 0);
5659 svuint64_t acc1 = svld1_u64(mask, xacc + 4);
5660 do {
5661 svprfd(mask, xinput + 128, SV_PLDL1STRM);
5662 ACCRND(acc0, 0);
5663 ACCRND(acc1, 4);
5664 xinput += 8;
5665 xsecret += 1;
5666 nbStripes--;
5667 } while (nbStripes != 0);
5668
5669 svst1_u64(mask, xacc + 0, acc0);
5670 svst1_u64(mask, xacc + 4, acc1);
5671 }
5672 }
5673 }
5674
5675 # endif
5676
5677 # if (XXH_VECTOR == XXH_LSX)
5678 # define _LSX_SHUFFLE(z, y, x, w) (((z) << 6) | ((y) << 4) | ((x) << 2) | (w))
5679
5680 XXH_FORCE_INLINE void XXH3_accumulate_512_lsx(
5681 void *XXH_RESTRICT acc,
5682 const void *XXH_RESTRICT input,
5683 const void *XXH_RESTRICT secret) {
5684 XXH_ASSERT((((size_t)acc) & 15) == 0);
5685 {
5686 __m128i *const xacc = (__m128i *)acc;
5687 const __m128i *const xinput = (const __m128i *)input;
5688 const __m128i *const xsecret = (const __m128i *)secret;
5689 size_t i;
5690
5691 for (i = 0; i < XXH_STRIPE_LEN / sizeof(__m128i); i++) {
5692 /* data_vec = xinput[i]; */
5693 __m128i const data_vec = __lsx_vld(xinput + i, 0);
5694 /* key_vec = xsecret[i]; */
5695 __m128i const key_vec = __lsx_vld(xsecret + i, 0);
5696 /* data_key = data_vec ^ key_vec; */
5697 __m128i const data_key = __lsx_vxor_v(data_vec, key_vec);
5698 /* data_key_lo = data_key >> 32; */
5699 __m128i const data_key_lo = __lsx_vsrli_d(data_key, 32);
5700 // __m128i const data_key_lo = __lsx_vsrli_d(data_key, 32);
5701 /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */
5702 __m128i const product = __lsx_vmulwev_d_wu(data_key, data_key_lo);
5703 /* xacc[i] += swap(data_vec); */
5704 __m128i const data_swap = __lsx_vshuf4i_w(data_vec, _LSX_SHUFFLE(1, 0, 3, 2));
5705 __m128i const sum = __lsx_vadd_d(xacc[i], data_swap);
5706 /* xacc[i] += product; */
5707 xacc[i] = __lsx_vadd_d(product, sum);
5708 }
5709 }
5710 }
5711 XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(lsx)
5712
5713 XXH_FORCE_INLINE void XXH3_scrambleAcc_lsx(void *XXH_RESTRICT acc, const void *XXH_RESTRICT secret) {
5714 XXH_ASSERT((((size_t)acc) & 15) == 0);
5715 {
5716 __m128i *const xacc = (__m128i *)acc;
5717 const __m128i *const xsecret = (const __m128i *)secret;
5718 const __m128i prime32 = __lsx_vreplgr2vr_d(XXH_PRIME32_1);
5719 size_t i;
5720
5721 for (i = 0; i < XXH_STRIPE_LEN / sizeof(__m128i); i++) {
5722 /* xacc[i] ^= (xacc[i] >> 47) */
5723 __m128i const acc_vec = xacc[i];
5724 __m128i const shifted = __lsx_vsrli_d(acc_vec, 47);
5725 __m128i const data_vec = __lsx_vxor_v(acc_vec, shifted);
5726 /* xacc[i] ^= xsecret[i]; */
5727 __m128i const key_vec = __lsx_vld(xsecret + i, 0);
5728 __m128i const data_key = __lsx_vxor_v(data_vec, key_vec);
5729
5730 /* xacc[i] *= XXH_PRIME32_1; */
5731 xacc[i] = __lsx_vmul_d(data_key, prime32);
5732 }
5733 }
5734 }
5735
5736 # endif
5737
5738 # if (XXH_VECTOR == XXH_LASX)
5739 # define _LASX_SHUFFLE(z, y, x, w) (((z) << 6) | ((y) << 4) | ((x) << 2) | (w))
5740
5741 XXH_FORCE_INLINE void XXH3_accumulate_512_lasx(
5742 void *XXH_RESTRICT acc,
5743 const void *XXH_RESTRICT input,
5744 const void *XXH_RESTRICT secret) {
5745 XXH_ASSERT((((size_t)acc) & 31) == 0);
5746 {
5747 size_t i;
5748 __m256i *const xacc = (__m256i *)acc;
5749 const __m256i *const xinput = (const __m256i *)input;
5750 const __m256i *const xsecret = (const __m256i *)secret;
5751
5752 for (i = 0; i < XXH_STRIPE_LEN / sizeof(__m256i); i++) {
5753 /* data_vec = xinput[i]; */
5754 __m256i const data_vec = __lasx_xvld(xinput + i, 0);
5755 /* key_vec = xsecret[i]; */
5756 __m256i const key_vec = __lasx_xvld(xsecret + i, 0);
5757 /* data_key = data_vec ^ key_vec; */
5758 __m256i const data_key = __lasx_xvxor_v(data_vec, key_vec);
5759 /* data_key_lo = data_key >> 32; */
5760 __m256i const data_key_lo = __lasx_xvsrli_d(data_key, 32);
5761 // __m256i const data_key_lo = __lasx_xvsrli_d(data_key, 32);
5762 /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */
5763 __m256i const product = __lasx_xvmulwev_d_wu(data_key, data_key_lo);
5764 /* xacc[i] += swap(data_vec); */
5765 __m256i const data_swap = __lasx_xvshuf4i_w(data_vec, _LASX_SHUFFLE(1, 0, 3, 2));
5766 __m256i const sum = __lasx_xvadd_d(xacc[i], data_swap);
5767 /* xacc[i] += product; */
5768 xacc[i] = __lasx_xvadd_d(product, sum);
5769 }
5770 }
5771 }
5772 XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(lasx)
5773
5774 XXH_FORCE_INLINE void XXH3_scrambleAcc_lasx(void *XXH_RESTRICT acc, const void *XXH_RESTRICT secret) {
5775 XXH_ASSERT((((size_t)acc) & 31) == 0);
5776 {
5777 __m256i *const xacc = (__m256i *)acc;
5778 const __m256i *const xsecret = (const __m256i *)secret;
5779 const __m256i prime32 = __lasx_xvreplgr2vr_d(XXH_PRIME32_1);
5780 size_t i;
5781
5782 for (i = 0; i < XXH_STRIPE_LEN / sizeof(__m256i); i++) {
5783 /* xacc[i] ^= (xacc[i] >> 47) */
5784 __m256i const acc_vec = xacc[i];
5785 __m256i const shifted = __lasx_xvsrli_d(acc_vec, 47);
5786 __m256i const data_vec = __lasx_xvxor_v(acc_vec, shifted);
5787 /* xacc[i] ^= xsecret[i]; */
5788 __m256i const key_vec = __lasx_xvld(xsecret + i, 0);
5789 __m256i const data_key = __lasx_xvxor_v(data_vec, key_vec);
5790
5791 /* xacc[i] *= XXH_PRIME32_1; */
5792 xacc[i] = __lasx_xvmul_d(data_key, prime32);
5793 }
5794 }
5795 }
5796
5797 # endif
5798
5799 # if (XXH_VECTOR == XXH_RVV)
5800 # define XXH_CONCAT2(X, Y) X##Y
5801 # define XXH_CONCAT(X, Y) XXH_CONCAT2(X, Y)
5802 # if ( \
5803 (defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 13) || \
5804 (defined(__clang__) && __clang_major__ < 16))
5805 # define XXH_RVOP(op) op
5806 # define XXH_RVCAST(op) XXH_CONCAT(vreinterpret_v_, op)
5807 # else
5808 # define XXH_RVOP(op) XXH_CONCAT(__riscv_, op)
5809 # define XXH_RVCAST(op) XXH_CONCAT(__riscv_vreinterpret_v_, op)
5810 # endif
5811 XXH_FORCE_INLINE void XXH3_accumulate_512_rvv(
5812 void *XXH_RESTRICT acc,
5813 const void *XXH_RESTRICT input,
5814 const void *XXH_RESTRICT secret) {
5815 XXH_ASSERT((((size_t)acc) & 63) == 0);
5816 {
5817 // Try to set vector lenght to 512 bits.
5818 // If this length is unavailable, then maximum available will be used
5819 size_t vl = XXH_RVOP(vsetvl_e64m2)(8);
5820
5821 uint64_t *xacc = (uint64_t *)acc;
5822 const uint64_t *xinput = (const uint64_t *)input;
5823 const uint64_t *xsecret = (const uint64_t *)secret;
5824 static const uint64_t swap_mask[16] = {1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14};
5825 vuint64m2_t xswap_mask = XXH_RVOP(vle64_v_u64m2)(swap_mask, vl);
5826
5827 size_t i;
5828 for (i = 0; i < XXH_STRIPE_LEN / 8; i += vl) {
5829 /* data_vec = xinput[i]; */
5830 vuint64m2_t data_vec = XXH_RVCAST(u8m2_u64m2)(XXH_RVOP(vle8_v_u8m2)((const uint8_t *)(xinput + i), vl * 8));
5831 /* key_vec = xsecret[i]; */
5832 vuint64m2_t key_vec = XXH_RVCAST(u8m2_u64m2)(XXH_RVOP(vle8_v_u8m2)((const uint8_t *)(xsecret + i), vl * 8));
5833 /* acc_vec = xacc[i]; */
5834 vuint64m2_t acc_vec = XXH_RVOP(vle64_v_u64m2)(xacc + i, vl);
5835 /* data_key = data_vec ^ key_vec; */
5836 vuint64m2_t data_key = XXH_RVOP(vxor_vv_u64m2)(data_vec, key_vec, vl);
5837 /* data_key_hi = data_key >> 32; */
5838 vuint64m2_t data_key_hi = XXH_RVOP(vsrl_vx_u64m2)(data_key, 32, vl);
5839 /* data_key_lo = data_key & 0xffffffff; */
5840 vuint64m2_t data_key_lo = XXH_RVOP(vand_vx_u64m2)(data_key, 0xffffffff, vl);
5841 /* swap high and low halves */
5842 vuint64m2_t data_swap = XXH_RVOP(vrgather_vv_u64m2)(data_vec, xswap_mask, vl);
5843 /* acc_vec += data_key_lo * data_key_hi; */
5844 acc_vec = XXH_RVOP(vmacc_vv_u64m2)(acc_vec, data_key_lo, data_key_hi, vl);
5845 /* acc_vec += data_swap; */
5846 acc_vec = XXH_RVOP(vadd_vv_u64m2)(acc_vec, data_swap, vl);
5847 /* xacc[i] = acc_vec; */
5848 XXH_RVOP(vse64_v_u64m2)(xacc + i, acc_vec, vl);
5849 }
5850 }
5851 }
5852
5853 XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(rvv)
5854
5855 XXH_FORCE_INLINE void XXH3_scrambleAcc_rvv(void *XXH_RESTRICT acc, const void *XXH_RESTRICT secret) {
5856 XXH_ASSERT((((size_t)acc) & 15) == 0);
5857 {
5858 size_t count = XXH_STRIPE_LEN / 8;
5859 uint64_t *xacc = (uint64_t *)acc;
5860 const uint8_t *xsecret = (const uint8_t *)secret;
5861 size_t vl;
5862 for (; count > 0; count -= vl, xacc += vl, xsecret += vl * 8) {
5863 vl = XXH_RVOP(vsetvl_e64m2)(count);
5864 {
5865 /* key_vec = xsecret[i]; */
5866 vuint64m2_t key_vec = XXH_RVCAST(u8m2_u64m2)(XXH_RVOP(vle8_v_u8m2)(xsecret, vl * 8));
5867 /* acc_vec = xacc[i]; */
5868 vuint64m2_t acc_vec = XXH_RVOP(vle64_v_u64m2)(xacc, vl);
5869 /* acc_vec ^= acc_vec >> 47; */
5870 vuint64m2_t vsrl = XXH_RVOP(vsrl_vx_u64m2)(acc_vec, 47, vl);
5871 acc_vec = XXH_RVOP(vxor_vv_u64m2)(acc_vec, vsrl, vl);
5872 /* acc_vec ^= key_vec; */
5873 acc_vec = XXH_RVOP(vxor_vv_u64m2)(acc_vec, key_vec, vl);
5874 /* acc_vec *= XXH_PRIME32_1; */
5875 acc_vec = XXH_RVOP(vmul_vx_u64m2)(acc_vec, XXH_PRIME32_1, vl);
5876 /* xacc[i] *= acc_vec; */
5877 XXH_RVOP(vse64_v_u64m2)(xacc, acc_vec, vl);
5878 }
5879 }
5880 }
5881 }
5882
5883 XXH_FORCE_INLINE void XXH3_initCustomSecret_rvv(void *XXH_RESTRICT customSecret, xxh_u64 seed64) {
5884 XXH_STATIC_ASSERT(XXH_SEC_ALIGN >= 8);
5885 XXH_ASSERT(((size_t)customSecret & 7) == 0);
5886 (void)(&XXH_writeLE64);
5887 {
5888 size_t count = XXH_SECRET_DEFAULT_SIZE / 8;
5889 size_t vl;
5890 size_t VLMAX = XXH_RVOP(vsetvlmax_e64m2)();
5891 int64_t *cSecret = (int64_t *)customSecret;
5892 const int64_t *kSecret = (const int64_t *)(const void *)XXH3_kSecret;
5893
5894 # if __riscv_v_intrinsic >= 1000000
5895 // ratified v1.0 intrinics version
5896 vbool32_t mneg = XXH_RVCAST(u8m1_b32)(XXH_RVOP(vmv_v_x_u8m1)(0xaa, XXH_RVOP(vsetvlmax_e8m1)()));
5897 # else
5898 // support pre-ratification intrinics, which lack mask to vector casts
5899 size_t vlmax = XXH_RVOP(vsetvlmax_e8m1)();
5900 vbool32_t mneg =
5901 XXH_RVOP(vmseq_vx_u8mf4_b32)(XXH_RVOP(vand_vx_u8mf4)(XXH_RVOP(vid_v_u8mf4)(vlmax), 1, vlmax), 1, vlmax);
5902 # endif
5903 vint64m2_t seed = XXH_RVOP(vmv_v_x_i64m2)((int64_t)seed64, VLMAX);
5904 seed = XXH_RVOP(vneg_v_i64m2_mu)(mneg, seed, seed, VLMAX);
5905
5906 for (; count > 0; count -= vl, cSecret += vl, kSecret += vl) {
5907 /* make sure vl=VLMAX until last iteration */
5908 vl = XXH_RVOP(vsetvl_e64m2)(count < VLMAX ? count : VLMAX);
5909 {
5910 vint64m2_t src = XXH_RVOP(vle64_v_i64m2)(kSecret, vl);
5911 vint64m2_t res = XXH_RVOP(vadd_vv_i64m2)(src, seed, vl);
5912 XXH_RVOP(vse64_v_i64m2)(cSecret, res, vl);
5913 }
5914 }
5915 }
5916 }
5917 # endif
5918
5919 /* scalar variants - universal */
5920
5921 # if defined(__aarch64__) && (defined(__GNUC__) || defined(__clang__))
5922 /*
5923 * In XXH3_scalarRound(), GCC and Clang have a similar codegen issue, where they
5924 * emit an excess mask and a full 64-bit multiply-add (MADD X-form).
5925 *
5926 * While this might not seem like much, as AArch64 is a 64-bit architecture, only
5927 * big Cortex designs have a full 64-bit multiplier.
5928 *
5929 * On the little cores, the smaller 32-bit multiplier is used, and full 64-bit
5930 * multiplies expand to 2-3 multiplies in microcode. This has a major penalty
5931 * of up to 4 latency cycles and 2 stall cycles in the multiply pipeline.
5932 *
5933 * Thankfully, AArch64 still provides the 32-bit long multiply-add (UMADDL) which does
5934 * not have this penalty and does the mask automatically.
5935 */
5936 XXH_FORCE_INLINE xxh_u64 XXH_mult32to64_add64(xxh_u64 lhs, xxh_u64 rhs, xxh_u64 acc) {
5937 xxh_u64 ret;
5938 /* note: %x = 64-bit register, %w = 32-bit register */
5939 __asm__("umaddl %x0, %w1, %w2, %x3" : "=r"(ret) : "r"(lhs), "r"(rhs), "r"(acc));
5940 return ret;
5941 }
5942 # else
5943 XXH_FORCE_INLINE xxh_u64 XXH_mult32to64_add64(xxh_u64 lhs, xxh_u64 rhs, xxh_u64 acc) {
5944 return XXH_mult32to64((xxh_u32)lhs, (xxh_u32)rhs) + acc;
5945 }
5946 # endif
5947
5948 /*!
5949 * @internal
5950 * @brief Scalar round for @ref XXH3_accumulate_512_scalar().
5951 *
5952 * This is extracted to its own function because the NEON path uses a combination
5953 * of NEON and scalar.
5954 */
5955 XXH_FORCE_INLINE void XXH3_scalarRound(
5956 void *XXH_RESTRICT acc,
5957 void const *XXH_RESTRICT input,
5958 void const *XXH_RESTRICT secret,
5959 size_t lane) {
5960 xxh_u64 *xacc = (xxh_u64 *)acc;
5961 xxh_u8 const *xinput = (xxh_u8 const *)input;
5962 xxh_u8 const *xsecret = (xxh_u8 const *)secret;
5963 XXH_ASSERT(lane < XXH_ACC_NB);
5964 XXH_ASSERT(((size_t)acc & (XXH_ACC_ALIGN - 1)) == 0);
5965 {
5966 xxh_u64 const data_val = XXH_readLE64(xinput + lane * 8);
5967 xxh_u64 const data_key = data_val ^ XXH_readLE64(xsecret + lane * 8);
5968 xacc[lane ^ 1] += data_val; /* swap adjacent lanes */
5969 xacc[lane] = XXH_mult32to64_add64(data_key /* & 0xFFFFFFFF */, data_key >> 32, xacc[lane]);
5970 }
5971 }
5972
5973 /*!
5974 * @internal
5975 * @brief Processes a 64 byte block of data using the scalar path.
5976 */
5977 XXH_FORCE_INLINE void XXH3_accumulate_512_scalar(
5978 void *XXH_RESTRICT acc,
5979 const void *XXH_RESTRICT input,
5980 const void *XXH_RESTRICT secret) {
5981 size_t i;
5982 /* ARM GCC refuses to unroll this loop, resulting in a 24% slowdown on ARMv6. */
5983 # if defined(__GNUC__) && !defined(__clang__) && (defined(__arm__) || defined(__thumb2__)) && \
5984 defined(__ARM_FEATURE_UNALIGNED) /* no unaligned access just wastes bytes */ \
5985 && XXH_SIZE_OPT <= 0
5986 # pragma GCC unroll 8
5987 # endif
5988 for (i = 0; i < XXH_ACC_NB; i++) {
5989 XXH3_scalarRound(acc, input, secret, i);
5990 }
5991 }
5992 XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(scalar)
5993
5994 /*!
5995 * @internal
5996 * @brief Scalar scramble step for @ref XXH3_scrambleAcc_scalar().
5997 *
5998 * This is extracted to its own function because the NEON path uses a combination
5999 * of NEON and scalar.
6000 */
6001 XXH_FORCE_INLINE
6002 void XXH3_scalarScrambleRound(void *XXH_RESTRICT acc, void const *XXH_RESTRICT secret, size_t lane) {
6003 xxh_u64 *const xacc = (xxh_u64 *)acc; /* presumed aligned */
6004 const xxh_u8 *const xsecret = (const xxh_u8 *)secret; /* no alignment restriction */
6005 XXH_ASSERT((((size_t)acc) & (XXH_ACC_ALIGN - 1)) == 0);
6006 XXH_ASSERT(lane < XXH_ACC_NB);
6007 {
6008 xxh_u64 const key64 = XXH_readLE64(xsecret + lane * 8);
6009 xxh_u64 acc64 = xacc[lane];
6010 acc64 = XXH_xorshift64(acc64, 47);
6011 acc64 ^= key64;
6012 acc64 *= XXH_PRIME32_1;
6013 xacc[lane] = acc64;
6014 }
6015 }
6016
6017 /*!
6018 * @internal
6019 * @brief Scrambles the accumulators after a large chunk has been read
6020 */
6021 XXH_FORCE_INLINE void XXH3_scrambleAcc_scalar(void *XXH_RESTRICT acc, const void *XXH_RESTRICT secret) {
6022 size_t i;
6023 for (i = 0; i < XXH_ACC_NB; i++) {
6024 XXH3_scalarScrambleRound(acc, secret, i);
6025 }
6026 }
6027
6028 XXH_FORCE_INLINE void XXH3_initCustomSecret_scalar(void *XXH_RESTRICT customSecret, xxh_u64 seed64) {
6029 /*
6030 * We need a separate pointer for the hack below,
6031 * which requires a non-const pointer.
6032 * Any decent compiler will optimize this out otherwise.
6033 */
6034 const xxh_u8 *kSecretPtr = XXH3_kSecret;
6035 XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 15) == 0);
6036
6037 # if defined(__GNUC__) && defined(__aarch64__)
6038 /*
6039 * UGLY HACK:
6040 * GCC and Clang generate a bunch of MOV/MOVK pairs for aarch64, and they are
6041 * placed sequentially, in order, at the top of the unrolled loop.
6042 *
6043 * While MOVK is great for generating constants (2 cycles for a 64-bit
6044 * constant compared to 4 cycles for LDR), it fights for bandwidth with
6045 * the arithmetic instructions.
6046 *
6047 * I L S
6048 * MOVK
6049 * MOVK
6050 * MOVK
6051 * MOVK
6052 * ADD
6053 * SUB STR
6054 * STR
6055 * By forcing loads from memory (as the asm line causes the compiler to assume
6056 * that XXH3_kSecretPtr has been changed), the pipelines are used more
6057 * efficiently:
6058 * I L S
6059 * LDR
6060 * ADD LDR
6061 * SUB STR
6062 * STR
6063 *
6064 * See XXH3_NEON_LANES for details on the pipeline.
6065 *
6066 * XXH3_64bits_withSeed, len == 256, Snapdragon 835
6067 * without hack: 2654.4 MB/s
6068 * with hack: 3202.9 MB/s
6069 */
6070 XXH_COMPILER_GUARD(kSecretPtr);
6071 # endif
6072 {
6073 int const nbRounds = XXH_SECRET_DEFAULT_SIZE / 16;
6074 int i;
6075 for (i = 0; i < nbRounds; i++) {
6076 /*
6077 * The asm hack causes the compiler to assume that kSecretPtr aliases with
6078 * customSecret, and on aarch64, this prevented LDP from merging two
6079 * loads together for free. Putting the loads together before the stores
6080 * properly generates LDP.
6081 */
6082 xxh_u64 lo = XXH_readLE64(kSecretPtr + 16 * i) + seed64;
6083 xxh_u64 hi = XXH_readLE64(kSecretPtr + 16 * i + 8) - seed64;
6084 XXH_writeLE64((xxh_u8 *)customSecret + 16 * i, lo);
6085 XXH_writeLE64((xxh_u8 *)customSecret + 16 * i + 8, hi);
6086 }
6087 }
6088 }
6089
6090 typedef void (
6091 *XXH3_f_accumulate)(xxh_u64 *XXH_RESTRICT, const xxh_u8 *XXH_RESTRICT, const xxh_u8 *XXH_RESTRICT, size_t);
6092 typedef void (*XXH3_f_scrambleAcc)(void *XXH_RESTRICT, const void *);
6093 typedef void (*XXH3_f_initCustomSecret)(void *XXH_RESTRICT, xxh_u64);
6094
6095 # if (XXH_VECTOR == XXH_AVX512)
6096
6097 # define XXH3_accumulate_512 XXH3_accumulate_512_avx512
6098 # define XXH3_accumulate XXH3_accumulate_avx512
6099 # define XXH3_scrambleAcc XXH3_scrambleAcc_avx512
6100 # define XXH3_initCustomSecret XXH3_initCustomSecret_avx512
6101
6102 # elif (XXH_VECTOR == XXH_AVX2)
6103
6104 # define XXH3_accumulate_512 XXH3_accumulate_512_avx2
6105 # define XXH3_accumulate XXH3_accumulate_avx2
6106 # define XXH3_scrambleAcc XXH3_scrambleAcc_avx2
6107 # define XXH3_initCustomSecret XXH3_initCustomSecret_avx2
6108
6109 # elif (XXH_VECTOR == XXH_SSE2)
6110
6111 # define XXH3_accumulate_512 XXH3_accumulate_512_sse2
6112 # define XXH3_accumulate XXH3_accumulate_sse2
6113 # define XXH3_scrambleAcc XXH3_scrambleAcc_sse2
6114 # define XXH3_initCustomSecret XXH3_initCustomSecret_sse2
6115
6116 # elif (XXH_VECTOR == XXH_NEON)
6117
6118 # define XXH3_accumulate_512 XXH3_accumulate_512_neon
6119 # define XXH3_accumulate XXH3_accumulate_neon
6120 # define XXH3_scrambleAcc XXH3_scrambleAcc_neon
6121 # define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
6122
6123 # elif (XXH_VECTOR == XXH_VSX)
6124
6125 # define XXH3_accumulate_512 XXH3_accumulate_512_vsx
6126 # define XXH3_accumulate XXH3_accumulate_vsx
6127 # define XXH3_scrambleAcc XXH3_scrambleAcc_vsx
6128 # define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
6129
6130 # elif (XXH_VECTOR == XXH_SVE)
6131 # define XXH3_accumulate_512 XXH3_accumulate_512_sve
6132 # define XXH3_accumulate XXH3_accumulate_sve
6133 # define XXH3_scrambleAcc XXH3_scrambleAcc_scalar
6134 # define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
6135
6136 # elif (XXH_VECTOR == XXH_LASX)
6137 # define XXH3_accumulate_512 XXH3_accumulate_512_lasx
6138 # define XXH3_accumulate XXH3_accumulate_lasx
6139 # define XXH3_scrambleAcc XXH3_scrambleAcc_lasx
6140 # define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
6141
6142 # elif (XXH_VECTOR == XXH_LSX)
6143 # define XXH3_accumulate_512 XXH3_accumulate_512_lsx
6144 # define XXH3_accumulate XXH3_accumulate_lsx
6145 # define XXH3_scrambleAcc XXH3_scrambleAcc_lsx
6146 # define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
6147
6148 # elif (XXH_VECTOR == XXH_RVV)
6149 # define XXH3_accumulate_512 XXH3_accumulate_512_rvv
6150 # define XXH3_accumulate XXH3_accumulate_rvv
6151 # define XXH3_scrambleAcc XXH3_scrambleAcc_rvv
6152 # define XXH3_initCustomSecret XXH3_initCustomSecret_rvv
6153
6154 # else /* scalar */
6155
6156 # define XXH3_accumulate_512 XXH3_accumulate_512_scalar
6157 # define XXH3_accumulate XXH3_accumulate_scalar
6158 # define XXH3_scrambleAcc XXH3_scrambleAcc_scalar
6159 # define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
6160
6161 # endif
6162
6163 # if XXH_SIZE_OPT >= 1 /* don't do SIMD for initialization */
6164 # undef XXH3_initCustomSecret
6165 # define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
6166 # endif
6167
6168 XXH_FORCE_INLINE void XXH3_hashLong_internal_loop(
6169 xxh_u64 *XXH_RESTRICT acc,
6170 const xxh_u8 *XXH_RESTRICT input,
6171 size_t len,
6172 const xxh_u8 *XXH_RESTRICT secret,
6173 size_t secretSize,
6174 XXH3_f_accumulate f_acc,
6175 XXH3_f_scrambleAcc f_scramble) {
6176 size_t const nbStripesPerBlock = (secretSize - XXH_STRIPE_LEN) / XXH_SECRET_CONSUME_RATE;
6177 size_t const block_len = XXH_STRIPE_LEN * nbStripesPerBlock;
6178 size_t const nb_blocks = (len - 1) / block_len;
6179
6180 size_t n;
6181
6182 XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
6183
6184 for (n = 0; n < nb_blocks; n++) {
6185 f_acc(acc, input + n * block_len, secret, nbStripesPerBlock);
6186 f_scramble(acc, secret + secretSize - XXH_STRIPE_LEN);
6187 }
6188
6189 /* last partial block */
6190 XXH_ASSERT(len > XXH_STRIPE_LEN);
6191 {
6192 size_t const nbStripes = ((len - 1) - (block_len * nb_blocks)) / XXH_STRIPE_LEN;
6193 XXH_ASSERT(nbStripes <= (secretSize / XXH_SECRET_CONSUME_RATE));
6194 f_acc(acc, input + nb_blocks * block_len, secret, nbStripes);
6195
6196 /* last stripe */
6197 {
6198 const xxh_u8 *const p = input + len - XXH_STRIPE_LEN;
6199 # define XXH_SECRET_LASTACC_START 7 /* not aligned on 8, last secret is different from acc & scrambler */
6200 XXH3_accumulate_512(acc, p, secret + secretSize - XXH_STRIPE_LEN - XXH_SECRET_LASTACC_START);
6201 }
6202 }
6203 }
6204
6205 XXH_FORCE_INLINE xxh_u64 XXH3_mix2Accs(const xxh_u64 *XXH_RESTRICT acc, const xxh_u8 *XXH_RESTRICT secret) {
6206 return XXH3_mul128_fold64(acc[0] ^ XXH_readLE64(secret), acc[1] ^ XXH_readLE64(secret + 8));
6207 }
6208
6209 static XXH_PUREF XXH64_hash_t
6210 XXH3_mergeAccs(const xxh_u64 *XXH_RESTRICT acc, const xxh_u8 *XXH_RESTRICT secret, xxh_u64 start) {
6211 xxh_u64 result64 = start;
6212 size_t i = 0;
6213
6214 for (i = 0; i < 4; i++) {
6215 result64 += XXH3_mix2Accs(acc + 2 * i, secret + 16 * i);
6216 # if defined(__clang__) /* Clang */ \
6217 && (defined(__arm__) || defined(__thumb__)) /* ARMv7 */ \
6218 && (defined(__ARM_NEON) || defined(__ARM_NEON__)) /* NEON */ \
6219 && !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable */
6220 /*
6221 * UGLY HACK:
6222 * Prevent autovectorization on Clang ARMv7-a. Exact same problem as
6223 * the one in XXH3_len_129to240_64b. Speeds up shorter keys > 240b.
6224 * XXH3_64bits, len == 256, Snapdragon 835:
6225 * without hack: 2063.7 MB/s
6226 * with hack: 2560.7 MB/s
6227 */
6228 XXH_COMPILER_GUARD(result64);
6229 # endif
6230 }
6231
6232 return XXH3_avalanche(result64);
6233 }
6234
6235 /* do not align on 8, so that the secret is different from the accumulator */
6236 # define XXH_SECRET_MERGEACCS_START 11
6237
6238 static XXH_PUREF XXH64_hash_t
6239 XXH3_finalizeLong_64b(const xxh_u64 *XXH_RESTRICT acc, const xxh_u8 *XXH_RESTRICT secret, xxh_u64 len) {
6240 return XXH3_mergeAccs(acc, secret + XXH_SECRET_MERGEACCS_START, len * XXH_PRIME64_1);
6241 }
6242
6243 # define XXH3_INIT_ACC \
6244 {XXH_PRIME32_3, \
6245 XXH_PRIME64_1, \
6246 XXH_PRIME64_2, \
6247 XXH_PRIME64_3, \
6248 XXH_PRIME64_4, \
6249 XXH_PRIME32_2, \
6250 XXH_PRIME64_5, \
6251 XXH_PRIME32_1}
6252
6253 XXH_FORCE_INLINE XXH64_hash_t XXH3_hashLong_64b_internal(
6254 const void *XXH_RESTRICT input,
6255 size_t len,
6256 const void *XXH_RESTRICT secret,
6257 size_t secretSize,
6258 XXH3_f_accumulate f_acc,
6259 XXH3_f_scrambleAcc f_scramble) {
6260 XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[XXH_ACC_NB] = XXH3_INIT_ACC;
6261
6262 XXH3_hashLong_internal_loop(acc, (const xxh_u8 *)input, len, (const xxh_u8 *)secret, secretSize, f_acc, f_scramble);
6263
6264 /* converge into final hash */
6265 XXH_STATIC_ASSERT(sizeof(acc) == 64);
6266 XXH_ASSERT(secretSize >= sizeof(acc) + XXH_SECRET_MERGEACCS_START);
6267 return XXH3_finalizeLong_64b(acc, (const xxh_u8 *)secret, (xxh_u64)len);
6268 }
6269
6270 /*
6271 * It's important for performance to transmit secret's size (when it's static)
6272 * so that the compiler can properly optimize the vectorized loop.
6273 * This makes a big performance difference for "medium" keys (<1 KB) when using AVX instruction set.
6274 * When the secret size is unknown, or on GCC 12 where the mix of NO_INLINE and FORCE_INLINE
6275 * breaks -Og, this is XXH_NO_INLINE.
6276 */
6277 XXH3_WITH_SECRET_INLINE XXH64_hash_t XXH3_hashLong_64b_withSecret(
6278 const void *XXH_RESTRICT input,
6279 size_t len,
6280 XXH64_hash_t seed64,
6281 const xxh_u8 *XXH_RESTRICT secret,
6282 size_t secretLen) {
6283 (void)seed64;
6284 return XXH3_hashLong_64b_internal(input, len, secret, secretLen, XXH3_accumulate, XXH3_scrambleAcc);
6285 }
6286
6287 /*
6288 * It's preferable for performance that XXH3_hashLong is not inlined,
6289 * as it results in a smaller function for small data, easier to the instruction cache.
6290 * Note that inside this no_inline function, we do inline the internal loop,
6291 * and provide a statically defined secret size to allow optimization of vector loop.
6292 */
6293 XXH_NO_INLINE XXH_PUREF XXH64_hash_t XXH3_hashLong_64b_default(
6294 const void *XXH_RESTRICT input,
6295 size_t len,
6296 XXH64_hash_t seed64,
6297 const xxh_u8 *XXH_RESTRICT secret,
6298 size_t secretLen) {
6299 (void)seed64;
6300 (void)secret;
6301 (void)secretLen;
6302 return XXH3_hashLong_64b_internal(
6303 input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate, XXH3_scrambleAcc);
6304 }
6305
6306 /*
6307 * XXH3_hashLong_64b_withSeed():
6308 * Generate a custom key based on alteration of default XXH3_kSecret with the seed,
6309 * and then use this key for long mode hashing.
6310 *
6311 * This operation is decently fast but nonetheless costs a little bit of time.
6312 * Try to avoid it whenever possible (typically when seed==0).
6313 *
6314 * It's important for performance that XXH3_hashLong is not inlined. Not sure
6315 * why (uop cache maybe?), but the difference is large and easily measurable.
6316 */
6317 XXH_FORCE_INLINE XXH64_hash_t XXH3_hashLong_64b_withSeed_internal(
6318 const void *input,
6319 size_t len,
6320 XXH64_hash_t seed,
6321 XXH3_f_accumulate f_acc,
6322 XXH3_f_scrambleAcc f_scramble,
6323 XXH3_f_initCustomSecret f_initSec) {
6324 # if XXH_SIZE_OPT <= 0
6325 if (seed == 0)
6326 return XXH3_hashLong_64b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), f_acc, f_scramble);
6327 # endif
6328 {
6329 XXH_ALIGN(XXH_SEC_ALIGN) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE];
6330 f_initSec(secret, seed);
6331 return XXH3_hashLong_64b_internal(input, len, secret, sizeof(secret), f_acc, f_scramble);
6332 }
6333 }
6334
6335 /*
6336 * It's important for performance that XXH3_hashLong is not inlined.
6337 */
6338 XXH_NO_INLINE XXH64_hash_t XXH3_hashLong_64b_withSeed(
6339 const void *XXH_RESTRICT input,
6340 size_t len,
6341 XXH64_hash_t seed,
6342 const xxh_u8 *XXH_RESTRICT secret,
6343 size_t secretLen) {
6344 (void)secret;
6345 (void)secretLen;
6346 return XXH3_hashLong_64b_withSeed_internal(
6347 input, len, seed, XXH3_accumulate, XXH3_scrambleAcc, XXH3_initCustomSecret);
6348 }
6349
6350 typedef XXH64_hash_t (
6351 *XXH3_hashLong64_f)(const void *XXH_RESTRICT, size_t, XXH64_hash_t, const xxh_u8 *XXH_RESTRICT, size_t);
6352
6353 XXH_FORCE_INLINE XXH64_hash_t XXH3_64bits_internal(
6354 const void *XXH_RESTRICT input,
6355 size_t len,
6356 XXH64_hash_t seed64,
6357 const void *XXH_RESTRICT secret,
6358 size_t secretLen,
6359 XXH3_hashLong64_f f_hashLong) {
6360 XXH_ASSERT(secretLen >= XXH3_SECRET_SIZE_MIN);
6361 /*
6362 * If an action is to be taken if `secretLen` condition is not respected,
6363 * it should be done here.
6364 * For now, it's a contract pre-condition.
6365 * Adding a check and a branch here would cost performance at every hash.
6366 * Also, note that function signature doesn't offer room to return an error.
6367 */
6368 if (len <= 16)
6369 return XXH3_len_0to16_64b((const xxh_u8 *)input, len, (const xxh_u8 *)secret, seed64);
6370 if (len <= 128)
6371 return XXH3_len_17to128_64b((const xxh_u8 *)input, len, (const xxh_u8 *)secret, secretLen, seed64);
6372 if (len <= XXH3_MIDSIZE_MAX)
6373 return XXH3_len_129to240_64b((const xxh_u8 *)input, len, (const xxh_u8 *)secret, secretLen, seed64);
6374 return f_hashLong(input, len, seed64, (const xxh_u8 *)secret, secretLen);
6375 }
6376
6377 /* === Public entry point === */
6378
6379 /*! @ingroup XXH3_family */
6380 XXH_PUBLIC_API XXH64_hash_t XXH3_64bits(XXH_NOESCAPE const void *input, size_t length) {
6381 return XXH3_64bits_internal(input, length, 0, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_default);
6382 }
6383
6384 /*! @ingroup XXH3_family */
6385 XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSecret(
6386 XXH_NOESCAPE const void *input,
6387 size_t length,
6388 XXH_NOESCAPE const void *secret,
6389 size_t secretSize) {
6390 return XXH3_64bits_internal(input, length, 0, secret, secretSize, XXH3_hashLong_64b_withSecret);
6391 }
6392
6393 /*! @ingroup XXH3_family */
6394 XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSeed(XXH_NOESCAPE const void *input, size_t length, XXH64_hash_t seed) {
6395 return XXH3_64bits_internal(input, length, seed, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_withSeed);
6396 }
6397
6398 XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSecretandSeed(
6399 XXH_NOESCAPE const void *input,
6400 size_t length,
6401 XXH_NOESCAPE const void *secret,
6402 size_t secretSize,
6403 XXH64_hash_t seed) {
6404 if (length <= XXH3_MIDSIZE_MAX)
6405 return XXH3_64bits_internal(input, length, seed, XXH3_kSecret, sizeof(XXH3_kSecret), NULL);
6406 return XXH3_hashLong_64b_withSecret(input, length, seed, (const xxh_u8 *)secret, secretSize);
6407 }
6408
6409 /* === XXH3 streaming === */
6410 # ifndef XXH_NO_STREAM
6411 /*
6412 * Malloc's a pointer that is always aligned to @align.
6413 *
6414 * This must be freed with `XXH_alignedFree()`.
6415 *
6416 * malloc typically guarantees 16 byte alignment on 64-bit systems and 8 byte
6417 * alignment on 32-bit. This isn't enough for the 32 byte aligned loads in AVX2
6418 * or on 32-bit, the 16 byte aligned loads in SSE2 and NEON.
6419 *
6420 * This underalignment previously caused a rather obvious crash which went
6421 * completely unnoticed due to XXH3_createState() not actually being tested.
6422 * Credit to RedSpah for noticing this bug.
6423 *
6424 * The alignment is done manually: Functions like posix_memalign or _mm_malloc
6425 * are avoided: To maintain portability, we would have to write a fallback
6426 * like this anyways, and besides, testing for the existence of library
6427 * functions without relying on external build tools is impossible.
6428 *
6429 * The method is simple: Overallocate, manually align, and store the offset
6430 * to the original behind the returned pointer.
6431 *
6432 * Align must be a power of 2 and 8 <= align <= 128.
6433 */
6434 static XXH_MALLOCF void *XXH_alignedMalloc(size_t s, size_t align) {
6435 XXH_ASSERT(align <= 128 && align >= 8); /* range check */
6436 XXH_ASSERT((align & (align - 1)) == 0); /* power of 2 */
6437 XXH_ASSERT(s != 0 && s < (s + align)); /* empty/overflow */
6438 { /* Overallocate to make room for manual realignment and an offset byte */
6439 xxh_u8 *base = (xxh_u8 *)XXH_malloc(s + align);
6440 if (base != NULL) {
6441 /*
6442 * Get the offset needed to align this pointer.
6443 *
6444 * Even if the returned pointer is aligned, there will always be
6445 * at least one byte to store the offset to the original pointer.
6446 */
6447 size_t offset = align - ((size_t)base & (align - 1)); /* base % align */
6448 /* Add the offset for the now-aligned pointer */
6449 xxh_u8 *ptr = base + offset;
6450
6451 XXH_ASSERT((size_t)ptr % align == 0);
6452
6453 /* Store the offset immediately before the returned pointer. */
6454 ptr[-1] = (xxh_u8)offset;
6455 return ptr;
6456 }
6457 return NULL;
6458 }
6459 }
6460 /*
6461 * Frees an aligned pointer allocated by XXH_alignedMalloc(). Don't pass
6462 * normal malloc'd pointers, XXH_alignedMalloc has a specific data layout.
6463 */
6464 static void XXH_alignedFree(void *p) {
6465 if (p != NULL) {
6466 xxh_u8 *ptr = (xxh_u8 *)p;
6467 /* Get the offset byte we added in XXH_malloc. */
6468 xxh_u8 offset = ptr[-1];
6469 /* Free the original malloc'd pointer */
6470 xxh_u8 *base = ptr - offset;
6471 XXH_free(base);
6472 }
6473 }
6474 /*! @ingroup XXH3_family */
6475 /*!
6476 * @brief Allocate an @ref XXH3_state_t.
6477 *
6478 * @return An allocated pointer of @ref XXH3_state_t on success.
6479 * @return `NULL` on failure.
6480 *
6481 * @note Must be freed with XXH3_freeState().
6482 *
6483 * @see @ref streaming_example "Streaming Example"
6484 */
6485 XXH_PUBLIC_API XXH3_state_t *XXH3_createState(void) {
6486 XXH3_state_t *const state = (XXH3_state_t *)XXH_alignedMalloc(sizeof(XXH3_state_t), 64);
6487 if (state == NULL)
6488 return NULL;
6489 XXH3_INITSTATE(state);
6490 return state;
6491 }
6492
6493 /*! @ingroup XXH3_family */
6494 /*!
6495 * @brief Frees an @ref XXH3_state_t.
6496 *
6497 * @param statePtr A pointer to an @ref XXH3_state_t allocated with @ref XXH3_createState().
6498 *
6499 * @return @ref XXH_OK.
6500 *
6501 * @note Must be allocated with XXH3_createState().
6502 *
6503 * @see @ref streaming_example "Streaming Example"
6504 */
6505 XXH_PUBLIC_API XXH_errorcode XXH3_freeState(XXH3_state_t *statePtr) {
6506 XXH_alignedFree(statePtr);
6507 return XXH_OK;
6508 }
6509
6510 /*! @ingroup XXH3_family */
6511 XXH_PUBLIC_API void XXH3_copyState(XXH_NOESCAPE XXH3_state_t *dst_state, XXH_NOESCAPE const XXH3_state_t *src_state) {
6512 XXH_memcpy(dst_state, src_state, sizeof(*dst_state));
6513 }
6514
6515 static void XXH3_reset_internal(XXH3_state_t *statePtr, XXH64_hash_t seed, const void *secret, size_t secretSize) {
6516 size_t const initStart = offsetof(XXH3_state_t, bufferedSize);
6517 size_t const initLength = offsetof(XXH3_state_t, nbStripesPerBlock) - initStart;
6518 XXH_ASSERT(offsetof(XXH3_state_t, nbStripesPerBlock) > initStart);
6519 XXH_ASSERT(statePtr != NULL);
6520 /* set members from bufferedSize to nbStripesPerBlock (excluded) to 0 */
6521 XXH_memset((char *)statePtr + initStart, 0, initLength);
6522 statePtr->acc[0] = XXH_PRIME32_3;
6523 statePtr->acc[1] = XXH_PRIME64_1;
6524 statePtr->acc[2] = XXH_PRIME64_2;
6525 statePtr->acc[3] = XXH_PRIME64_3;
6526 statePtr->acc[4] = XXH_PRIME64_4;
6527 statePtr->acc[5] = XXH_PRIME32_2;
6528 statePtr->acc[6] = XXH_PRIME64_5;
6529 statePtr->acc[7] = XXH_PRIME32_1;
6530 statePtr->seed = seed;
6531 statePtr->useSeed = (seed != 0);
6532 statePtr->extSecret = (const unsigned char *)secret;
6533 XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
6534 statePtr->secretLimit = secretSize - XXH_STRIPE_LEN;
6535 statePtr->nbStripesPerBlock = statePtr->secretLimit / XXH_SECRET_CONSUME_RATE;
6536 }
6537
6538 /*! @ingroup XXH3_family */
6539 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset(XXH_NOESCAPE XXH3_state_t *statePtr) {
6540 if (statePtr == NULL)
6541 return XXH_ERROR;
6542 XXH3_reset_internal(statePtr, 0, XXH3_kSecret, XXH_SECRET_DEFAULT_SIZE);
6543 return XXH_OK;
6544 }
6545
6546 /*! @ingroup XXH3_family */
6547 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSecret(
6548 XXH_NOESCAPE XXH3_state_t *statePtr,
6549 XXH_NOESCAPE const void *secret,
6550 size_t secretSize) {
6551 if (statePtr == NULL)
6552 return XXH_ERROR;
6553 XXH3_reset_internal(statePtr, 0, secret, secretSize);
6554 if (secret == NULL)
6555 return XXH_ERROR;
6556 if (secretSize < XXH3_SECRET_SIZE_MIN)
6557 return XXH_ERROR;
6558 return XXH_OK;
6559 }
6560
6561 /*! @ingroup XXH3_family */
6562 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t *statePtr, XXH64_hash_t seed) {
6563 if (statePtr == NULL)
6564 return XXH_ERROR;
6565 if (seed == 0)
6566 return XXH3_64bits_reset(statePtr);
6567 if ((seed != statePtr->seed) || (statePtr->extSecret != NULL))
6568 XXH3_initCustomSecret(statePtr->customSecret, seed);
6569 XXH3_reset_internal(statePtr, seed, NULL, XXH_SECRET_DEFAULT_SIZE);
6570 return XXH_OK;
6571 }
6572
6573 /*! @ingroup XXH3_family */
6574 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSecretandSeed(
6575 XXH_NOESCAPE XXH3_state_t *statePtr,
6576 XXH_NOESCAPE const void *secret,
6577 size_t secretSize,
6578 XXH64_hash_t seed64) {
6579 if (statePtr == NULL)
6580 return XXH_ERROR;
6581 if (secret == NULL)
6582 return XXH_ERROR;
6583 if (secretSize < XXH3_SECRET_SIZE_MIN)
6584 return XXH_ERROR;
6585 XXH3_reset_internal(statePtr, seed64, secret, secretSize);
6586 statePtr->useSeed = 1; /* always, even if seed64==0 */
6587 return XXH_OK;
6588 }
6589
6590 /*!
6591 * @internal
6592 * @brief Processes a large input for XXH3_update() and XXH3_digest_long().
6593 *
6594 * Unlike XXH3_hashLong_internal_loop(), this can process data that overlaps a block.
6595 *
6596 * @param acc Pointer to the 8 accumulator lanes
6597 * @param nbStripesSoFarPtr In/out pointer to the number of leftover stripes in the block*
6598 * @param nbStripesPerBlock Number of stripes in a block
6599 * @param input Input pointer
6600 * @param nbStripes Number of stripes to process
6601 * @param secret Secret pointer
6602 * @param secretLimit Offset of the last block in @p secret
6603 * @param f_acc Pointer to an XXH3_accumulate implementation
6604 * @param f_scramble Pointer to an XXH3_scrambleAcc implementation
6605 * @return Pointer past the end of @p input after processing
6606 */
6607 XXH_FORCE_INLINE const xxh_u8 *XXH3_consumeStripes(
6608 xxh_u64 *XXH_RESTRICT acc,
6609 size_t *XXH_RESTRICT nbStripesSoFarPtr,
6610 size_t nbStripesPerBlock,
6611 const xxh_u8 *XXH_RESTRICT input,
6612 size_t nbStripes,
6613 const xxh_u8 *XXH_RESTRICT secret,
6614 size_t secretLimit,
6615 XXH3_f_accumulate f_acc,
6616 XXH3_f_scrambleAcc f_scramble) {
6617 const xxh_u8 *initialSecret = secret + *nbStripesSoFarPtr * XXH_SECRET_CONSUME_RATE;
6618 /* Process full blocks */
6619 if (nbStripes >= (nbStripesPerBlock - *nbStripesSoFarPtr)) {
6620 /* Process the initial partial block... */
6621 size_t nbStripesThisIter = nbStripesPerBlock - *nbStripesSoFarPtr;
6622
6623 do {
6624 /* Accumulate and scramble */
6625 f_acc(acc, input, initialSecret, nbStripesThisIter);
6626 f_scramble(acc, secret + secretLimit);
6627 input += nbStripesThisIter * XXH_STRIPE_LEN;
6628 nbStripes -= nbStripesThisIter;
6629 /* Then continue the loop with the full block size */
6630 nbStripesThisIter = nbStripesPerBlock;
6631 initialSecret = secret;
6632 } while (nbStripes >= nbStripesPerBlock);
6633 *nbStripesSoFarPtr = 0;
6634 }
6635 /* Process a partial block */
6636 if (nbStripes > 0) {
6637 f_acc(acc, input, initialSecret, nbStripes);
6638 input += nbStripes * XXH_STRIPE_LEN;
6639 *nbStripesSoFarPtr += nbStripes;
6640 }
6641 /* Return end pointer */
6642 return input;
6643 }
6644
6645 # ifndef XXH3_STREAM_USE_STACK
6646 # if XXH_SIZE_OPT <= 0 && !defined(__clang__) /* clang doesn't need additional stack space */
6647 # define XXH3_STREAM_USE_STACK 1
6648 # endif
6649 # endif
6650 /* This function accepts f_acc and f_scramble as function pointers,
6651 * making it possible to implement multiple variants with different acc & scramble stages.
6652 * This is notably useful to implement multiple vector variants with different intrinsics.
6653 */
6654 XXH_FORCE_INLINE XXH_errorcode XXH3_update(
6655 XXH3_state_t *XXH_RESTRICT const state,
6656 const xxh_u8 *XXH_RESTRICT input,
6657 size_t len,
6658 XXH3_f_accumulate f_acc,
6659 XXH3_f_scrambleAcc f_scramble) {
6660 if (input == NULL) {
6661 XXH_ASSERT(len == 0);
6662 return XXH_OK;
6663 }
6664
6665 XXH_ASSERT(state != NULL);
6666 state->totalLen += len;
6667
6668 /* small input : just fill in tmp buffer */
6669 XXH_ASSERT(state->bufferedSize <= XXH3_INTERNALBUFFER_SIZE);
6670 if (len <= XXH3_INTERNALBUFFER_SIZE - state->bufferedSize) {
6671 XXH_memcpy(state->buffer + state->bufferedSize, input, len);
6672 state->bufferedSize += (XXH32_hash_t)len;
6673 return XXH_OK;
6674 }
6675
6676 {
6677 const xxh_u8 *const bEnd = input + len;
6678 const unsigned char *const secret = (state->extSecret == NULL) ? state->customSecret : state->extSecret;
6679 # if defined(XXH3_STREAM_USE_STACK) && XXH3_STREAM_USE_STACK >= 1
6680 /* For some reason, gcc and MSVC seem to suffer greatly
6681 * when operating accumulators directly into state.
6682 * Operating into stack space seems to enable proper optimization.
6683 * clang, on the other hand, doesn't seem to need this trick */
6684 XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[8];
6685 XXH_memcpy(acc, state->acc, sizeof(acc));
6686 # else
6687 xxh_u64 *XXH_RESTRICT const acc = state->acc;
6688 # endif
6689
6690 /* total input is now > XXH3_INTERNALBUFFER_SIZE */
6691 # define XXH3_INTERNALBUFFER_STRIPES (XXH3_INTERNALBUFFER_SIZE / XXH_STRIPE_LEN)
6692 XXH_STATIC_ASSERT(XXH3_INTERNALBUFFER_SIZE % XXH_STRIPE_LEN == 0); /* clean multiple */
6693
6694 /*
6695 * Internal buffer is partially filled (always, except at beginning)
6696 * Complete it, then consume it.
6697 */
6698 if (state->bufferedSize) {
6699 size_t const loadSize = XXH3_INTERNALBUFFER_SIZE - state->bufferedSize;
6700 XXH_memcpy(state->buffer + state->bufferedSize, input, loadSize);
6701 input += loadSize;
6702 XXH3_consumeStripes(
6703 acc,
6704 &state->nbStripesSoFar,
6705 state->nbStripesPerBlock,
6706 state->buffer,
6707 XXH3_INTERNALBUFFER_STRIPES,
6708 secret,
6709 state->secretLimit,
6710 f_acc,
6711 f_scramble);
6712 state->bufferedSize = 0;
6713 }
6714 XXH_ASSERT(input < bEnd);
6715 if (bEnd - input > XXH3_INTERNALBUFFER_SIZE) {
6716 size_t nbStripes = (size_t)(bEnd - 1 - input) / XXH_STRIPE_LEN;
6717 input = XXH3_consumeStripes(
6718 acc,
6719 &state->nbStripesSoFar,
6720 state->nbStripesPerBlock,
6721 input,
6722 nbStripes,
6723 secret,
6724 state->secretLimit,
6725 f_acc,
6726 f_scramble);
6727 XXH_memcpy(state->buffer + sizeof(state->buffer) - XXH_STRIPE_LEN, input - XXH_STRIPE_LEN, XXH_STRIPE_LEN);
6728 }
6729 /* Some remaining input (always) : buffer it */
6730 XXH_ASSERT(input < bEnd);
6731 XXH_ASSERT(bEnd - input <= XXH3_INTERNALBUFFER_SIZE);
6732 XXH_ASSERT(state->bufferedSize == 0);
6733 XXH_memcpy(state->buffer, input, (size_t)(bEnd - input));
6734 state->bufferedSize = (XXH32_hash_t)(bEnd - input);
6735 # if defined(XXH3_STREAM_USE_STACK) && XXH3_STREAM_USE_STACK >= 1
6736 /* save stack accumulators into state */
6737 XXH_memcpy(state->acc, acc, sizeof(acc));
6738 # endif
6739 }
6740
6741 return XXH_OK;
6742 }
6743
6744 /*
6745 * Both XXH3_64bits_update and XXH3_128bits_update use this routine.
6746 */
6747 XXH_NO_INLINE XXH_errorcode
6748 XXH3_update_regular(XXH_NOESCAPE XXH3_state_t *state, XXH_NOESCAPE const void *input, size_t len) {
6749 return XXH3_update(state, (const xxh_u8 *)input, len, XXH3_accumulate, XXH3_scrambleAcc);
6750 }
6751
6752 /*! @ingroup XXH3_family */
6753 XXH_PUBLIC_API XXH_errorcode
6754 XXH3_64bits_update(XXH_NOESCAPE XXH3_state_t *state, XXH_NOESCAPE const void *input, size_t len) {
6755 return XXH3_update_regular(state, input, len);
6756 }
6757
6758 XXH_FORCE_INLINE void XXH3_digest_long(XXH64_hash_t *acc, const XXH3_state_t *state, const unsigned char *secret) {
6759 xxh_u8 lastStripe[XXH_STRIPE_LEN];
6760 const xxh_u8 *lastStripePtr;
6761
6762 /*
6763 * Digest on a local copy. This way, the state remains unaltered, and it can
6764 * continue ingesting more input afterwards.
6765 */
6766 XXH_memcpy(acc, state->acc, sizeof(state->acc));
6767 if (state->bufferedSize >= XXH_STRIPE_LEN) {
6768 /* Consume remaining stripes then point to remaining data in buffer */
6769 size_t const nbStripes = (state->bufferedSize - 1) / XXH_STRIPE_LEN;
6770 size_t nbStripesSoFar = state->nbStripesSoFar;
6771 XXH3_consumeStripes(
6772 acc,
6773 &nbStripesSoFar,
6774 state->nbStripesPerBlock,
6775 state->buffer,
6776 nbStripes,
6777 secret,
6778 state->secretLimit,
6779 XXH3_accumulate,
6780 XXH3_scrambleAcc);
6781 lastStripePtr = state->buffer + state->bufferedSize - XXH_STRIPE_LEN;
6782 } else { /* bufferedSize < XXH_STRIPE_LEN */
6783 /* Copy to temp buffer */
6784 size_t const catchupSize = XXH_STRIPE_LEN - state->bufferedSize;
6785 XXH_ASSERT(state->bufferedSize > 0); /* there is always some input buffered */
6786 XXH_memcpy(lastStripe, state->buffer + sizeof(state->buffer) - catchupSize, catchupSize);
6787 XXH_memcpy(lastStripe + catchupSize, state->buffer, state->bufferedSize);
6788 lastStripePtr = lastStripe;
6789 }
6790 /* Last stripe */
6791 XXH3_accumulate_512(acc, lastStripePtr, secret + state->secretLimit - XXH_SECRET_LASTACC_START);
6792 }
6793
6794 /*! @ingroup XXH3_family */
6795 XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_digest(XXH_NOESCAPE const XXH3_state_t *state) {
6796 const unsigned char *const secret = (state->extSecret == NULL) ? state->customSecret : state->extSecret;
6797 if (state->totalLen > XXH3_MIDSIZE_MAX) {
6798 XXH_ALIGN(XXH_ACC_ALIGN) XXH64_hash_t acc[XXH_ACC_NB];
6799 XXH3_digest_long(acc, state, secret);
6800 return XXH3_finalizeLong_64b(acc, secret, (xxh_u64)state->totalLen);
6801 }
6802 /* totalLen <= XXH3_MIDSIZE_MAX: digesting a short input */
6803 if (state->useSeed)
6804 return XXH3_64bits_withSeed(state->buffer, (size_t)state->totalLen, state->seed);
6805 return XXH3_64bits_withSecret(
6806 state->buffer, (size_t)(state->totalLen), secret, state->secretLimit + XXH_STRIPE_LEN);
6807 }
6808 # endif /* !XXH_NO_STREAM */
6809
6810 /* ==========================================
6811 * XXH3 128 bits (a.k.a XXH128)
6812 * ==========================================
6813 * XXH3's 128-bit variant has better mixing and strength than the 64-bit variant,
6814 * even without counting the significantly larger output size.
6815 *
6816 * For example, extra steps are taken to avoid the seed-dependent collisions
6817 * in 17-240 byte inputs (See XXH3_mix16B and XXH128_mix32B).
6818 *
6819 * This strength naturally comes at the cost of some speed, especially on short
6820 * lengths. Note that longer hashes are about as fast as the 64-bit version
6821 * due to it using only a slight modification of the 64-bit loop.
6822 *
6823 * XXH128 is also more oriented towards 64-bit machines. It is still extremely
6824 * fast for a _128-bit_ hash on 32-bit (it usually clears XXH64).
6825 */
6826
6827 XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t
6828 XXH3_len_1to3_128b(const xxh_u8 *input, size_t len, const xxh_u8 *secret, XXH64_hash_t seed) {
6829 /* A doubled version of 1to3_64b with different constants. */
6830 XXH_ASSERT(input != NULL);
6831 XXH_ASSERT(1 <= len && len <= 3);
6832 XXH_ASSERT(secret != NULL);
6833 /*
6834 * len = 1: combinedl = { input[0], 0x01, input[0], input[0] }
6835 * len = 2: combinedl = { input[1], 0x02, input[0], input[1] }
6836 * len = 3: combinedl = { input[2], 0x03, input[0], input[1] }
6837 */
6838 {
6839 xxh_u8 const c1 = input[0];
6840 xxh_u8 const c2 = input[len >> 1];
6841 xxh_u8 const c3 = input[len - 1];
6842 xxh_u32 const combinedl = ((xxh_u32)c1 << 16) | ((xxh_u32)c2 << 24) | ((xxh_u32)c3 << 0) | ((xxh_u32)len << 8);
6843 xxh_u32 const combinedh = XXH_rotl32(XXH_swap32(combinedl), 13);
6844 xxh_u64 const bitflipl = (XXH_readLE32(secret) ^ XXH_readLE32(secret + 4)) + seed;
6845 xxh_u64 const bitfliph = (XXH_readLE32(secret + 8) ^ XXH_readLE32(secret + 12)) - seed;
6846 xxh_u64 const keyed_lo = (xxh_u64)combinedl ^ bitflipl;
6847 xxh_u64 const keyed_hi = (xxh_u64)combinedh ^ bitfliph;
6848 XXH128_hash_t h128;
6849 h128.low64 = XXH64_avalanche(keyed_lo);
6850 h128.high64 = XXH64_avalanche(keyed_hi);
6851 return h128;
6852 }
6853 }
6854
6855 XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t
6856 XXH3_len_4to8_128b(const xxh_u8 *input, size_t len, const xxh_u8 *secret, XXH64_hash_t seed) {
6857 XXH_ASSERT(input != NULL);
6858 XXH_ASSERT(secret != NULL);
6859 XXH_ASSERT(4 <= len && len <= 8);
6860 seed ^= (xxh_u64)XXH_swap32((xxh_u32)seed) << 32;
6861 {
6862 xxh_u32 const input_lo = XXH_readLE32(input);
6863 xxh_u32 const input_hi = XXH_readLE32(input + len - 4);
6864 xxh_u64 const input_64 = input_lo + ((xxh_u64)input_hi << 32);
6865 xxh_u64 const bitflip = (XXH_readLE64(secret + 16) ^ XXH_readLE64(secret + 24)) + seed;
6866 xxh_u64 const keyed = input_64 ^ bitflip;
6867
6868 /* Shift len to the left to ensure it is even, this avoids even multiplies. */
6869 XXH128_hash_t m128 = XXH_mult64to128(keyed, XXH_PRIME64_1 + (len << 2));
6870
6871 m128.high64 += (m128.low64 << 1);
6872 m128.low64 ^= (m128.high64 >> 3);
6873
6874 m128.low64 = XXH_xorshift64(m128.low64, 35);
6875 m128.low64 *= PRIME_MX2;
6876 m128.low64 = XXH_xorshift64(m128.low64, 28);
6877 m128.high64 = XXH3_avalanche(m128.high64);
6878 return m128;
6879 }
6880 }
6881
6882 XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t
6883 XXH3_len_9to16_128b(const xxh_u8 *input, size_t len, const xxh_u8 *secret, XXH64_hash_t seed) {
6884 XXH_ASSERT(input != NULL);
6885 XXH_ASSERT(secret != NULL);
6886 XXH_ASSERT(9 <= len && len <= 16);
6887 {
6888 xxh_u64 const bitflipl = (XXH_readLE64(secret + 32) ^ XXH_readLE64(secret + 40)) - seed;
6889 xxh_u64 const bitfliph = (XXH_readLE64(secret + 48) ^ XXH_readLE64(secret + 56)) + seed;
6890 xxh_u64 const input_lo = XXH_readLE64(input);
6891 xxh_u64 input_hi = XXH_readLE64(input + len - 8);
6892 XXH128_hash_t m128 = XXH_mult64to128(input_lo ^ input_hi ^ bitflipl, XXH_PRIME64_1);
6893 /*
6894 * Put len in the middle of m128 to ensure that the length gets mixed to
6895 * both the low and high bits in the 128x64 multiply below.
6896 */
6897 m128.low64 += (xxh_u64)(len - 1) << 54;
6898 input_hi ^= bitfliph;
6899 /*
6900 * Add the high 32 bits of input_hi to the high 32 bits of m128, then
6901 * add the long product of the low 32 bits of input_hi and XXH_PRIME32_2 to
6902 * the high 64 bits of m128.
6903 *
6904 * The best approach to this operation is different on 32-bit and 64-bit.
6905 */
6906 if (sizeof(void *) < sizeof(xxh_u64)) { /* 32-bit */
6907 /*
6908 * 32-bit optimized version, which is more readable.
6909 *
6910 * On 32-bit, it removes an ADC and delays a dependency between the two
6911 * halves of m128.high64, but it generates an extra mask on 64-bit.
6912 */
6913 m128.high64 += (input_hi & 0xFFFFFFFF00000000ULL) + XXH_mult32to64((xxh_u32)input_hi, XXH_PRIME32_2);
6914 } else {
6915 /*
6916 * 64-bit optimized (albeit more confusing) version.
6917 *
6918 * Uses some properties of addition and multiplication to remove the mask:
6919 *
6920 * Let:
6921 * a = input_hi.lo = (input_hi & 0x00000000FFFFFFFF)
6922 * b = input_hi.hi = (input_hi & 0xFFFFFFFF00000000)
6923 * c = XXH_PRIME32_2
6924 *
6925 * a + (b * c)
6926 * Inverse Property: x + y - x == y
6927 * a + (b * (1 + c - 1))
6928 * Distributive Property: x * (y + z) == (x * y) + (x * z)
6929 * a + (b * 1) + (b * (c - 1))
6930 * Identity Property: x * 1 == x
6931 * a + b + (b * (c - 1))
6932 *
6933 * Substitute a, b, and c:
6934 * input_hi.hi + input_hi.lo + ((xxh_u64)input_hi.lo * (XXH_PRIME32_2 - 1))
6935 *
6936 * Since input_hi.hi + input_hi.lo == input_hi, we get this:
6937 * input_hi + ((xxh_u64)input_hi.lo * (XXH_PRIME32_2 - 1))
6938 */
6939 m128.high64 += input_hi + XXH_mult32to64((xxh_u32)input_hi, XXH_PRIME32_2 - 1);
6940 }
6941 /* m128 ^= XXH_swap64(m128 >> 64); */
6942 m128.low64 ^= XXH_swap64(m128.high64);
6943
6944 { /* 128x64 multiply: h128 = m128 * XXH_PRIME64_2; */
6945 XXH128_hash_t h128 = XXH_mult64to128(m128.low64, XXH_PRIME64_2);
6946 h128.high64 += m128.high64 * XXH_PRIME64_2;
6947
6948 h128.low64 = XXH3_avalanche(h128.low64);
6949 h128.high64 = XXH3_avalanche(h128.high64);
6950 return h128;
6951 }
6952 }
6953 }
6954
6955 /*
6956 * Assumption: `secret` size is >= XXH3_SECRET_SIZE_MIN
6957 */
6958 XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t
6959 XXH3_len_0to16_128b(const xxh_u8 *input, size_t len, const xxh_u8 *secret, XXH64_hash_t seed) {
6960 XXH_ASSERT(len <= 16);
6961 {
6962 if (len > 8)
6963 return XXH3_len_9to16_128b(input, len, secret, seed);
6964 if (len >= 4)
6965 return XXH3_len_4to8_128b(input, len, secret, seed);
6966 if (len)
6967 return XXH3_len_1to3_128b(input, len, secret, seed);
6968 {
6969 XXH128_hash_t h128;
6970 xxh_u64 const bitflipl = XXH_readLE64(secret + 64) ^ XXH_readLE64(secret + 72);
6971 xxh_u64 const bitfliph = XXH_readLE64(secret + 80) ^ XXH_readLE64(secret + 88);
6972 h128.low64 = XXH64_avalanche(seed ^ bitflipl);
6973 h128.high64 = XXH64_avalanche(seed ^ bitfliph);
6974 return h128;
6975 }
6976 }
6977 }
6978
6979 /*
6980 * A bit slower than XXH3_mix16B, but handles multiply by zero better.
6981 */
6982 XXH_FORCE_INLINE XXH128_hash_t XXH128_mix32B(
6983 XXH128_hash_t acc,
6984 const xxh_u8 *input_1,
6985 const xxh_u8 *input_2,
6986 const xxh_u8 *secret,
6987 XXH64_hash_t seed) {
6988 acc.low64 += XXH3_mix16B(input_1, secret + 0, seed);
6989 acc.low64 ^= XXH_readLE64(input_2) + XXH_readLE64(input_2 + 8);
6990 acc.high64 += XXH3_mix16B(input_2, secret + 16, seed);
6991 acc.high64 ^= XXH_readLE64(input_1) + XXH_readLE64(input_1 + 8);
6992 return acc;
6993 }
6994
6995 XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t XXH3_len_17to128_128b(
6996 const xxh_u8 *XXH_RESTRICT input,
6997 size_t len,
6998 const xxh_u8 *XXH_RESTRICT secret,
6999 size_t secretSize,
7000 XXH64_hash_t seed) {
7001 XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
7002 (void)secretSize;
7003 XXH_ASSERT(16 < len && len <= 128);
7004
7005 {
7006 XXH128_hash_t acc;
7007 acc.low64 = len * XXH_PRIME64_1;
7008 acc.high64 = 0;
7009
7010 # if XXH_SIZE_OPT >= 1
7011 {
7012 /* Smaller, but slightly slower. */
7013 unsigned int i = (unsigned int)(len - 1) / 32;
7014 do {
7015 acc = XXH128_mix32B(acc, input + 16 * i, input + len - 16 * (i + 1), secret + 32 * i, seed);
7016 } while (i-- != 0);
7017 }
7018 # else
7019 if (len > 32) {
7020 if (len > 64) {
7021 if (len > 96) {
7022 acc = XXH128_mix32B(acc, input + 48, input + len - 64, secret + 96, seed);
7023 }
7024 acc = XXH128_mix32B(acc, input + 32, input + len - 48, secret + 64, seed);
7025 }
7026 acc = XXH128_mix32B(acc, input + 16, input + len - 32, secret + 32, seed);
7027 }
7028 acc = XXH128_mix32B(acc, input, input + len - 16, secret, seed);
7029 # endif
7030 {
7031 XXH128_hash_t h128;
7032 h128.low64 = acc.low64 + acc.high64;
7033 h128.high64 = (acc.low64 * XXH_PRIME64_1) + (acc.high64 * XXH_PRIME64_4) + ((len - seed) * XXH_PRIME64_2);
7034 h128.low64 = XXH3_avalanche(h128.low64);
7035 h128.high64 = (XXH64_hash_t)0 - XXH3_avalanche(h128.high64);
7036 return h128;
7037 }
7038 }
7039 }
7040
7041 XXH_NO_INLINE XXH_PUREF XXH128_hash_t XXH3_len_129to240_128b(
7042 const xxh_u8 *XXH_RESTRICT input,
7043 size_t len,
7044 const xxh_u8 *XXH_RESTRICT secret,
7045 size_t secretSize,
7046 XXH64_hash_t seed) {
7047 XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
7048 (void)secretSize;
7049 XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX);
7050
7051 {
7052 XXH128_hash_t acc;
7053 unsigned i;
7054 acc.low64 = len * XXH_PRIME64_1;
7055 acc.high64 = 0;
7056 /*
7057 * We set as `i` as offset + 32. We do this so that unchanged
7058 * `len` can be used as upper bound. This reaches a sweet spot
7059 * where both x86 and aarch64 get simple agen and good codegen
7060 * for the loop.
7061 */
7062 for (i = 32; i < 160; i += 32) {
7063 acc = XXH128_mix32B(acc, input + i - 32, input + i - 16, secret + i - 32, seed);
7064 }
7065 acc.low64 = XXH3_avalanche(acc.low64);
7066 acc.high64 = XXH3_avalanche(acc.high64);
7067 /*
7068 * NB: `i <= len` will duplicate the last 32-bytes if
7069 * len % 32 was zero. This is an unfortunate necessity to keep
7070 * the hash result stable.
7071 */
7072 for (i = 160; i <= len; i += 32) {
7073 acc = XXH128_mix32B(acc, input + i - 32, input + i - 16, secret + XXH3_MIDSIZE_STARTOFFSET + i - 160, seed);
7074 }
7075 /* last bytes */
7076 acc = XXH128_mix32B(
7077 acc,
7078 input + len - 16,
7079 input + len - 32,
7080 secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET - 16,
7081 (XXH64_hash_t)0 - seed);
7082
7083 {
7084 XXH128_hash_t h128;
7085 h128.low64 = acc.low64 + acc.high64;
7086 h128.high64 = (acc.low64 * XXH_PRIME64_1) + (acc.high64 * XXH_PRIME64_4) + ((len - seed) * XXH_PRIME64_2);
7087 h128.low64 = XXH3_avalanche(h128.low64);
7088 h128.high64 = (XXH64_hash_t)0 - XXH3_avalanche(h128.high64);
7089 return h128;
7090 }
7091 }
7092 }
7093
7094 static XXH_PUREF XXH128_hash_t XXH3_finalizeLong_128b(
7095 const xxh_u64 *XXH_RESTRICT acc,
7096 const xxh_u8 *XXH_RESTRICT secret,
7097 size_t secretSize,
7098 xxh_u64 len) {
7099 XXH128_hash_t h128;
7100 h128.low64 = XXH3_finalizeLong_64b(acc, secret, len);
7101 h128.high64 =
7102 XXH3_mergeAccs(acc, secret + secretSize - XXH_STRIPE_LEN - XXH_SECRET_MERGEACCS_START, ~(len * XXH_PRIME64_2));
7103 return h128;
7104 }
7105
7106 XXH_FORCE_INLINE XXH128_hash_t XXH3_hashLong_128b_internal(
7107 const void *XXH_RESTRICT input,
7108 size_t len,
7109 const xxh_u8 *XXH_RESTRICT secret,
7110 size_t secretSize,
7111 XXH3_f_accumulate f_acc,
7112 XXH3_f_scrambleAcc f_scramble) {
7113 XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[XXH_ACC_NB] = XXH3_INIT_ACC;
7114
7115 XXH3_hashLong_internal_loop(acc, (const xxh_u8 *)input, len, secret, secretSize, f_acc, f_scramble);
7116
7117 /* converge into final hash */
7118 XXH_STATIC_ASSERT(sizeof(acc) == 64);
7119 XXH_ASSERT(secretSize >= sizeof(acc) + XXH_SECRET_MERGEACCS_START);
7120 return XXH3_finalizeLong_128b(acc, secret, secretSize, (xxh_u64)len);
7121 }
7122
7123 /*
7124 * It's important for performance that XXH3_hashLong() is not inlined.
7125 */
7126 XXH_NO_INLINE XXH_PUREF XXH128_hash_t XXH3_hashLong_128b_default(
7127 const void *XXH_RESTRICT input,
7128 size_t len,
7129 XXH64_hash_t seed64,
7130 const void *XXH_RESTRICT secret,
7131 size_t secretLen) {
7132 (void)seed64;
7133 (void)secret;
7134 (void)secretLen;
7135 return XXH3_hashLong_128b_internal(
7136 input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate, XXH3_scrambleAcc);
7137 }
7138
7139 /*
7140 * It's important for performance to pass @p secretLen (when it's static)
7141 * to the compiler, so that it can properly optimize the vectorized loop.
7142 *
7143 * When the secret size is unknown, or on GCC 12 where the mix of NO_INLINE and FORCE_INLINE
7144 * breaks -Og, this is XXH_NO_INLINE.
7145 */
7146 XXH3_WITH_SECRET_INLINE XXH128_hash_t XXH3_hashLong_128b_withSecret(
7147 const void *XXH_RESTRICT input,
7148 size_t len,
7149 XXH64_hash_t seed64,
7150 const void *XXH_RESTRICT secret,
7151 size_t secretLen) {
7152 (void)seed64;
7153 return XXH3_hashLong_128b_internal(
7154 input, len, (const xxh_u8 *)secret, secretLen, XXH3_accumulate, XXH3_scrambleAcc);
7155 }
7156
7157 XXH_FORCE_INLINE XXH128_hash_t XXH3_hashLong_128b_withSeed_internal(
7158 const void *XXH_RESTRICT input,
7159 size_t len,
7160 XXH64_hash_t seed64,
7161 XXH3_f_accumulate f_acc,
7162 XXH3_f_scrambleAcc f_scramble,
7163 XXH3_f_initCustomSecret f_initSec) {
7164 if (seed64 == 0)
7165 return XXH3_hashLong_128b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), f_acc, f_scramble);
7166 {
7167 XXH_ALIGN(XXH_SEC_ALIGN) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE];
7168 f_initSec(secret, seed64);
7169 return XXH3_hashLong_128b_internal(input, len, (const xxh_u8 *)secret, sizeof(secret), f_acc, f_scramble);
7170 }
7171 }
7172
7173 /*
7174 * It's important for performance that XXH3_hashLong is not inlined.
7175 */
7176 XXH_NO_INLINE XXH128_hash_t XXH3_hashLong_128b_withSeed(
7177 const void *input,
7178 size_t len,
7179 XXH64_hash_t seed64,
7180 const void *XXH_RESTRICT secret,
7181 size_t secretLen) {
7182 (void)secret;
7183 (void)secretLen;
7184 return XXH3_hashLong_128b_withSeed_internal(
7185 input, len, seed64, XXH3_accumulate, XXH3_scrambleAcc, XXH3_initCustomSecret);
7186 }
7187
7188 typedef XXH128_hash_t (
7189 *XXH3_hashLong128_f)(const void *XXH_RESTRICT, size_t, XXH64_hash_t, const void *XXH_RESTRICT, size_t);
7190
7191 XXH_FORCE_INLINE XXH128_hash_t XXH3_128bits_internal(
7192 const void *input,
7193 size_t len,
7194 XXH64_hash_t seed64,
7195 const void *XXH_RESTRICT secret,
7196 size_t secretLen,
7197 XXH3_hashLong128_f f_hl128) {
7198 XXH_ASSERT(secretLen >= XXH3_SECRET_SIZE_MIN);
7199 /*
7200 * If an action is to be taken if `secret` conditions are not respected,
7201 * it should be done here.
7202 * For now, it's a contract pre-condition.
7203 * Adding a check and a branch here would cost performance at every hash.
7204 */
7205 if (len <= 16)
7206 return XXH3_len_0to16_128b((const xxh_u8 *)input, len, (const xxh_u8 *)secret, seed64);
7207 if (len <= 128)
7208 return XXH3_len_17to128_128b((const xxh_u8 *)input, len, (const xxh_u8 *)secret, secretLen, seed64);
7209 if (len <= XXH3_MIDSIZE_MAX)
7210 return XXH3_len_129to240_128b((const xxh_u8 *)input, len, (const xxh_u8 *)secret, secretLen, seed64);
7211 return f_hl128(input, len, seed64, secret, secretLen);
7212 }
7213
7214 /* === Public XXH128 API === */
7215
7216 /*! @ingroup XXH3_family */
7217 XXH_PUBLIC_API XXH128_hash_t XXH3_128bits(XXH_NOESCAPE const void *input, size_t len) {
7218 return XXH3_128bits_internal(input, len, 0, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_128b_default);
7219 }
7220
7221 /*! @ingroup XXH3_family */
7222 XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_withSecret(
7223 XXH_NOESCAPE const void *input,
7224 size_t len,
7225 XXH_NOESCAPE const void *secret,
7226 size_t secretSize) {
7227 return XXH3_128bits_internal(input, len, 0, (const xxh_u8 *)secret, secretSize, XXH3_hashLong_128b_withSecret);
7228 }
7229
7230 /*! @ingroup XXH3_family */
7231 XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_withSeed(XXH_NOESCAPE const void *input, size_t len, XXH64_hash_t seed) {
7232 return XXH3_128bits_internal(input, len, seed, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_128b_withSeed);
7233 }
7234
7235 /*! @ingroup XXH3_family */
7236 XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_withSecretandSeed(
7237 XXH_NOESCAPE const void *input,
7238 size_t len,
7239 XXH_NOESCAPE const void *secret,
7240 size_t secretSize,
7241 XXH64_hash_t seed) {
7242 if (len <= XXH3_MIDSIZE_MAX)
7243 return XXH3_128bits_internal(input, len, seed, XXH3_kSecret, sizeof(XXH3_kSecret), NULL);
7244 return XXH3_hashLong_128b_withSecret(input, len, seed, secret, secretSize);
7245 }
7246
7247 /*! @ingroup XXH3_family */
7248 XXH_PUBLIC_API XXH128_hash_t XXH128(XXH_NOESCAPE const void *input, size_t len, XXH64_hash_t seed) {
7249 return XXH3_128bits_withSeed(input, len, seed);
7250 }
7251
7252 /* === XXH3 128-bit streaming === */
7253 # ifndef XXH_NO_STREAM
7254 /*
7255 * All initialization and update functions are identical to 64-bit streaming variant.
7256 * The only difference is the finalization routine.
7257 */
7258
7259 /*! @ingroup XXH3_family */
7260 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset(XXH_NOESCAPE XXH3_state_t *statePtr) {
7261 return XXH3_64bits_reset(statePtr);
7262 }
7263
7264 /*! @ingroup XXH3_family */
7265 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSecret(
7266 XXH_NOESCAPE XXH3_state_t *statePtr,
7267 XXH_NOESCAPE const void *secret,
7268 size_t secretSize) {
7269 return XXH3_64bits_reset_withSecret(statePtr, secret, secretSize);
7270 }
7271
7272 /*! @ingroup XXH3_family */
7273 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t *statePtr, XXH64_hash_t seed) {
7274 return XXH3_64bits_reset_withSeed(statePtr, seed);
7275 }
7276
7277 /*! @ingroup XXH3_family */
7278 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSecretandSeed(
7279 XXH_NOESCAPE XXH3_state_t *statePtr,
7280 XXH_NOESCAPE const void *secret,
7281 size_t secretSize,
7282 XXH64_hash_t seed) {
7283 return XXH3_64bits_reset_withSecretandSeed(statePtr, secret, secretSize, seed);
7284 }
7285
7286 /*! @ingroup XXH3_family */
7287 XXH_PUBLIC_API XXH_errorcode
7288 XXH3_128bits_update(XXH_NOESCAPE XXH3_state_t *state, XXH_NOESCAPE const void *input, size_t len) {
7289 return XXH3_update_regular(state, input, len);
7290 }
7291
7292 /*! @ingroup XXH3_family */
7293 XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_digest(XXH_NOESCAPE const XXH3_state_t *state) {
7294 const unsigned char *const secret = (state->extSecret == NULL) ? state->customSecret : state->extSecret;
7295 if (state->totalLen > XXH3_MIDSIZE_MAX) {
7296 XXH_ALIGN(XXH_ACC_ALIGN) XXH64_hash_t acc[XXH_ACC_NB];
7297 XXH3_digest_long(acc, state, secret);
7298 XXH_ASSERT(state->secretLimit + XXH_STRIPE_LEN >= sizeof(acc) + XXH_SECRET_MERGEACCS_START);
7299 return XXH3_finalizeLong_128b(acc, secret, state->secretLimit + XXH_STRIPE_LEN, (xxh_u64)state->totalLen);
7300 }
7301 /* len <= XXH3_MIDSIZE_MAX : short code */
7302 if (state->useSeed)
7303 return XXH3_128bits_withSeed(state->buffer, (size_t)state->totalLen, state->seed);
7304 return XXH3_128bits_withSecret(
7305 state->buffer, (size_t)(state->totalLen), secret, state->secretLimit + XXH_STRIPE_LEN);
7306 }
7307 # endif /* !XXH_NO_STREAM */
7308 /* 128-bit utility functions */
7309
7310 /* return : 1 is equal, 0 if different */
7311 /*! @ingroup XXH3_family */
7312 XXH_PUBLIC_API int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2) {
7313 /* note : XXH128_hash_t is compact, it has no padding byte */
7314 return !(XXH_memcmp(&h1, &h2, sizeof(h1)));
7315 }
7316
7317 /* This prototype is compatible with stdlib's qsort().
7318 * @return : >0 if *h128_1 > *h128_2
7319 * <0 if *h128_1 < *h128_2
7320 * =0 if *h128_1 == *h128_2 */
7321 /*! @ingroup XXH3_family */
7322 XXH_PUBLIC_API int XXH128_cmp(XXH_NOESCAPE const void *h128_1, XXH_NOESCAPE const void *h128_2) {
7323 XXH128_hash_t const h1 = *(const XXH128_hash_t *)h128_1;
7324 XXH128_hash_t const h2 = *(const XXH128_hash_t *)h128_2;
7325 int const hcmp = (h1.high64 > h2.high64) - (h2.high64 > h1.high64);
7326 /* note : bets that, in most cases, hash values are different */
7327 if (hcmp)
7328 return hcmp;
7329 return (h1.low64 > h2.low64) - (h2.low64 > h1.low64);
7330 }
7331
7332 /*====== Canonical representation ======*/
7333 /*! @ingroup XXH3_family */
7334 XXH_PUBLIC_API void XXH128_canonicalFromHash(XXH_NOESCAPE XXH128_canonical_t *dst, XXH128_hash_t hash) {
7335 XXH_STATIC_ASSERT(sizeof(XXH128_canonical_t) == sizeof(XXH128_hash_t));
7336 if (XXH_CPU_LITTLE_ENDIAN) {
7337 hash.high64 = XXH_swap64(hash.high64);
7338 hash.low64 = XXH_swap64(hash.low64);
7339 }
7340 XXH_memcpy(dst, &hash.high64, sizeof(hash.high64));
7341 XXH_memcpy((char *)dst + sizeof(hash.high64), &hash.low64, sizeof(hash.low64));
7342 }
7343
7344 /*! @ingroup XXH3_family */
7345 XXH_PUBLIC_API XXH128_hash_t XXH128_hashFromCanonical(XXH_NOESCAPE const XXH128_canonical_t *src) {
7346 XXH128_hash_t h;
7347 h.high64 = XXH_readBE64(src);
7348 h.low64 = XXH_readBE64(src->digest + 8);
7349 return h;
7350 }
7351
7352 /* ==========================================
7353 * Secret generators
7354 * ==========================================
7355 */
7356 # define XXH_MIN(x, y) (((x) > (y)) ? (y) : (x))
7357
7358 XXH_FORCE_INLINE void XXH3_combine16(void *dst, XXH128_hash_t h128) {
7359 XXH_writeLE64(dst, XXH_readLE64(dst) ^ h128.low64);
7360 XXH_writeLE64((char *)dst + 8, XXH_readLE64((char *)dst + 8) ^ h128.high64);
7361 }
7362
7363 /*! @ingroup XXH3_family */
7364 XXH_PUBLIC_API XXH_errorcode XXH3_generateSecret(
7365 XXH_NOESCAPE void *secretBuffer,
7366 size_t secretSize,
7367 XXH_NOESCAPE const void *customSeed,
7368 size_t customSeedSize) {
7369 # if (XXH_DEBUGLEVEL >= 1)
7370 XXH_ASSERT(secretBuffer != NULL);
7371 XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
7372 # else
7373 /* production mode, assert() are disabled */
7374 if (secretBuffer == NULL)
7375 return XXH_ERROR;
7376 if (secretSize < XXH3_SECRET_SIZE_MIN)
7377 return XXH_ERROR;
7378 # endif
7379
7380 if (customSeedSize == 0) {
7381 customSeed = XXH3_kSecret;
7382 customSeedSize = XXH_SECRET_DEFAULT_SIZE;
7383 }
7384 # if (XXH_DEBUGLEVEL >= 1)
7385 XXH_ASSERT(customSeed != NULL);
7386 # else
7387 if (customSeed == NULL)
7388 return XXH_ERROR;
7389 # endif
7390
7391 /* Fill secretBuffer with a copy of customSeed - repeat as needed */
7392 {
7393 size_t pos = 0;
7394 while (pos < secretSize) {
7395 size_t const toCopy = XXH_MIN((secretSize - pos), customSeedSize);
7396 XXH_memcpy((char *)secretBuffer + pos, customSeed, toCopy);
7397 pos += toCopy;
7398 }
7399 }
7400
7401 {
7402 size_t const nbSeg16 = secretSize / 16;
7403 size_t n;
7404 XXH128_canonical_t scrambler;
7405 XXH128_canonicalFromHash(&scrambler, XXH128(customSeed, customSeedSize, 0));
7406 for (n = 0; n < nbSeg16; n++) {
7407 XXH128_hash_t const h128 = XXH128(&scrambler, sizeof(scrambler), n);
7408 XXH3_combine16((char *)secretBuffer + n * 16, h128);
7409 }
7410 /* last segment */
7411 XXH3_combine16((char *)secretBuffer + secretSize - 16, XXH128_hashFromCanonical(&scrambler));
7412 }
7413 return XXH_OK;
7414 }
7415
7416 /*! @ingroup XXH3_family */
7417 XXH_PUBLIC_API void XXH3_generateSecret_fromSeed(XXH_NOESCAPE void *secretBuffer, XXH64_hash_t seed) {
7418 XXH_ALIGN(XXH_SEC_ALIGN) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE];
7419 XXH3_initCustomSecret(secret, seed);
7420 XXH_ASSERT(secretBuffer != NULL);
7421 XXH_memcpy(secretBuffer, secret, XXH_SECRET_DEFAULT_SIZE);
7422 }
7423
7424 /* Pop our optimization override from above */
7425 # if XXH_VECTOR == XXH_AVX2 /* AVX2 */ \
7426 && defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \
7427 && defined(__OPTIMIZE__) && XXH_SIZE_OPT <= 0 /* respect -O0 and -Os */
7428 # pragma GCC pop_options
7429 # endif
7430
7431 # endif /* XXH_NO_LONG_LONG */
7432
7433 # endif /* XXH_NO_XXH3 */
7434
7435 /*!
7436 * @}
7437 */
7438 #endif /* XXH_IMPLEMENTATION */
7439
7440 #if defined(__cplusplus) && !defined(XXH_NO_EXTERNC_GUARD)
7441 } /* extern "C" */
7442 #endif