xref: /lighttpd1.4/src/algo_xxhash.h (revision a568bf47)
1 #ifndef INCLUDED_ALGO_XXHASH_H
2 #define INCLUDED_ALGO_XXHASH_H
3 #include "first.h"
4 
5 /*(lighttpd customization)*/
6 /*#define XXH_NO_INLINE_HINTS 1*/
7 /*#define XXH_REROLL 1*/
8 #define XXH_NO_LONG_LONG
9 
10 
11 #ifdef HAVE_XXHASH_H
12 
13 #include <xxhash.h>
14 
15 #else  /* ! HAVE_XXHASH_H */
16 
17 /*
18  * xxHash - Extremely Fast Hash algorithm
19  * Header File
20  * Copyright (C) 2012-2020 Yann Collet
21  *
22  * BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php)
23  *
24  * Redistribution and use in source and binary forms, with or without
25  * modification, are permitted provided that the following conditions are
26  * met:
27  *
28  *    * Redistributions of source code must retain the above copyright
29  *      notice, this list of conditions and the following disclaimer.
30  *    * Redistributions in binary form must reproduce the above
31  *      copyright notice, this list of conditions and the following disclaimer
32  *      in the documentation and/or other materials provided with the
33  *      distribution.
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46  *
47  * You can contact the author at:
48  *   - xxHash homepage: https://www.xxhash.com
49  *   - xxHash source repository: https://github.com/Cyan4973/xxHash
50  */
51 /*!
52  * @mainpage xxHash
53  *
54  * @file xxhash.h
55  * xxHash prototypes and implementation
56  */
57 /* TODO: update */
58 /* Notice extracted from xxHash homepage:
59 
60 xxHash is an extremely fast hash algorithm, running at RAM speed limits.
61 It also successfully passes all tests from the SMHasher suite.
62 
63 Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz)
64 
65 Name            Speed       Q.Score   Author
66 xxHash          5.4 GB/s     10
67 CrapWow         3.2 GB/s      2       Andrew
68 MurmurHash 3a   2.7 GB/s     10       Austin Appleby
69 SpookyHash      2.0 GB/s     10       Bob Jenkins
70 SBox            1.4 GB/s      9       Bret Mulvey
71 Lookup3         1.2 GB/s      9       Bob Jenkins
72 SuperFastHash   1.2 GB/s      1       Paul Hsieh
73 CityHash64      1.05 GB/s    10       Pike & Alakuijala
74 FNV             0.55 GB/s     5       Fowler, Noll, Vo
75 CRC32           0.43 GB/s     9
76 MD5-32          0.33 GB/s    10       Ronald L. Rivest
77 SHA1-32         0.28 GB/s    10
78 
79 Q.Score is a measure of quality of the hash function.
80 It depends on successfully passing SMHasher test set.
81 10 is a perfect score.
82 
83 Note: SMHasher's CRC32 implementation is not the fastest one.
84 Other speed-oriented implementations can be faster,
85 especially in combination with PCLMUL instruction:
86 https://fastcompression.blogspot.com/2019/03/presenting-xxh3.html?showComment=1552696407071#c3490092340461170735
87 
88 A 64-bit version, named XXH64, is available since r35.
89 It offers much better speed, but for 64-bit applications only.
90 Name     Speed on 64 bits    Speed on 32 bits
91 XXH64       13.8 GB/s            1.9 GB/s
92 XXH32        6.8 GB/s            6.0 GB/s
93 */
94 
95 #if defined (__cplusplus)
96 extern "C" {
97 #endif
98 
99 /* ****************************
100  *  INLINE mode
101  ******************************/
102 /*!
103  * XXH_INLINE_ALL (and XXH_PRIVATE_API)
104  * Use these build macros to inline xxhash into the target unit.
105  * Inlining improves performance on small inputs, especially when the length is
106  * expressed as a compile-time constant:
107  *
108  *      https://fastcompression.blogspot.com/2018/03/xxhash-for-small-keys-impressive-power.html
109  *
110  * It also keeps xxHash symbols private to the unit, so they are not exported.
111  *
112  * Usage:
113  *     #define XXH_INLINE_ALL
114  *     #include "xxhash.h"
115  *
116  * Do not compile and link xxhash.o as a separate object, as it is not useful.
117  */
118 #if (defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API)) \
119     && !defined(XXH_INLINE_ALL_31684351384)
120    /* this section should be traversed only once */
121 #  define XXH_INLINE_ALL_31684351384
122    /* give access to the advanced API, required to compile implementations */
123 #  undef XXH_STATIC_LINKING_ONLY   /* avoid macro redef */
124 #  define XXH_STATIC_LINKING_ONLY
125    /* make all functions private */
126 #  undef XXH_PUBLIC_API
127 #  if defined(__GNUC__)
128 #    define XXH_PUBLIC_API static __inline __attribute__((unused))
129 #  elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
130 #    define XXH_PUBLIC_API static inline
131 #  elif defined(_MSC_VER)
132 #    define XXH_PUBLIC_API static __inline
133 #  else
134      /* note: this version may generate warnings for unused static functions */
135 #    define XXH_PUBLIC_API static
136 #  endif
137 
138    /*
139     * This part deals with the special case where a unit wants to inline xxHash,
140     * but "xxhash.h" has previously been included without XXH_INLINE_ALL,
141     * such as part of some previously included *.h header file.
142     * Without further action, the new include would just be ignored,
143     * and functions would effectively _not_ be inlined (silent failure).
144     * The following macros solve this situation by prefixing all inlined names,
145     * avoiding naming collision with previous inclusions.
146     */
147    /* Before that, we unconditionally #undef all symbols,
148     * in case they were already defined with XXH_NAMESPACE.
149     * They will then be redefined for XXH_INLINE_ALL
150     */
151 #  undef XXH_versionNumber
152     /* XXH32 */
153 #  undef XXH32
154 #  undef XXH32_createState
155 #  undef XXH32_freeState
156 #  undef XXH32_reset
157 #  undef XXH32_update
158 #  undef XXH32_digest
159 #  undef XXH32_copyState
160 #  undef XXH32_canonicalFromHash
161 #  undef XXH32_hashFromCanonical
162     /* XXH64 */
163 #  undef XXH64
164 #  undef XXH64_createState
165 #  undef XXH64_freeState
166 #  undef XXH64_reset
167 #  undef XXH64_update
168 #  undef XXH64_digest
169 #  undef XXH64_copyState
170 #  undef XXH64_canonicalFromHash
171 #  undef XXH64_hashFromCanonical
172     /* XXH3_64bits */
173 #  undef XXH3_64bits
174 #  undef XXH3_64bits_withSecret
175 #  undef XXH3_64bits_withSeed
176 #  undef XXH3_64bits_withSecretandSeed
177 #  undef XXH3_createState
178 #  undef XXH3_freeState
179 #  undef XXH3_copyState
180 #  undef XXH3_64bits_reset
181 #  undef XXH3_64bits_reset_withSeed
182 #  undef XXH3_64bits_reset_withSecret
183 #  undef XXH3_64bits_update
184 #  undef XXH3_64bits_digest
185 #  undef XXH3_generateSecret
186     /* XXH3_128bits */
187 #  undef XXH128
188 #  undef XXH3_128bits
189 #  undef XXH3_128bits_withSeed
190 #  undef XXH3_128bits_withSecret
191 #  undef XXH3_128bits_reset
192 #  undef XXH3_128bits_reset_withSeed
193 #  undef XXH3_128bits_reset_withSecret
194 #  undef XXH3_128bits_reset_withSecretandSeed
195 #  undef XXH3_128bits_update
196 #  undef XXH3_128bits_digest
197 #  undef XXH128_isEqual
198 #  undef XXH128_cmp
199 #  undef XXH128_canonicalFromHash
200 #  undef XXH128_hashFromCanonical
201     /* Finally, free the namespace itself */
202 #  undef XXH_NAMESPACE
203 
204     /* employ the namespace for XXH_INLINE_ALL */
205 #  define XXH_NAMESPACE XXH_INLINE_
206    /*
207     * Some identifiers (enums, type names) are not symbols,
208     * but they must nonetheless be renamed to avoid redeclaration.
209     * Alternative solution: do not redeclare them.
210     * However, this requires some #ifdefs, and has a more dispersed impact.
211     * Meanwhile, renaming can be achieved in a single place.
212     */
213 #  define XXH_IPREF(Id)   XXH_NAMESPACE ## Id
214 #  define XXH_OK XXH_IPREF(XXH_OK)
215 #  define XXH_ERROR XXH_IPREF(XXH_ERROR)
216 #  define XXH_errorcode XXH_IPREF(XXH_errorcode)
217 #  define XXH32_canonical_t  XXH_IPREF(XXH32_canonical_t)
218 #  define XXH64_canonical_t  XXH_IPREF(XXH64_canonical_t)
219 #  define XXH128_canonical_t XXH_IPREF(XXH128_canonical_t)
220 #  define XXH32_state_s XXH_IPREF(XXH32_state_s)
221 #  define XXH32_state_t XXH_IPREF(XXH32_state_t)
222 #  define XXH64_state_s XXH_IPREF(XXH64_state_s)
223 #  define XXH64_state_t XXH_IPREF(XXH64_state_t)
224 #  define XXH3_state_s  XXH_IPREF(XXH3_state_s)
225 #  define XXH3_state_t  XXH_IPREF(XXH3_state_t)
226 #  define XXH128_hash_t XXH_IPREF(XXH128_hash_t)
227    /* Ensure the header is parsed again, even if it was previously included */
228 #  undef XXHASH_H_5627135585666179
229 #  undef XXHASH_H_STATIC_13879238742
230 #endif /* XXH_INLINE_ALL || XXH_PRIVATE_API */
231 
232 
233 
234 /* ****************************************************************
235  *  Stable API
236  *****************************************************************/
237 #ifndef XXHASH_H_5627135585666179
238 #define XXHASH_H_5627135585666179 1
239 
240 
241 /*!
242  * @defgroup public Public API
243  * Contains details on the public xxHash functions.
244  * @{
245  */
246 /* specific declaration modes for Windows */
247 #if !defined(XXH_INLINE_ALL) && !defined(XXH_PRIVATE_API)
248 #  if defined(WIN32) && defined(_MSC_VER) && (defined(XXH_IMPORT) || defined(XXH_EXPORT))
249 #    ifdef XXH_EXPORT
250 #      define XXH_PUBLIC_API __declspec(dllexport)
251 #    elif XXH_IMPORT
252 #      define XXH_PUBLIC_API __declspec(dllimport)
253 #    endif
254 #  else
255 #    define XXH_PUBLIC_API   /* do nothing */
256 #  endif
257 #endif
258 
259 #ifdef XXH_DOXYGEN
260 /*!
261  * @brief Emulate a namespace by transparently prefixing all symbols.
262  *
263  * If you want to include _and expose_ xxHash functions from within your own
264  * library, but also want to avoid symbol collisions with other libraries which
265  * may also include xxHash, you can use XXH_NAMESPACE to automatically prefix
266  * any public symbol from xxhash library with the value of XXH_NAMESPACE
267  * (therefore, avoid empty or numeric values).
268  *
269  * Note that no change is required within the calling program as long as it
270  * includes `xxhash.h`: Regular symbol names will be automatically translated
271  * by this header.
272  */
273 #  define XXH_NAMESPACE /* YOUR NAME HERE */
274 #  undef XXH_NAMESPACE
275 #endif
276 
277 #ifdef XXH_NAMESPACE
278 #  define XXH_CAT(A,B) A##B
279 #  define XXH_NAME2(A,B) XXH_CAT(A,B)
280 #  define XXH_versionNumber XXH_NAME2(XXH_NAMESPACE, XXH_versionNumber)
281 /* XXH32 */
282 #  define XXH32 XXH_NAME2(XXH_NAMESPACE, XXH32)
283 #  define XXH32_createState XXH_NAME2(XXH_NAMESPACE, XXH32_createState)
284 #  define XXH32_freeState XXH_NAME2(XXH_NAMESPACE, XXH32_freeState)
285 #  define XXH32_reset XXH_NAME2(XXH_NAMESPACE, XXH32_reset)
286 #  define XXH32_update XXH_NAME2(XXH_NAMESPACE, XXH32_update)
287 #  define XXH32_digest XXH_NAME2(XXH_NAMESPACE, XXH32_digest)
288 #  define XXH32_copyState XXH_NAME2(XXH_NAMESPACE, XXH32_copyState)
289 #  define XXH32_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH32_canonicalFromHash)
290 #  define XXH32_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH32_hashFromCanonical)
291 /* XXH64 */
292 #  define XXH64 XXH_NAME2(XXH_NAMESPACE, XXH64)
293 #  define XXH64_createState XXH_NAME2(XXH_NAMESPACE, XXH64_createState)
294 #  define XXH64_freeState XXH_NAME2(XXH_NAMESPACE, XXH64_freeState)
295 #  define XXH64_reset XXH_NAME2(XXH_NAMESPACE, XXH64_reset)
296 #  define XXH64_update XXH_NAME2(XXH_NAMESPACE, XXH64_update)
297 #  define XXH64_digest XXH_NAME2(XXH_NAMESPACE, XXH64_digest)
298 #  define XXH64_copyState XXH_NAME2(XXH_NAMESPACE, XXH64_copyState)
299 #  define XXH64_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH64_canonicalFromHash)
300 #  define XXH64_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH64_hashFromCanonical)
301 /* XXH3_64bits */
302 #  define XXH3_64bits XXH_NAME2(XXH_NAMESPACE, XXH3_64bits)
303 #  define XXH3_64bits_withSecret XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_withSecret)
304 #  define XXH3_64bits_withSeed XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_withSeed)
305 #  define XXH3_64bits_withSecretandSeed XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_withSecretandSeed)
306 #  define XXH3_createState XXH_NAME2(XXH_NAMESPACE, XXH3_createState)
307 #  define XXH3_freeState XXH_NAME2(XXH_NAMESPACE, XXH3_freeState)
308 #  define XXH3_copyState XXH_NAME2(XXH_NAMESPACE, XXH3_copyState)
309 #  define XXH3_64bits_reset XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_reset)
310 #  define XXH3_64bits_reset_withSeed XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_reset_withSeed)
311 #  define XXH3_64bits_reset_withSecret XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_reset_withSecret)
312 #  define XXH3_64bits_reset_withSecretandSeed XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_reset_withSecretandSeed)
313 #  define XXH3_64bits_update XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_update)
314 #  define XXH3_64bits_digest XXH_NAME2(XXH_NAMESPACE, XXH3_64bits_digest)
315 #  define XXH3_generateSecret XXH_NAME2(XXH_NAMESPACE, XXH3_generateSecret)
316 #  define XXH3_generateSecret_fromSeed XXH_NAME2(XXH_NAMESPACE, XXH3_generateSecret_fromSeed)
317 /* XXH3_128bits */
318 #  define XXH128 XXH_NAME2(XXH_NAMESPACE, XXH128)
319 #  define XXH3_128bits XXH_NAME2(XXH_NAMESPACE, XXH3_128bits)
320 #  define XXH3_128bits_withSeed XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_withSeed)
321 #  define XXH3_128bits_withSecret XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_withSecret)
322 #  define XXH3_128bits_withSecretandSeed XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_withSecretandSeed)
323 #  define XXH3_128bits_reset XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_reset)
324 #  define XXH3_128bits_reset_withSeed XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_reset_withSeed)
325 #  define XXH3_128bits_reset_withSecret XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_reset_withSecret)
326 #  define XXH3_128bits_reset_withSecretandSeed XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_reset_withSecretandSeed)
327 #  define XXH3_128bits_update XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_update)
328 #  define XXH3_128bits_digest XXH_NAME2(XXH_NAMESPACE, XXH3_128bits_digest)
329 #  define XXH128_isEqual XXH_NAME2(XXH_NAMESPACE, XXH128_isEqual)
330 #  define XXH128_cmp     XXH_NAME2(XXH_NAMESPACE, XXH128_cmp)
331 #  define XXH128_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH128_canonicalFromHash)
332 #  define XXH128_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH128_hashFromCanonical)
333 #endif
334 
335 
336 /* *************************************
337 *  Version
338 ***************************************/
339 #define XXH_VERSION_MAJOR    0
340 #define XXH_VERSION_MINOR    8
341 #define XXH_VERSION_RELEASE  1
342 #define XXH_VERSION_NUMBER  (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE)
343 
344 /*!
345  * @brief Obtains the xxHash version.
346  *
347  * This is mostly useful when xxHash is compiled as a shared library,
348  * since the returned value comes from the library, as opposed to header file.
349  *
350  * @return `XXH_VERSION_NUMBER` of the invoked library.
351  */
352 XXH_PUBLIC_API unsigned XXH_versionNumber (void);
353 
354 
355 /* ****************************
356 *  Common basic types
357 ******************************/
358 #include <stddef.h>   /* size_t */
359 typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode;
360 
361 
362 /*-**********************************************************************
363 *  32-bit hash
364 ************************************************************************/
365 #if defined(XXH_DOXYGEN) /* Don't show <stdint.h> include */
366 /*!
367  * @brief An unsigned 32-bit integer.
368  *
369  * Not necessarily defined to `uint32_t` but functionally equivalent.
370  */
371 typedef uint32_t XXH32_hash_t;
372 
373 #elif !defined (__VMS) \
374   && (defined (__cplusplus) \
375   || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
376 #   include <stdint.h>
377     typedef uint32_t XXH32_hash_t;
378 
379 #else
380 #   include <limits.h>
381 #   if UINT_MAX == 0xFFFFFFFFUL
382       typedef unsigned int XXH32_hash_t;
383 #   else
384 #     if ULONG_MAX == 0xFFFFFFFFUL
385         typedef unsigned long XXH32_hash_t;
386 #     else
387 #       error "unsupported platform: need a 32-bit type"
388 #     endif
389 #   endif
390 #endif
391 
392 /*!
393  * @}
394  *
395  * @defgroup xxh32_family XXH32 family
396  * @ingroup public
397  * Contains functions used in the classic 32-bit xxHash algorithm.
398  *
399  * @note
400  *   XXH32 is useful for older platforms, with no or poor 64-bit performance.
401  *   Note that @ref xxh3_family provides competitive speed
402  *   for both 32-bit and 64-bit systems, and offers true 64/128 bit hash results.
403  *
404  * @see @ref xxh64_family, @ref xxh3_family : Other xxHash families
405  * @see @ref xxh32_impl for implementation details
406  * @{
407  */
408 
409 /*!
410  * @brief Calculates the 32-bit hash of @p input using xxHash32.
411  *
412  * Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark): 5.4 GB/s
413  *
414  * @param input The block of data to be hashed, at least @p length bytes in size.
415  * @param length The length of @p input, in bytes.
416  * @param seed The 32-bit seed to alter the hash's output predictably.
417  *
418  * @pre
419  *   The memory between @p input and @p input + @p length must be valid,
420  *   readable, contiguous memory. However, if @p length is `0`, @p input may be
421  *   `NULL`. In C++, this also must be *TriviallyCopyable*.
422  *
423  * @return The calculated 32-bit hash value.
424  *
425  * @see
426  *    XXH64(), XXH3_64bits_withSeed(), XXH3_128bits_withSeed(), XXH128():
427  *    Direct equivalents for the other variants of xxHash.
428  * @see
429  *    XXH32_createState(), XXH32_update(), XXH32_digest(): Streaming version.
430  */
431 XXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t length, XXH32_hash_t seed);
432 
433 /*!
434  * Streaming functions generate the xxHash value from an incremental input.
435  * This method is slower than single-call functions, due to state management.
436  * For small inputs, prefer `XXH32()` and `XXH64()`, which are better optimized.
437  *
438  * An XXH state must first be allocated using `XXH*_createState()`.
439  *
440  * Start a new hash by initializing the state with a seed using `XXH*_reset()`.
441  *
442  * Then, feed the hash state by calling `XXH*_update()` as many times as necessary.
443  *
444  * The function returns an error code, with 0 meaning OK, and any other value
445  * meaning there is an error.
446  *
447  * Finally, a hash value can be produced anytime, by using `XXH*_digest()`.
448  * This function returns the nn-bits hash as an int or long long.
449  *
450  * It's still possible to continue inserting input into the hash state after a
451  * digest, and generate new hash values later on by invoking `XXH*_digest()`.
452  *
453  * When done, release the state using `XXH*_freeState()`.
454  *
455  * Example code for incrementally hashing a file:
456  * @code{.c}
457  *    #include <stdio.h>
458  *    #include <xxhash.h>
459  *    #define BUFFER_SIZE 256
460  *
461  *    // Note: XXH64 and XXH3 use the same interface.
462  *    XXH32_hash_t
463  *    hashFile(FILE* stream)
464  *    {
465  *        XXH32_state_t* state;
466  *        unsigned char buf[BUFFER_SIZE];
467  *        size_t amt;
468  *        XXH32_hash_t hash;
469  *
470  *        state = XXH32_createState();       // Create a state
471  *        assert(state != NULL);             // Error check here
472  *        XXH32_reset(state, 0xbaad5eed);    // Reset state with our seed
473  *        while ((amt = fread(buf, 1, sizeof(buf), stream)) != 0) {
474  *            XXH32_update(state, buf, amt); // Hash the file in chunks
475  *        }
476  *        hash = XXH32_digest(state);        // Finalize the hash
477  *        XXH32_freeState(state);            // Clean up
478  *        return hash;
479  *    }
480  * @endcode
481  */
482 
483 /*!
484  * @typedef struct XXH32_state_s XXH32_state_t
485  * @brief The opaque state struct for the XXH32 streaming API.
486  *
487  * @see XXH32_state_s for details.
488  */
489 typedef struct XXH32_state_s XXH32_state_t;
490 
491 /*!
492  * @brief Allocates an @ref XXH32_state_t.
493  *
494  * Must be freed with XXH32_freeState().
495  * @return An allocated XXH32_state_t on success, `NULL` on failure.
496  */
497 XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void);
498 /*!
499  * @brief Frees an @ref XXH32_state_t.
500  *
501  * Must be allocated with XXH32_createState().
502  * @param statePtr A pointer to an @ref XXH32_state_t allocated with @ref XXH32_createState().
503  * @return XXH_OK.
504  */
505 XXH_PUBLIC_API XXH_errorcode  XXH32_freeState(XXH32_state_t* statePtr);
506 /*!
507  * @brief Copies one @ref XXH32_state_t to another.
508  *
509  * @param dst_state The state to copy to.
510  * @param src_state The state to copy from.
511  * @pre
512  *   @p dst_state and @p src_state must not be `NULL` and must not overlap.
513  */
514 XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dst_state, const XXH32_state_t* src_state);
515 
516 /*!
517  * @brief Resets an @ref XXH32_state_t to begin a new hash.
518  *
519  * This function resets and seeds a state. Call it before @ref XXH32_update().
520  *
521  * @param statePtr The state struct to reset.
522  * @param seed The 32-bit seed to alter the hash result predictably.
523  *
524  * @pre
525  *   @p statePtr must not be `NULL`.
526  *
527  * @return @ref XXH_OK on success, @ref XXH_ERROR on failure.
528  */
529 XXH_PUBLIC_API XXH_errorcode XXH32_reset  (XXH32_state_t* statePtr, XXH32_hash_t seed);
530 
531 /*!
532  * @brief Consumes a block of @p input to an @ref XXH32_state_t.
533  *
534  * Call this to incrementally consume blocks of data.
535  *
536  * @param statePtr The state struct to update.
537  * @param input The block of data to be hashed, at least @p length bytes in size.
538  * @param length The length of @p input, in bytes.
539  *
540  * @pre
541  *   @p statePtr must not be `NULL`.
542  * @pre
543  *   The memory between @p input and @p input + @p length must be valid,
544  *   readable, contiguous memory. However, if @p length is `0`, @p input may be
545  *   `NULL`. In C++, this also must be *TriviallyCopyable*.
546  *
547  * @return @ref XXH_OK on success, @ref XXH_ERROR on failure.
548  */
549 XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length);
550 
551 /*!
552  * @brief Returns the calculated hash value from an @ref XXH32_state_t.
553  *
554  * @note
555  *   Calling XXH32_digest() will not affect @p statePtr, so you can update,
556  *   digest, and update again.
557  *
558  * @param statePtr The state struct to calculate the hash from.
559  *
560  * @pre
561  *  @p statePtr must not be `NULL`.
562  *
563  * @return The calculated xxHash32 value from that state.
564  */
565 XXH_PUBLIC_API XXH32_hash_t  XXH32_digest (const XXH32_state_t* statePtr);
566 
567 /*******   Canonical representation   *******/
568 
569 /*
570  * The default return values from XXH functions are unsigned 32 and 64 bit
571  * integers.
572  * This the simplest and fastest format for further post-processing.
573  *
574  * However, this leaves open the question of what is the order on the byte level,
575  * since little and big endian conventions will store the same number differently.
576  *
577  * The canonical representation settles this issue by mandating big-endian
578  * convention, the same convention as human-readable numbers (large digits first).
579  *
580  * When writing hash values to storage, sending them over a network, or printing
581  * them, it's highly recommended to use the canonical representation to ensure
582  * portability across a wider range of systems, present and future.
583  *
584  * The following functions allow transformation of hash values to and from
585  * canonical format.
586  */
587 
588 /*!
589  * @brief Canonical (big endian) representation of @ref XXH32_hash_t.
590  */
591 typedef struct {
592     unsigned char digest[4]; /*!< Hash bytes, big endian */
593 } XXH32_canonical_t;
594 
595 /*!
596  * @brief Converts an @ref XXH32_hash_t to a big endian @ref XXH32_canonical_t.
597  *
598  * @param dst The @ref XXH32_canonical_t pointer to be stored to.
599  * @param hash The @ref XXH32_hash_t to be converted.
600  *
601  * @pre
602  *   @p dst must not be `NULL`.
603  */
604 XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash);
605 
606 /*!
607  * @brief Converts an @ref XXH32_canonical_t to a native @ref XXH32_hash_t.
608  *
609  * @param src The @ref XXH32_canonical_t to convert.
610  *
611  * @pre
612  *   @p src must not be `NULL`.
613  *
614  * @return The converted hash.
615  */
616 XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src);
617 
618 
619 #ifdef __has_attribute
620 # define XXH_HAS_ATTRIBUTE(x) __has_attribute(x)
621 #else
622 # define XXH_HAS_ATTRIBUTE(x) 0
623 #endif
624 
625 /* C-language Attributes are added in C23. */
626 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201710L) && defined(__has_c_attribute)
627 # define XXH_HAS_C_ATTRIBUTE(x) __has_c_attribute(x)
628 #else
629 # define XXH_HAS_C_ATTRIBUTE(x) 0
630 #endif
631 
632 #if defined(__cplusplus) && defined(__has_cpp_attribute)
633 # define XXH_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
634 #else
635 # define XXH_HAS_CPP_ATTRIBUTE(x) 0
636 #endif
637 
638 /*
639 Define XXH_FALLTHROUGH macro for annotating switch case with the 'fallthrough' attribute
640 introduced in CPP17 and C23.
641 CPP17 : https://en.cppreference.com/w/cpp/language/attributes/fallthrough
642 C23   : https://en.cppreference.com/w/c/language/attributes/fallthrough
643 */
644 #if XXH_HAS_C_ATTRIBUTE(x)
645 # define XXH_FALLTHROUGH [[fallthrough]]
646 #elif XXH_HAS_CPP_ATTRIBUTE(x)
647 # define XXH_FALLTHROUGH [[fallthrough]]
648 #elif XXH_HAS_ATTRIBUTE(__fallthrough__)
649 # define XXH_FALLTHROUGH __attribute__ ((fallthrough))
650 #else
651 # define XXH_FALLTHROUGH
652 #endif
653 
654 /*!
655  * @}
656  * @ingroup public
657  * @{
658  */
659 
660 #ifndef XXH_NO_LONG_LONG
661 /*-**********************************************************************
662 *  64-bit hash
663 ************************************************************************/
664 #if defined(XXH_DOXYGEN) /* don't include <stdint.h> */
665 /*!
666  * @brief An unsigned 64-bit integer.
667  *
668  * Not necessarily defined to `uint64_t` but functionally equivalent.
669  */
670 typedef uint64_t XXH64_hash_t;
671 #elif !defined (__VMS) \
672   && (defined (__cplusplus) \
673   || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
674 #  include <stdint.h>
675    typedef uint64_t XXH64_hash_t;
676 #else
677 #  include <limits.h>
678 #  if defined(__LP64__) && ULONG_MAX == 0xFFFFFFFFFFFFFFFFULL
679      /* LP64 ABI says uint64_t is unsigned long */
680      typedef unsigned long XXH64_hash_t;
681 #  else
682      /* the following type must have a width of 64-bit */
683      typedef unsigned long long XXH64_hash_t;
684 #  endif
685 #endif
686 
687 /*!
688  * @}
689  *
690  * @defgroup xxh64_family XXH64 family
691  * @ingroup public
692  * @{
693  * Contains functions used in the classic 64-bit xxHash algorithm.
694  *
695  * @note
696  *   XXH3 provides competitive speed for both 32-bit and 64-bit systems,
697  *   and offers true 64/128 bit hash results.
698  *   It provides better speed for systems with vector processing capabilities.
699  */
700 
701 
702 /*!
703  * @brief Calculates the 64-bit hash of @p input using xxHash64.
704  *
705  * This function usually runs faster on 64-bit systems, but slower on 32-bit
706  * systems (see benchmark).
707  *
708  * @param input The block of data to be hashed, at least @p length bytes in size.
709  * @param length The length of @p input, in bytes.
710  * @param seed The 64-bit seed to alter the hash's output predictably.
711  *
712  * @pre
713  *   The memory between @p input and @p input + @p length must be valid,
714  *   readable, contiguous memory. However, if @p length is `0`, @p input may be
715  *   `NULL`. In C++, this also must be *TriviallyCopyable*.
716  *
717  * @return The calculated 64-bit hash.
718  *
719  * @see
720  *    XXH32(), XXH3_64bits_withSeed(), XXH3_128bits_withSeed(), XXH128():
721  *    Direct equivalents for the other variants of xxHash.
722  * @see
723  *    XXH64_createState(), XXH64_update(), XXH64_digest(): Streaming version.
724  */
725 XXH_PUBLIC_API XXH64_hash_t XXH64(const void* input, size_t length, XXH64_hash_t seed);
726 
727 /*******   Streaming   *******/
728 /*!
729  * @brief The opaque state struct for the XXH64 streaming API.
730  *
731  * @see XXH64_state_s for details.
732  */
733 typedef struct XXH64_state_s XXH64_state_t;   /* incomplete type */
734 XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void);
735 XXH_PUBLIC_API XXH_errorcode  XXH64_freeState(XXH64_state_t* statePtr);
736 XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* dst_state, const XXH64_state_t* src_state);
737 
738 XXH_PUBLIC_API XXH_errorcode XXH64_reset  (XXH64_state_t* statePtr, XXH64_hash_t seed);
739 XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* statePtr, const void* input, size_t length);
740 XXH_PUBLIC_API XXH64_hash_t  XXH64_digest (const XXH64_state_t* statePtr);
741 
742 /*******   Canonical representation   *******/
743 typedef struct { unsigned char digest[sizeof(XXH64_hash_t)]; } XXH64_canonical_t;
744 XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash);
745 XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src);
746 
747 /*!
748  * @}
749  * ************************************************************************
750  * @defgroup xxh3_family XXH3 family
751  * @ingroup public
752  * @{
753  *
754  * XXH3 is a more recent hash algorithm featuring:
755  *  - Improved speed for both small and large inputs
756  *  - True 64-bit and 128-bit outputs
757  *  - SIMD acceleration
758  *  - Improved 32-bit viability
759  *
760  * Speed analysis methodology is explained here:
761  *
762  *    https://fastcompression.blogspot.com/2019/03/presenting-xxh3.html
763  *
764  * Compared to XXH64, expect XXH3 to run approximately
765  * ~2x faster on large inputs and >3x faster on small ones,
766  * exact differences vary depending on platform.
767  *
768  * XXH3's speed benefits greatly from SIMD and 64-bit arithmetic,
769  * but does not require it.
770  * Any 32-bit and 64-bit targets that can run XXH32 smoothly
771  * can run XXH3 at competitive speeds, even without vector support.
772  * Further details are explained in the implementation.
773  *
774  * Optimized implementations are provided for AVX512, AVX2, SSE2, NEON, POWER8,
775  * ZVector and scalar targets. This can be controlled via the XXH_VECTOR macro.
776  *
777  * XXH3 implementation is portable:
778  * it has a generic C90 formulation that can be compiled on any platform,
779  * all implementations generage exactly the same hash value on all platforms.
780  * Starting from v0.8.0, it's also labelled "stable", meaning that
781  * any future version will also generate the same hash value.
782  *
783  * XXH3 offers 2 variants, _64bits and _128bits.
784  *
785  * When only 64 bits are needed, prefer invoking the _64bits variant, as it
786  * reduces the amount of mixing, resulting in faster speed on small inputs.
787  * It's also generally simpler to manipulate a scalar return type than a struct.
788  *
789  * The API supports one-shot hashing, streaming mode, and custom secrets.
790  */
791 
792 /*-**********************************************************************
793 *  XXH3 64-bit variant
794 ************************************************************************/
795 
796 /* XXH3_64bits():
797  * default 64-bit variant, using default secret and default seed of 0.
798  * It's the fastest variant. */
799 XXH_PUBLIC_API XXH64_hash_t XXH3_64bits(const void* data, size_t len);
800 
801 /*
802  * XXH3_64bits_withSeed():
803  * This variant generates a custom secret on the fly
804  * based on default secret altered using the `seed` value.
805  * While this operation is decently fast, note that it's not completely free.
806  * Note: seed==0 produces the same results as XXH3_64bits().
807  */
808 XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSeed(const void* data, size_t len, XXH64_hash_t seed);
809 
810 /*!
811  * The bare minimum size for a custom secret.
812  *
813  * @see
814  *  XXH3_64bits_withSecret(), XXH3_64bits_reset_withSecret(),
815  *  XXH3_128bits_withSecret(), XXH3_128bits_reset_withSecret().
816  */
817 #define XXH3_SECRET_SIZE_MIN 136
818 
819 /*
820  * XXH3_64bits_withSecret():
821  * It's possible to provide any blob of bytes as a "secret" to generate the hash.
822  * This makes it more difficult for an external actor to prepare an intentional collision.
823  * The main condition is that secretSize *must* be large enough (>= XXH3_SECRET_SIZE_MIN).
824  * However, the quality of the secret impacts the dispersion of the hash algorithm.
825  * Therefore, the secret _must_ look like a bunch of random bytes.
826  * Avoid "trivial" or structured data such as repeated sequences or a text document.
827  * Whenever in doubt about the "randomness" of the blob of bytes,
828  * consider employing "XXH3_generateSecret()" instead (see below).
829  * It will generate a proper high entropy secret derived from the blob of bytes.
830  * Another advantage of using XXH3_generateSecret() is that
831  * it guarantees that all bits within the initial blob of bytes
832  * will impact every bit of the output.
833  * This is not necessarily the case when using the blob of bytes directly
834  * because, when hashing _small_ inputs, only a portion of the secret is employed.
835  */
836 XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSecret(const void* data, size_t len, const void* secret, size_t secretSize);
837 
838 
839 /*******   Streaming   *******/
840 /*
841  * Streaming requires state maintenance.
842  * This operation costs memory and CPU.
843  * As a consequence, streaming is slower than one-shot hashing.
844  * For better performance, prefer one-shot functions whenever applicable.
845  */
846 
847 /*!
848  * @brief The state struct for the XXH3 streaming API.
849  *
850  * @see XXH3_state_s for details.
851  */
852 typedef struct XXH3_state_s XXH3_state_t;
853 XXH_PUBLIC_API XXH3_state_t* XXH3_createState(void);
854 XXH_PUBLIC_API XXH_errorcode XXH3_freeState(XXH3_state_t* statePtr);
855 XXH_PUBLIC_API void XXH3_copyState(XXH3_state_t* dst_state, const XXH3_state_t* src_state);
856 
857 /*
858  * XXH3_64bits_reset():
859  * Initialize with default parameters.
860  * digest will be equivalent to `XXH3_64bits()`.
861  */
862 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset(XXH3_state_t* statePtr);
863 /*
864  * XXH3_64bits_reset_withSeed():
865  * Generate a custom secret from `seed`, and store it into `statePtr`.
866  * digest will be equivalent to `XXH3_64bits_withSeed()`.
867  */
868 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSeed(XXH3_state_t* statePtr, XXH64_hash_t seed);
869 /*
870  * XXH3_64bits_reset_withSecret():
871  * `secret` is referenced, it _must outlive_ the hash streaming session.
872  * Similar to one-shot API, `secretSize` must be >= `XXH3_SECRET_SIZE_MIN`,
873  * and the quality of produced hash values depends on secret's entropy
874  * (secret's content should look like a bunch of random bytes).
875  * When in doubt about the randomness of a candidate `secret`,
876  * consider employing `XXH3_generateSecret()` instead (see below).
877  */
878 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSecret(XXH3_state_t* statePtr, const void* secret, size_t secretSize);
879 
880 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_update (XXH3_state_t* statePtr, const void* input, size_t length);
881 XXH_PUBLIC_API XXH64_hash_t  XXH3_64bits_digest (const XXH3_state_t* statePtr);
882 
883 /* note : canonical representation of XXH3 is the same as XXH64
884  * since they both produce XXH64_hash_t values */
885 
886 
887 /*-**********************************************************************
888 *  XXH3 128-bit variant
889 ************************************************************************/
890 
891 /*!
892  * @brief The return value from 128-bit hashes.
893  *
894  * Stored in little endian order, although the fields themselves are in native
895  * endianness.
896  */
897 typedef struct {
898     XXH64_hash_t low64;   /*!< `value & 0xFFFFFFFFFFFFFFFF` */
899     XXH64_hash_t high64;  /*!< `value >> 64` */
900 } XXH128_hash_t;
901 
902 XXH_PUBLIC_API XXH128_hash_t XXH3_128bits(const void* data, size_t len);
903 XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_withSeed(const void* data, size_t len, XXH64_hash_t seed);
904 XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_withSecret(const void* data, size_t len, const void* secret, size_t secretSize);
905 
906 /*******   Streaming   *******/
907 /*
908  * Streaming requires state maintenance.
909  * This operation costs memory and CPU.
910  * As a consequence, streaming is slower than one-shot hashing.
911  * For better performance, prefer one-shot functions whenever applicable.
912  *
913  * XXH3_128bits uses the same XXH3_state_t as XXH3_64bits().
914  * Use already declared XXH3_createState() and XXH3_freeState().
915  *
916  * All reset and streaming functions have same meaning as their 64-bit counterpart.
917  */
918 
919 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset(XXH3_state_t* statePtr);
920 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSeed(XXH3_state_t* statePtr, XXH64_hash_t seed);
921 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSecret(XXH3_state_t* statePtr, const void* secret, size_t secretSize);
922 
923 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_update (XXH3_state_t* statePtr, const void* input, size_t length);
924 XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_digest (const XXH3_state_t* statePtr);
925 
926 /* Following helper functions make it possible to compare XXH128_hast_t values.
927  * Since XXH128_hash_t is a structure, this capability is not offered by the language.
928  * Note: For better performance, these functions can be inlined using XXH_INLINE_ALL */
929 
930 /*!
931  * XXH128_isEqual():
932  * Return: 1 if `h1` and `h2` are equal, 0 if they are not.
933  */
934 XXH_PUBLIC_API int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2);
935 
936 /*!
937  * XXH128_cmp():
938  *
939  * This comparator is compatible with stdlib's `qsort()`/`bsearch()`.
940  *
941  * return: >0 if *h128_1  > *h128_2
942  *         =0 if *h128_1 == *h128_2
943  *         <0 if *h128_1  < *h128_2
944  */
945 XXH_PUBLIC_API int XXH128_cmp(const void* h128_1, const void* h128_2);
946 
947 
948 /*******   Canonical representation   *******/
949 typedef struct { unsigned char digest[sizeof(XXH128_hash_t)]; } XXH128_canonical_t;
950 XXH_PUBLIC_API void XXH128_canonicalFromHash(XXH128_canonical_t* dst, XXH128_hash_t hash);
951 XXH_PUBLIC_API XXH128_hash_t XXH128_hashFromCanonical(const XXH128_canonical_t* src);
952 
953 
954 #endif  /* XXH_NO_LONG_LONG */
955 
956 /*!
957  * @}
958  */
959 #endif /* XXHASH_H_5627135585666179 */
960 
961 
962 
963 #if defined(XXH_STATIC_LINKING_ONLY) && !defined(XXHASH_H_STATIC_13879238742)
964 #define XXHASH_H_STATIC_13879238742
965 /* ****************************************************************************
966  * This section contains declarations which are not guaranteed to remain stable.
967  * They may change in future versions, becoming incompatible with a different
968  * version of the library.
969  * These declarations should only be used with static linking.
970  * Never use them in association with dynamic linking!
971  ***************************************************************************** */
972 
973 /*
974  * These definitions are only present to allow static allocation
975  * of XXH states, on stack or in a struct, for example.
976  * Never **ever** access their members directly.
977  */
978 
979 /*!
980  * @internal
981  * @brief Structure for XXH32 streaming API.
982  *
983  * @note This is only defined when @ref XXH_STATIC_LINKING_ONLY,
984  * @ref XXH_INLINE_ALL, or @ref XXH_IMPLEMENTATION is defined. Otherwise it is
985  * an opaque type. This allows fields to safely be changed.
986  *
987  * Typedef'd to @ref XXH32_state_t.
988  * Do not access the members of this struct directly.
989  * @see XXH64_state_s, XXH3_state_s
990  */
991 struct XXH32_state_s {
992    XXH32_hash_t total_len_32; /*!< Total length hashed, modulo 2^32 */
993    XXH32_hash_t large_len;    /*!< Whether the hash is >= 16 (handles @ref total_len_32 overflow) */
994    XXH32_hash_t v[4];         /*!< Accumulator lanes */
995    XXH32_hash_t mem32[4];     /*!< Internal buffer for partial reads. Treated as unsigned char[16]. */
996    XXH32_hash_t memsize;      /*!< Amount of data in @ref mem32 */
997    XXH32_hash_t reserved;     /*!< Reserved field. Do not read or write to it, it may be removed. */
998 };   /* typedef'd to XXH32_state_t */
999 
1000 
1001 #ifndef XXH_NO_LONG_LONG  /* defined when there is no 64-bit support */
1002 
1003 /*!
1004  * @internal
1005  * @brief Structure for XXH64 streaming API.
1006  *
1007  * @note This is only defined when @ref XXH_STATIC_LINKING_ONLY,
1008  * @ref XXH_INLINE_ALL, or @ref XXH_IMPLEMENTATION is defined. Otherwise it is
1009  * an opaque type. This allows fields to safely be changed.
1010  *
1011  * Typedef'd to @ref XXH64_state_t.
1012  * Do not access the members of this struct directly.
1013  * @see XXH32_state_s, XXH3_state_s
1014  */
1015 struct XXH64_state_s {
1016    XXH64_hash_t total_len;    /*!< Total length hashed. This is always 64-bit. */
1017    XXH64_hash_t v[4];         /*!< Accumulator lanes */
1018    XXH64_hash_t mem64[4];     /*!< Internal buffer for partial reads. Treated as unsigned char[32]. */
1019    XXH32_hash_t memsize;      /*!< Amount of data in @ref mem64 */
1020    XXH32_hash_t reserved32;   /*!< Reserved field, needed for padding anyways*/
1021    XXH64_hash_t reserved64;   /*!< Reserved field. Do not read or write to it, it may be removed. */
1022 };   /* typedef'd to XXH64_state_t */
1023 
1024 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* >= C11 */
1025 #  include <stdalign.h>
1026 #  define XXH_ALIGN(n)      alignas(n)
1027 #elif defined(__cplusplus) && (__cplusplus >= 201103L) /* >= C++11 */
1028 /* In C++ alignas() is a keyword */
1029 #  define XXH_ALIGN(n)      alignas(n)
1030 #elif defined(__GNUC__)
1031 #  define XXH_ALIGN(n)      __attribute__ ((aligned(n)))
1032 #elif defined(_MSC_VER)
1033 #  define XXH_ALIGN(n)      __declspec(align(n))
1034 #else
1035 #  define XXH_ALIGN(n)   /* disabled */
1036 #endif
1037 
1038 /* Old GCC versions only accept the attribute after the type in structures. */
1039 #if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L))   /* C11+ */ \
1040     && ! (defined(__cplusplus) && (__cplusplus >= 201103L)) /* >= C++11 */ \
1041     && defined(__GNUC__)
1042 #   define XXH_ALIGN_MEMBER(align, type) type XXH_ALIGN(align)
1043 #else
1044 #   define XXH_ALIGN_MEMBER(align, type) XXH_ALIGN(align) type
1045 #endif
1046 
1047 /*!
1048  * @brief The size of the internal XXH3 buffer.
1049  *
1050  * This is the optimal update size for incremental hashing.
1051  *
1052  * @see XXH3_64b_update(), XXH3_128b_update().
1053  */
1054 #define XXH3_INTERNALBUFFER_SIZE 256
1055 
1056 /*!
1057  * @brief Default size of the secret buffer (and @ref XXH3_kSecret).
1058  *
1059  * This is the size used in @ref XXH3_kSecret and the seeded functions.
1060  *
1061  * Not to be confused with @ref XXH3_SECRET_SIZE_MIN.
1062  */
1063 #define XXH3_SECRET_DEFAULT_SIZE 192
1064 
1065 /*!
1066  * @internal
1067  * @brief Structure for XXH3 streaming API.
1068  *
1069  * @note This is only defined when @ref XXH_STATIC_LINKING_ONLY,
1070  * @ref XXH_INLINE_ALL, or @ref XXH_IMPLEMENTATION is defined.
1071  * Otherwise it is an opaque type.
1072  * Never use this definition in combination with dynamic library.
1073  * This allows fields to safely be changed in the future.
1074  *
1075  * @note ** This structure has a strict alignment requirement of 64 bytes!! **
1076  * Do not allocate this with `malloc()` or `new`,
1077  * it will not be sufficiently aligned.
1078  * Use @ref XXH3_createState() and @ref XXH3_freeState(), or stack allocation.
1079  *
1080  * Typedef'd to @ref XXH3_state_t.
1081  * Do never access the members of this struct directly.
1082  *
1083  * @see XXH3_INITSTATE() for stack initialization.
1084  * @see XXH3_createState(), XXH3_freeState().
1085  * @see XXH32_state_s, XXH64_state_s
1086  */
1087 struct XXH3_state_s {
1088    XXH_ALIGN_MEMBER(64, XXH64_hash_t acc[8]);
1089        /*!< The 8 accumulators. Similar to `vN` in @ref XXH32_state_s::v1 and @ref XXH64_state_s */
1090    XXH_ALIGN_MEMBER(64, unsigned char customSecret[XXH3_SECRET_DEFAULT_SIZE]);
1091        /*!< Used to store a custom secret generated from a seed. */
1092    XXH_ALIGN_MEMBER(64, unsigned char buffer[XXH3_INTERNALBUFFER_SIZE]);
1093        /*!< The internal buffer. @see XXH32_state_s::mem32 */
1094    XXH32_hash_t bufferedSize;
1095        /*!< The amount of memory in @ref buffer, @see XXH32_state_s::memsize */
1096    XXH32_hash_t useSeed;
1097        /*!< Reserved field. Needed for padding on 64-bit. */
1098    size_t nbStripesSoFar;
1099        /*!< Number or stripes processed. */
1100    XXH64_hash_t totalLen;
1101        /*!< Total length hashed. 64-bit even on 32-bit targets. */
1102    size_t nbStripesPerBlock;
1103        /*!< Number of stripes per block. */
1104    size_t secretLimit;
1105        /*!< Size of @ref customSecret or @ref extSecret */
1106    XXH64_hash_t seed;
1107        /*!< Seed for _withSeed variants. Must be zero otherwise, @see XXH3_INITSTATE() */
1108    XXH64_hash_t reserved64;
1109        /*!< Reserved field. */
1110    const unsigned char* extSecret;
1111        /*!< Reference to an external secret for the _withSecret variants, NULL
1112         *   for other variants. */
1113    /* note: there may be some padding at the end due to alignment on 64 bytes */
1114 }; /* typedef'd to XXH3_state_t */
1115 
1116 #undef XXH_ALIGN_MEMBER
1117 
1118 /*!
1119  * @brief Initializes a stack-allocated `XXH3_state_s`.
1120  *
1121  * When the @ref XXH3_state_t structure is merely emplaced on stack,
1122  * it should be initialized with XXH3_INITSTATE() or a memset()
1123  * in case its first reset uses XXH3_NNbits_reset_withSeed().
1124  * This init can be omitted if the first reset uses default or _withSecret mode.
1125  * This operation isn't necessary when the state is created with XXH3_createState().
1126  * Note that this doesn't prepare the state for a streaming operation,
1127  * it's still necessary to use XXH3_NNbits_reset*() afterwards.
1128  */
1129 #define XXH3_INITSTATE(XXH3_state_ptr)   { (XXH3_state_ptr)->seed = 0; }
1130 
1131 
1132 /* XXH128() :
1133  * simple alias to pre-selected XXH3_128bits variant
1134  */
1135 XXH_PUBLIC_API XXH128_hash_t XXH128(const void* data, size_t len, XXH64_hash_t seed);
1136 
1137 
1138 /* ===   Experimental API   === */
1139 /* Symbols defined below must be considered tied to a specific library version. */
1140 
1141 /*
1142  * XXH3_generateSecret():
1143  *
1144  * Derive a high-entropy secret from any user-defined content, named customSeed.
1145  * The generated secret can be used in combination with `*_withSecret()` functions.
1146  * The `_withSecret()` variants are useful to provide a higher level of protection than 64-bit seed,
1147  * as it becomes much more difficult for an external actor to guess how to impact the calculation logic.
1148  *
1149  * The function accepts as input a custom seed of any length and any content,
1150  * and derives from it a high-entropy secret of length @secretSize
1151  * into an already allocated buffer @secretBuffer.
1152  * @secretSize must be >= XXH3_SECRET_SIZE_MIN
1153  *
1154  * The generated secret can then be used with any `*_withSecret()` variant.
1155  * Functions `XXH3_128bits_withSecret()`, `XXH3_64bits_withSecret()`,
1156  * `XXH3_128bits_reset_withSecret()` and `XXH3_64bits_reset_withSecret()`
1157  * are part of this list. They all accept a `secret` parameter
1158  * which must be large enough for implementation reasons (>= XXH3_SECRET_SIZE_MIN)
1159  * _and_ feature very high entropy (consist of random-looking bytes).
1160  * These conditions can be a high bar to meet, so
1161  * XXH3_generateSecret() can be employed to ensure proper quality.
1162  *
1163  * customSeed can be anything. It can have any size, even small ones,
1164  * and its content can be anything, even "poor entropy" sources such as a bunch of zeroes.
1165  * The resulting `secret` will nonetheless provide all required qualities.
1166  *
1167  * When customSeedSize > 0, supplying NULL as customSeed is undefined behavior.
1168  */
1169 XXH_PUBLIC_API XXH_errorcode XXH3_generateSecret(void* secretBuffer, size_t secretSize, const void* customSeed, size_t customSeedSize);
1170 
1171 
1172 /*
1173  * XXH3_generateSecret_fromSeed():
1174  *
1175  * Generate the same secret as the _withSeed() variants.
1176  *
1177  * The resulting secret has a length of XXH3_SECRET_DEFAULT_SIZE (necessarily).
1178  * @secretBuffer must be already allocated, of size at least XXH3_SECRET_DEFAULT_SIZE bytes.
1179  *
1180  * The generated secret can be used in combination with
1181  *`*_withSecret()` and `_withSecretandSeed()` variants.
1182  * This generator is notably useful in combination with `_withSecretandSeed()`,
1183  * as a way to emulate a faster `_withSeed()` variant.
1184  */
1185 XXH_PUBLIC_API void XXH3_generateSecret_fromSeed(void* secretBuffer, XXH64_hash_t seed);
1186 
1187 /*
1188  * *_withSecretandSeed() :
1189  * These variants generate hash values using either
1190  * @seed for "short" keys (< XXH3_MIDSIZE_MAX = 240 bytes)
1191  * or @secret for "large" keys (>= XXH3_MIDSIZE_MAX).
1192  *
1193  * This generally benefits speed, compared to `_withSeed()` or `_withSecret()`.
1194  * `_withSeed()` has to generate the secret on the fly for "large" keys.
1195  * It's fast, but can be perceptible for "not so large" keys (< 1 KB).
1196  * `_withSecret()` has to generate the masks on the fly for "small" keys,
1197  * which requires more instructions than _withSeed() variants.
1198  * Therefore, _withSecretandSeed variant combines the best of both worlds.
1199  *
1200  * When @secret has been generated by XXH3_generateSecret_fromSeed(),
1201  * this variant produces *exactly* the same results as `_withSeed()` variant,
1202  * hence offering only a pure speed benefit on "large" input,
1203  * by skipping the need to regenerate the secret for every large input.
1204  *
1205  * Another usage scenario is to hash the secret to a 64-bit hash value,
1206  * for example with XXH3_64bits(), which then becomes the seed,
1207  * and then employ both the seed and the secret in _withSecretandSeed().
1208  * On top of speed, an added benefit is that each bit in the secret
1209  * has a 50% chance to swap each bit in the output,
1210  * via its impact to the seed.
1211  * This is not guaranteed when using the secret directly in "small data" scenarios,
1212  * because only portions of the secret are employed for small data.
1213  */
1214 XXH_PUBLIC_API XXH64_hash_t
1215 XXH3_64bits_withSecretandSeed(const void* data, size_t len,
1216                               const void* secret, size_t secretSize,
1217                               XXH64_hash_t seed);
1218 
1219 XXH_PUBLIC_API XXH128_hash_t
1220 XXH3_128bits_withSecretandSeed(const void* data, size_t len,
1221                                const void* secret, size_t secretSize,
1222                                XXH64_hash_t seed64);
1223 
1224 XXH_PUBLIC_API XXH_errorcode
1225 XXH3_64bits_reset_withSecretandSeed(XXH3_state_t* statePtr,
1226                                     const void* secret, size_t secretSize,
1227                                     XXH64_hash_t seed64);
1228 
1229 XXH_PUBLIC_API XXH_errorcode
1230 XXH3_128bits_reset_withSecretandSeed(XXH3_state_t* statePtr,
1231                                      const void* secret, size_t secretSize,
1232                                      XXH64_hash_t seed64);
1233 
1234 
1235 #endif  /* XXH_NO_LONG_LONG */
1236 #if defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API)
1237 #  define XXH_IMPLEMENTATION
1238 #endif
1239 
1240 #endif  /* defined(XXH_STATIC_LINKING_ONLY) && !defined(XXHASH_H_STATIC_13879238742) */
1241 
1242 
1243 /* ======================================================================== */
1244 /* ======================================================================== */
1245 /* ======================================================================== */
1246 
1247 
1248 /*-**********************************************************************
1249  * xxHash implementation
1250  *-**********************************************************************
1251  * xxHash's implementation used to be hosted inside xxhash.c.
1252  *
1253  * However, inlining requires implementation to be visible to the compiler,
1254  * hence be included alongside the header.
1255  * Previously, implementation was hosted inside xxhash.c,
1256  * which was then #included when inlining was activated.
1257  * This construction created issues with a few build and install systems,
1258  * as it required xxhash.c to be stored in /include directory.
1259  *
1260  * xxHash implementation is now directly integrated within xxhash.h.
1261  * As a consequence, xxhash.c is no longer needed in /include.
1262  *
1263  * xxhash.c is still available and is still useful.
1264  * In a "normal" setup, when xxhash is not inlined,
1265  * xxhash.h only exposes the prototypes and public symbols,
1266  * while xxhash.c can be built into an object file xxhash.o
1267  * which can then be linked into the final binary.
1268  ************************************************************************/
1269 
1270 #if ( defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API) \
1271    || defined(XXH_IMPLEMENTATION) ) && !defined(XXH_IMPLEM_13a8737387)
1272 #  define XXH_IMPLEM_13a8737387
1273 
1274 /* *************************************
1275 *  Tuning parameters
1276 ***************************************/
1277 
1278 /*!
1279  * @defgroup tuning Tuning parameters
1280  * @{
1281  *
1282  * Various macros to control xxHash's behavior.
1283  */
1284 #ifdef XXH_DOXYGEN
1285 /*!
1286  * @brief Define this to disable 64-bit code.
1287  *
1288  * Useful if only using the @ref xxh32_family and you have a strict C90 compiler.
1289  */
1290 #  define XXH_NO_LONG_LONG
1291 #  undef XXH_NO_LONG_LONG /* don't actually */
1292 /*!
1293  * @brief Controls how unaligned memory is accessed.
1294  *
1295  * By default, access to unaligned memory is controlled by `memcpy()`, which is
1296  * safe and portable.
1297  *
1298  * Unfortunately, on some target/compiler combinations, the generated assembly
1299  * is sub-optimal.
1300  *
1301  * The below switch allow selection of a different access method
1302  * in the search for improved performance.
1303  *
1304  * @par Possible options:
1305  *
1306  *  - `XXH_FORCE_MEMORY_ACCESS=0` (default): `memcpy`
1307  *   @par
1308  *     Use `memcpy()`. Safe and portable. Note that most modern compilers will
1309  *     eliminate the function call and treat it as an unaligned access.
1310  *
1311  *  - `XXH_FORCE_MEMORY_ACCESS=1`: `__attribute__((packed))`
1312  *   @par
1313  *     Depends on compiler extensions and is therefore not portable.
1314  *     This method is safe _if_ your compiler supports it,
1315  *     and *generally* as fast or faster than `memcpy`.
1316  *
1317  *  - `XXH_FORCE_MEMORY_ACCESS=2`: Direct cast
1318  *  @par
1319  *     Casts directly and dereferences. This method doesn't depend on the
1320  *     compiler, but it violates the C standard as it directly dereferences an
1321  *     unaligned pointer. It can generate buggy code on targets which do not
1322  *     support unaligned memory accesses, but in some circumstances, it's the
1323  *     only known way to get the most performance.
1324  *
1325  *  - `XXH_FORCE_MEMORY_ACCESS=3`: Byteshift
1326  *  @par
1327  *     Also portable. This can generate the best code on old compilers which don't
1328  *     inline small `memcpy()` calls, and it might also be faster on big-endian
1329  *     systems which lack a native byteswap instruction. However, some compilers
1330  *     will emit literal byteshifts even if the target supports unaligned access.
1331  *  .
1332  *
1333  * @warning
1334  *   Methods 1 and 2 rely on implementation-defined behavior. Use these with
1335  *   care, as what works on one compiler/platform/optimization level may cause
1336  *   another to read garbage data or even crash.
1337  *
1338  * See http://fastcompression.blogspot.com/2015/08/accessing-unaligned-memory.html for details.
1339  *
1340  * Prefer these methods in priority order (0 > 3 > 1 > 2)
1341  */
1342 #  define XXH_FORCE_MEMORY_ACCESS 0
1343 
1344 /*!
1345  * @def XXH_FORCE_ALIGN_CHECK
1346  * @brief If defined to non-zero, adds a special path for aligned inputs (XXH32()
1347  * and XXH64() only).
1348  *
1349  * This is an important performance trick for architectures without decent
1350  * unaligned memory access performance.
1351  *
1352  * It checks for input alignment, and when conditions are met, uses a "fast
1353  * path" employing direct 32-bit/64-bit reads, resulting in _dramatically
1354  * faster_ read speed.
1355  *
1356  * The check costs one initial branch per hash, which is generally negligible,
1357  * but not zero.
1358  *
1359  * Moreover, it's not useful to generate an additional code path if memory
1360  * access uses the same instruction for both aligned and unaligned
1361  * addresses (e.g. x86 and aarch64).
1362  *
1363  * In these cases, the alignment check can be removed by setting this macro to 0.
1364  * Then the code will always use unaligned memory access.
1365  * Align check is automatically disabled on x86, x64 & arm64,
1366  * which are platforms known to offer good unaligned memory accesses performance.
1367  *
1368  * This option does not affect XXH3 (only XXH32 and XXH64).
1369  */
1370 #  define XXH_FORCE_ALIGN_CHECK 0
1371 
1372 /*!
1373  * @def XXH_NO_INLINE_HINTS
1374  * @brief When non-zero, sets all functions to `static`.
1375  *
1376  * By default, xxHash tries to force the compiler to inline almost all internal
1377  * functions.
1378  *
1379  * This can usually improve performance due to reduced jumping and improved
1380  * constant folding, but significantly increases the size of the binary which
1381  * might not be favorable.
1382  *
1383  * Additionally, sometimes the forced inlining can be detrimental to performance,
1384  * depending on the architecture.
1385  *
1386  * XXH_NO_INLINE_HINTS marks all internal functions as static, giving the
1387  * compiler full control on whether to inline or not.
1388  *
1389  * When not optimizing (-O0), optimizing for size (-Os, -Oz), or using
1390  * -fno-inline with GCC or Clang, this will automatically be defined.
1391  */
1392 #  define XXH_NO_INLINE_HINTS 0
1393 
1394 /*!
1395  * @def XXH32_ENDJMP
1396  * @brief Whether to use a jump for `XXH32_finalize`.
1397  *
1398  * For performance, `XXH32_finalize` uses multiple branches in the finalizer.
1399  * This is generally preferable for performance,
1400  * but depending on exact architecture, a jmp may be preferable.
1401  *
1402  * This setting is only possibly making a difference for very small inputs.
1403  */
1404 #  define XXH32_ENDJMP 0
1405 
1406 /*!
1407  * @internal
1408  * @brief Redefines old internal names.
1409  *
1410  * For compatibility with code that uses xxHash's internals before the names
1411  * were changed to improve namespacing. There is no other reason to use this.
1412  */
1413 #  define XXH_OLD_NAMES
1414 #  undef XXH_OLD_NAMES /* don't actually use, it is ugly. */
1415 #endif /* XXH_DOXYGEN */
1416 /*!
1417  * @}
1418  */
1419 
1420 #ifndef XXH_FORCE_MEMORY_ACCESS   /* can be defined externally, on command line for example */
1421    /* prefer __packed__ structures (method 1) for gcc on armv7+ and mips */
1422 #  if !defined(__clang__) && \
1423 ( \
1424     (defined(__INTEL_COMPILER) && !defined(_WIN32)) || \
1425     ( \
1426         defined(__GNUC__) && ( \
1427             (defined(__ARM_ARCH) && __ARM_ARCH >= 7) || \
1428             ( \
1429                 defined(__mips__) && \
1430                 (__mips <= 5 || __mips_isa_rev < 6) && \
1431                 (!defined(__mips16) || defined(__mips_mips16e2)) \
1432             ) \
1433         ) \
1434     ) \
1435 )
1436 #    define XXH_FORCE_MEMORY_ACCESS 1
1437 #  endif
1438 #endif
1439 
1440 #ifndef XXH_FORCE_ALIGN_CHECK  /* can be defined externally */
1441 #  if defined(__i386)  || defined(__x86_64__) || defined(__aarch64__) \
1442    || defined(_M_IX86) || defined(_M_X64)     || defined(_M_ARM64) /* visual */
1443 #    define XXH_FORCE_ALIGN_CHECK 0
1444 #  else
1445 #    define XXH_FORCE_ALIGN_CHECK 1
1446 #  endif
1447 #endif
1448 
1449 #ifndef XXH_NO_INLINE_HINTS
1450 #  if defined(__OPTIMIZE_SIZE__) /* -Os, -Oz */ \
1451    || defined(__NO_INLINE__)     /* -O0, -fno-inline */
1452 #    define XXH_NO_INLINE_HINTS 1
1453 #  else
1454 #    define XXH_NO_INLINE_HINTS 0
1455 #  endif
1456 #endif
1457 
1458 #ifndef XXH32_ENDJMP
1459 /* generally preferable for performance */
1460 #  define XXH32_ENDJMP 0
1461 #endif
1462 
1463 /*!
1464  * @defgroup impl Implementation
1465  * @{
1466  */
1467 
1468 
1469 /* *************************************
1470 *  Includes & Memory related functions
1471 ***************************************/
1472 /*
1473  * Modify the local functions below should you wish to use
1474  * different memory routines for malloc() and free()
1475  */
1476 #include <stdlib.h>
1477 
1478 /*!
1479  * @internal
1480  * @brief Modify this function to use a different routine than malloc().
1481  */
XXH_malloc(size_t s)1482 static void* XXH_malloc(size_t s) { return malloc(s); }
1483 
1484 /*!
1485  * @internal
1486  * @brief Modify this function to use a different routine than free().
1487  */
XXH_free(void * p)1488 static void XXH_free(void* p) { free(p); }
1489 
1490 #include <string.h>
1491 
1492 /*!
1493  * @internal
1494  * @brief Modify this function to use a different routine than memcpy().
1495  */
XXH_memcpy(void * dest,const void * src,size_t size)1496 static void* XXH_memcpy(void* dest, const void* src, size_t size)
1497 {
1498     return memcpy(dest,src,size);
1499 }
1500 
1501 #include <limits.h>   /* ULLONG_MAX */
1502 
1503 
1504 /* *************************************
1505 *  Compiler Specific Options
1506 ***************************************/
1507 #ifdef _MSC_VER /* Visual Studio warning fix */
1508 #  pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
1509 #endif
1510 
1511 #if XXH_NO_INLINE_HINTS  /* disable inlining hints */
1512 #  if defined(__GNUC__) || defined(__clang__)
1513 #    define XXH_FORCE_INLINE static __attribute__((unused))
1514 #  else
1515 #    define XXH_FORCE_INLINE static
1516 #  endif
1517 #  define XXH_NO_INLINE static
1518 /* enable inlining hints */
1519 #elif defined(__GNUC__) || defined(__clang__)
1520 #  define XXH_FORCE_INLINE static __inline__ __attribute__((always_inline, unused))
1521 #  define XXH_NO_INLINE static __attribute__((noinline))
1522 #elif defined(_MSC_VER)  /* Visual Studio */
1523 #  define XXH_FORCE_INLINE static __forceinline
1524 #  define XXH_NO_INLINE static __declspec(noinline)
1525 #elif defined (__cplusplus) \
1526   || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L))   /* C99 */
1527 #  define XXH_FORCE_INLINE static inline
1528 #  define XXH_NO_INLINE static
1529 #else
1530 #  define XXH_FORCE_INLINE static
1531 #  define XXH_NO_INLINE static
1532 #endif
1533 
1534 
1535 
1536 /* *************************************
1537 *  Debug
1538 ***************************************/
1539 /*!
1540  * @ingroup tuning
1541  * @def XXH_DEBUGLEVEL
1542  * @brief Sets the debugging level.
1543  *
1544  * XXH_DEBUGLEVEL is expected to be defined externally, typically via the
1545  * compiler's command line options. The value must be a number.
1546  */
1547 #ifndef XXH_DEBUGLEVEL
1548 #  ifdef DEBUGLEVEL /* backwards compat */
1549 #    define XXH_DEBUGLEVEL DEBUGLEVEL
1550 #  else
1551 #    define XXH_DEBUGLEVEL 0
1552 #  endif
1553 #endif
1554 
1555 #if (XXH_DEBUGLEVEL>=1)
1556 #  include <assert.h>   /* note: can still be disabled with NDEBUG */
1557 #  define XXH_ASSERT(c)   assert(c)
1558 #else
1559 #  define XXH_ASSERT(c)   ((void)0)
1560 #endif
1561 
1562 /* note: use after variable declarations */
1563 #ifndef XXH_STATIC_ASSERT
1564 #  if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)    /* C11 */
1565 #    include <assert.h>
1566 #    ifndef static_assert /* uClibc does not define static_assert */
1567 #      define static_assert _Static_assert
1568 #    endif
1569 #    define XXH_STATIC_ASSERT_WITH_MESSAGE(c,m) do { static_assert((c),m); } while(0)
1570 #  elif defined(__cplusplus) && (__cplusplus >= 201103L)            /* C++11 */
1571 #    define XXH_STATIC_ASSERT_WITH_MESSAGE(c,m) do { static_assert((c),m); } while(0)
1572 #  else
1573 #    define XXH_STATIC_ASSERT_WITH_MESSAGE(c,m) do { struct xxh_sa { char x[(c) ? 1 : -1]; }; } while(0)
1574 #  endif
1575 #  define XXH_STATIC_ASSERT(c) XXH_STATIC_ASSERT_WITH_MESSAGE((c),#c)
1576 #endif
1577 
1578 /*!
1579  * @internal
1580  * @def XXH_COMPILER_GUARD(var)
1581  * @brief Used to prevent unwanted optimizations for @p var.
1582  *
1583  * It uses an empty GCC inline assembly statement with a register constraint
1584  * which forces @p var into a general purpose register (eg eax, ebx, ecx
1585  * on x86) and marks it as modified.
1586  *
1587  * This is used in a few places to avoid unwanted autovectorization (e.g.
1588  * XXH32_round()). All vectorization we want is explicit via intrinsics,
1589  * and _usually_ isn't wanted elsewhere.
1590  *
1591  * We also use it to prevent unwanted constant folding for AArch64 in
1592  * XXH3_initCustomSecret_scalar().
1593  */
1594 #if defined(__GNUC__) || defined(__clang__)
1595 #  define XXH_COMPILER_GUARD(var) __asm__ __volatile__("" : "+r" (var))
1596 #else
1597 #  define XXH_COMPILER_GUARD(var) ((void)0)
1598 #endif
1599 
1600 /* *************************************
1601 *  Basic Types
1602 ***************************************/
1603 #if !defined (__VMS) \
1604  && (defined (__cplusplus) \
1605  || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
1606 # include <stdint.h>
1607   typedef uint8_t xxh_u8;
1608 #else
1609   typedef unsigned char xxh_u8;
1610 #endif
1611 typedef XXH32_hash_t xxh_u32;
1612 
1613 #ifdef XXH_OLD_NAMES
1614 #  define BYTE xxh_u8
1615 #  define U8   xxh_u8
1616 #  define U32  xxh_u32
1617 #endif
1618 
1619 /* ***   Memory access   *** */
1620 
1621 /*!
1622  * @internal
1623  * @fn xxh_u32 XXH_read32(const void* ptr)
1624  * @brief Reads an unaligned 32-bit integer from @p ptr in native endianness.
1625  *
1626  * Affected by @ref XXH_FORCE_MEMORY_ACCESS.
1627  *
1628  * @param ptr The pointer to read from.
1629  * @return The 32-bit native endian integer from the bytes at @p ptr.
1630  */
1631 
1632 /*!
1633  * @internal
1634  * @fn xxh_u32 XXH_readLE32(const void* ptr)
1635  * @brief Reads an unaligned 32-bit little endian integer from @p ptr.
1636  *
1637  * Affected by @ref XXH_FORCE_MEMORY_ACCESS.
1638  *
1639  * @param ptr The pointer to read from.
1640  * @return The 32-bit little endian integer from the bytes at @p ptr.
1641  */
1642 
1643 /*!
1644  * @internal
1645  * @fn xxh_u32 XXH_readBE32(const void* ptr)
1646  * @brief Reads an unaligned 32-bit big endian integer from @p ptr.
1647  *
1648  * Affected by @ref XXH_FORCE_MEMORY_ACCESS.
1649  *
1650  * @param ptr The pointer to read from.
1651  * @return The 32-bit big endian integer from the bytes at @p ptr.
1652  */
1653 
1654 /*!
1655  * @internal
1656  * @fn xxh_u32 XXH_readLE32_align(const void* ptr, XXH_alignment align)
1657  * @brief Like @ref XXH_readLE32(), but has an option for aligned reads.
1658  *
1659  * Affected by @ref XXH_FORCE_MEMORY_ACCESS.
1660  * Note that when @ref XXH_FORCE_ALIGN_CHECK == 0, the @p align parameter is
1661  * always @ref XXH_alignment::XXH_unaligned.
1662  *
1663  * @param ptr The pointer to read from.
1664  * @param align Whether @p ptr is aligned.
1665  * @pre
1666  *   If @p align == @ref XXH_alignment::XXH_aligned, @p ptr must be 4 byte
1667  *   aligned.
1668  * @return The 32-bit little endian integer from the bytes at @p ptr.
1669  */
1670 
1671 #if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==3))
1672 /*
1673  * Manual byteshift. Best for old compilers which don't inline memcpy.
1674  * We actually directly use XXH_readLE32 and XXH_readBE32.
1675  */
1676 #elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2))
1677 
1678 /*
1679  * Force direct memory access. Only works on CPU which support unaligned memory
1680  * access in hardware.
1681  */
XXH_read32(const void * memPtr)1682 static xxh_u32 XXH_read32(const void* memPtr) { return *(const xxh_u32*) memPtr; }
1683 
1684 #elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1))
1685 
1686 /*
1687  * __pack instructions are safer but compiler specific, hence potentially
1688  * problematic for some compilers.
1689  *
1690  * Currently only defined for GCC and ICC.
1691  */
1692 #ifdef XXH_OLD_NAMES
1693 typedef union { xxh_u32 u32; } __attribute__((packed)) unalign;
1694 #endif
XXH_read32(const void * ptr)1695 static xxh_u32 XXH_read32(const void* ptr)
1696 {
1697     typedef union { xxh_u32 u32; } __attribute__((packed)) xxh_unalign;
1698     return ((const xxh_unalign*)ptr)->u32;
1699 }
1700 
1701 #else
1702 
1703 /*
1704  * Portable and safe solution. Generally efficient.
1705  * see: http://fastcompression.blogspot.com/2015/08/accessing-unaligned-memory.html
1706  */
XXH_read32(const void * memPtr)1707 static xxh_u32 XXH_read32(const void* memPtr)
1708 {
1709     xxh_u32 val;
1710     XXH_memcpy(&val, memPtr, sizeof(val));
1711     return val;
1712 }
1713 
1714 #endif   /* XXH_FORCE_DIRECT_MEMORY_ACCESS */
1715 
1716 
1717 /* ***   Endianness   *** */
1718 
1719 /*!
1720  * @ingroup tuning
1721  * @def XXH_CPU_LITTLE_ENDIAN
1722  * @brief Whether the target is little endian.
1723  *
1724  * Defined to 1 if the target is little endian, or 0 if it is big endian.
1725  * It can be defined externally, for example on the compiler command line.
1726  *
1727  * If it is not defined,
1728  * a runtime check (which is usually constant folded) is used instead.
1729  *
1730  * @note
1731  *   This is not necessarily defined to an integer constant.
1732  *
1733  * @see XXH_isLittleEndian() for the runtime check.
1734  */
1735 #ifndef XXH_CPU_LITTLE_ENDIAN
1736 /*
1737  * Try to detect endianness automatically, to avoid the nonstandard behavior
1738  * in `XXH_isLittleEndian()`
1739  */
1740 #  if defined(_WIN32) /* Windows is always little endian */ \
1741      || defined(__LITTLE_ENDIAN__) \
1742      || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
1743 #    define XXH_CPU_LITTLE_ENDIAN 1
1744 #  elif defined(__BIG_ENDIAN__) \
1745      || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
1746 #    define XXH_CPU_LITTLE_ENDIAN 0
1747 #  else
1748 /*!
1749  * @internal
1750  * @brief Runtime check for @ref XXH_CPU_LITTLE_ENDIAN.
1751  *
1752  * Most compilers will constant fold this.
1753  */
XXH_isLittleEndian(void)1754 static int XXH_isLittleEndian(void)
1755 {
1756     /*
1757      * Portable and well-defined behavior.
1758      * Don't use static: it is detrimental to performance.
1759      */
1760     const union { xxh_u32 u; xxh_u8 c[4]; } one = { 1 };
1761     return one.c[0];
1762 }
1763 #   define XXH_CPU_LITTLE_ENDIAN   XXH_isLittleEndian()
1764 #  endif
1765 #endif
1766 
1767 
1768 
1769 
1770 /* ****************************************
1771 *  Compiler-specific Functions and Macros
1772 ******************************************/
1773 #define XXH_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
1774 
1775 #ifdef __has_builtin
1776 #  define XXH_HAS_BUILTIN(x) __has_builtin(x)
1777 #else
1778 #  define XXH_HAS_BUILTIN(x) 0
1779 #endif
1780 
1781 /*!
1782  * @internal
1783  * @def XXH_rotl32(x,r)
1784  * @brief 32-bit rotate left.
1785  *
1786  * @param x The 32-bit integer to be rotated.
1787  * @param r The number of bits to rotate.
1788  * @pre
1789  *   @p r > 0 && @p r < 32
1790  * @note
1791  *   @p x and @p r may be evaluated multiple times.
1792  * @return The rotated result.
1793  */
1794 #if !defined(NO_CLANG_BUILTIN) && XXH_HAS_BUILTIN(__builtin_rotateleft32) \
1795                                && XXH_HAS_BUILTIN(__builtin_rotateleft64)
1796 #  define XXH_rotl32 __builtin_rotateleft32
1797 #  define XXH_rotl64 __builtin_rotateleft64
1798 /* Note: although _rotl exists for minGW (GCC under windows), performance seems poor */
1799 #elif defined(_MSC_VER)
1800 #  define XXH_rotl32(x,r) _rotl(x,r)
1801 #  define XXH_rotl64(x,r) _rotl64(x,r)
1802 #else
1803 #  define XXH_rotl32(x,r) (((x) << (r)) | ((x) >> (32 - (r))))
1804 #  define XXH_rotl64(x,r) (((x) << (r)) | ((x) >> (64 - (r))))
1805 #endif
1806 
1807 /*!
1808  * @internal
1809  * @fn xxh_u32 XXH_swap32(xxh_u32 x)
1810  * @brief A 32-bit byteswap.
1811  *
1812  * @param x The 32-bit integer to byteswap.
1813  * @return @p x, byteswapped.
1814  */
1815 #if defined(_MSC_VER)     /* Visual Studio */
1816 #  define XXH_swap32 _byteswap_ulong
1817 #elif XXH_GCC_VERSION >= 403
1818 #  define XXH_swap32 __builtin_bswap32
1819 #else
XXH_swap32(xxh_u32 x)1820 static xxh_u32 XXH_swap32 (xxh_u32 x)
1821 {
1822     return  ((x << 24) & 0xff000000 ) |
1823             ((x <<  8) & 0x00ff0000 ) |
1824             ((x >>  8) & 0x0000ff00 ) |
1825             ((x >> 24) & 0x000000ff );
1826 }
1827 #endif
1828 
1829 
1830 /* ***************************
1831 *  Memory reads
1832 *****************************/
1833 
1834 /*!
1835  * @internal
1836  * @brief Enum to indicate whether a pointer is aligned.
1837  */
1838 typedef enum {
1839     XXH_aligned,  /*!< Aligned */
1840     XXH_unaligned /*!< Possibly unaligned */
1841 } XXH_alignment;
1842 
1843 /*
1844  * XXH_FORCE_MEMORY_ACCESS==3 is an endian-independent byteshift load.
1845  *
1846  * This is ideal for older compilers which don't inline memcpy.
1847  */
1848 #if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==3))
1849 
XXH_readLE32(const void * memPtr)1850 XXH_FORCE_INLINE xxh_u32 XXH_readLE32(const void* memPtr)
1851 {
1852     const xxh_u8* bytePtr = (const xxh_u8 *)memPtr;
1853     return bytePtr[0]
1854          | ((xxh_u32)bytePtr[1] << 8)
1855          | ((xxh_u32)bytePtr[2] << 16)
1856          | ((xxh_u32)bytePtr[3] << 24);
1857 }
1858 
XXH_readBE32(const void * memPtr)1859 XXH_FORCE_INLINE xxh_u32 XXH_readBE32(const void* memPtr)
1860 {
1861     const xxh_u8* bytePtr = (const xxh_u8 *)memPtr;
1862     return bytePtr[3]
1863          | ((xxh_u32)bytePtr[2] << 8)
1864          | ((xxh_u32)bytePtr[1] << 16)
1865          | ((xxh_u32)bytePtr[0] << 24);
1866 }
1867 
1868 #else
XXH_readLE32(const void * ptr)1869 XXH_FORCE_INLINE xxh_u32 XXH_readLE32(const void* ptr)
1870 {
1871     return XXH_CPU_LITTLE_ENDIAN ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr));
1872 }
1873 
XXH_readBE32(const void * ptr)1874 static xxh_u32 XXH_readBE32(const void* ptr)
1875 {
1876     return XXH_CPU_LITTLE_ENDIAN ? XXH_swap32(XXH_read32(ptr)) : XXH_read32(ptr);
1877 }
1878 #endif
1879 
1880 XXH_FORCE_INLINE xxh_u32
XXH_readLE32_align(const void * ptr,XXH_alignment align)1881 XXH_readLE32_align(const void* ptr, XXH_alignment align)
1882 {
1883     if (align==XXH_unaligned) {
1884         return XXH_readLE32(ptr);
1885     } else {
1886         return XXH_CPU_LITTLE_ENDIAN ? *(const xxh_u32*)ptr : XXH_swap32(*(const xxh_u32*)ptr);
1887     }
1888 }
1889 
1890 
1891 /* *************************************
1892 *  Misc
1893 ***************************************/
1894 /*! @ingroup public */
XXH_versionNumber(void)1895 XXH_PUBLIC_API unsigned XXH_versionNumber (void) { return XXH_VERSION_NUMBER; }
1896 
1897 
1898 /* *******************************************************************
1899 *  32-bit hash functions
1900 *********************************************************************/
1901 /*!
1902  * @}
1903  * @defgroup xxh32_impl XXH32 implementation
1904  * @ingroup impl
1905  * @{
1906  */
1907  /* #define instead of static const, to be used as initializers */
1908 #define XXH_PRIME32_1  0x9E3779B1U  /*!< 0b10011110001101110111100110110001 */
1909 #define XXH_PRIME32_2  0x85EBCA77U  /*!< 0b10000101111010111100101001110111 */
1910 #define XXH_PRIME32_3  0xC2B2AE3DU  /*!< 0b11000010101100101010111000111101 */
1911 #define XXH_PRIME32_4  0x27D4EB2FU  /*!< 0b00100111110101001110101100101111 */
1912 #define XXH_PRIME32_5  0x165667B1U  /*!< 0b00010110010101100110011110110001 */
1913 
1914 #ifdef XXH_OLD_NAMES
1915 #  define PRIME32_1 XXH_PRIME32_1
1916 #  define PRIME32_2 XXH_PRIME32_2
1917 #  define PRIME32_3 XXH_PRIME32_3
1918 #  define PRIME32_4 XXH_PRIME32_4
1919 #  define PRIME32_5 XXH_PRIME32_5
1920 #endif
1921 
1922 /*!
1923  * @internal
1924  * @brief Normal stripe processing routine.
1925  *
1926  * This shuffles the bits so that any bit from @p input impacts several bits in
1927  * @p acc.
1928  *
1929  * @param acc The accumulator lane.
1930  * @param input The stripe of input to mix.
1931  * @return The mixed accumulator lane.
1932  */
XXH32_round(xxh_u32 acc,xxh_u32 input)1933 static xxh_u32 XXH32_round(xxh_u32 acc, xxh_u32 input)
1934 {
1935     acc += input * XXH_PRIME32_2;
1936     acc  = XXH_rotl32(acc, 13);
1937     acc *= XXH_PRIME32_1;
1938 #if (defined(__SSE4_1__) || defined(__aarch64__)) && !defined(XXH_ENABLE_AUTOVECTORIZE)
1939     /*
1940      * UGLY HACK:
1941      * A compiler fence is the only thing that prevents GCC and Clang from
1942      * autovectorizing the XXH32 loop (pragmas and attributes don't work for some
1943      * reason) without globally disabling SSE4.1.
1944      *
1945      * The reason we want to avoid vectorization is because despite working on
1946      * 4 integers at a time, there are multiple factors slowing XXH32 down on
1947      * SSE4:
1948      * - There's a ridiculous amount of lag from pmulld (10 cycles of latency on
1949      *   newer chips!) making it slightly slower to multiply four integers at
1950      *   once compared to four integers independently. Even when pmulld was
1951      *   fastest, Sandy/Ivy Bridge, it is still not worth it to go into SSE
1952      *   just to multiply unless doing a long operation.
1953      *
1954      * - Four instructions are required to rotate,
1955      *      movqda tmp,  v // not required with VEX encoding
1956      *      pslld  tmp, 13 // tmp <<= 13
1957      *      psrld  v,   19 // x >>= 19
1958      *      por    v,  tmp // x |= tmp
1959      *   compared to one for scalar:
1960      *      roll   v, 13    // reliably fast across the board
1961      *      shldl  v, v, 13 // Sandy Bridge and later prefer this for some reason
1962      *
1963      * - Instruction level parallelism is actually more beneficial here because
1964      *   the SIMD actually serializes this operation: While v1 is rotating, v2
1965      *   can load data, while v3 can multiply. SSE forces them to operate
1966      *   together.
1967      *
1968      * This is also enabled on AArch64, as Clang autovectorizes it incorrectly
1969      * and it is pointless writing a NEON implementation that is basically the
1970      * same speed as scalar for XXH32.
1971      */
1972     XXH_COMPILER_GUARD(acc);
1973 #endif
1974     return acc;
1975 }
1976 
1977 /*!
1978  * @internal
1979  * @brief Mixes all bits to finalize the hash.
1980  *
1981  * The final mix ensures that all input bits have a chance to impact any bit in
1982  * the output digest, resulting in an unbiased distribution.
1983  *
1984  * @param h32 The hash to avalanche.
1985  * @return The avalanched hash.
1986  */
XXH32_avalanche(xxh_u32 h32)1987 static xxh_u32 XXH32_avalanche(xxh_u32 h32)
1988 {
1989     h32 ^= h32 >> 15;
1990     h32 *= XXH_PRIME32_2;
1991     h32 ^= h32 >> 13;
1992     h32 *= XXH_PRIME32_3;
1993     h32 ^= h32 >> 16;
1994     return(h32);
1995 }
1996 
1997 #define XXH_get32bits(p) XXH_readLE32_align(p, align)
1998 
1999 /*!
2000  * @internal
2001  * @brief Processes the last 0-15 bytes of @p ptr.
2002  *
2003  * There may be up to 15 bytes remaining to consume from the input.
2004  * This final stage will digest them to ensure that all input bytes are present
2005  * in the final mix.
2006  *
2007  * @param h32 The hash to finalize.
2008  * @param ptr The pointer to the remaining input.
2009  * @param len The remaining length, modulo 16.
2010  * @param align Whether @p ptr is aligned.
2011  * @return The finalized hash.
2012  */
2013 static xxh_u32
XXH32_finalize(xxh_u32 h32,const xxh_u8 * ptr,size_t len,XXH_alignment align)2014 XXH32_finalize(xxh_u32 h32, const xxh_u8* ptr, size_t len, XXH_alignment align)
2015 {
2016 #define XXH_PROCESS1 do {                           \
2017     h32 += (*ptr++) * XXH_PRIME32_5;                \
2018     h32 = XXH_rotl32(h32, 11) * XXH_PRIME32_1;      \
2019 } while (0)
2020 
2021 #define XXH_PROCESS4 do {                           \
2022     h32 += XXH_get32bits(ptr) * XXH_PRIME32_3;      \
2023     ptr += 4;                                   \
2024     h32  = XXH_rotl32(h32, 17) * XXH_PRIME32_4;     \
2025 } while (0)
2026 
2027     if (ptr==NULL) XXH_ASSERT(len == 0);
2028 
2029     /* Compact rerolled version; generally faster */
2030     if (!XXH32_ENDJMP) {
2031         len &= 15;
2032         while (len >= 4) {
2033             XXH_PROCESS4;
2034             len -= 4;
2035         }
2036         while (len > 0) {
2037             XXH_PROCESS1;
2038             --len;
2039         }
2040         return XXH32_avalanche(h32);
2041     } else {
2042          switch(len&15) /* or switch(bEnd - p) */ {
2043            case 12:      XXH_PROCESS4;
2044                          XXH_FALLTHROUGH;
2045            case 8:       XXH_PROCESS4;
2046                          XXH_FALLTHROUGH;
2047            case 4:       XXH_PROCESS4;
2048                          return XXH32_avalanche(h32);
2049 
2050            case 13:      XXH_PROCESS4;
2051                          XXH_FALLTHROUGH;
2052            case 9:       XXH_PROCESS4;
2053                          XXH_FALLTHROUGH;
2054            case 5:       XXH_PROCESS4;
2055                          XXH_PROCESS1;
2056                          return XXH32_avalanche(h32);
2057 
2058            case 14:      XXH_PROCESS4;
2059                          XXH_FALLTHROUGH;
2060            case 10:      XXH_PROCESS4;
2061                          XXH_FALLTHROUGH;
2062            case 6:       XXH_PROCESS4;
2063                          XXH_PROCESS1;
2064                          XXH_PROCESS1;
2065                          return XXH32_avalanche(h32);
2066 
2067            case 15:      XXH_PROCESS4;
2068                          XXH_FALLTHROUGH;
2069            case 11:      XXH_PROCESS4;
2070                          XXH_FALLTHROUGH;
2071            case 7:       XXH_PROCESS4;
2072                          XXH_FALLTHROUGH;
2073            case 3:       XXH_PROCESS1;
2074                          XXH_FALLTHROUGH;
2075            case 2:       XXH_PROCESS1;
2076                          XXH_FALLTHROUGH;
2077            case 1:       XXH_PROCESS1;
2078                          XXH_FALLTHROUGH;
2079            case 0:       return XXH32_avalanche(h32);
2080         }
2081         XXH_ASSERT(0);
2082         return h32;   /* reaching this point is deemed impossible */
2083     }
2084 }
2085 
2086 #ifdef XXH_OLD_NAMES
2087 #  define PROCESS1 XXH_PROCESS1
2088 #  define PROCESS4 XXH_PROCESS4
2089 #else
2090 #  undef XXH_PROCESS1
2091 #  undef XXH_PROCESS4
2092 #endif
2093 
2094 /*!
2095  * @internal
2096  * @brief The implementation for @ref XXH32().
2097  *
2098  * @param input , len , seed Directly passed from @ref XXH32().
2099  * @param align Whether @p input is aligned.
2100  * @return The calculated hash.
2101  */
2102 XXH_FORCE_INLINE xxh_u32
XXH32_endian_align(const xxh_u8 * input,size_t len,xxh_u32 seed,XXH_alignment align)2103 XXH32_endian_align(const xxh_u8* input, size_t len, xxh_u32 seed, XXH_alignment align)
2104 {
2105     xxh_u32 h32;
2106 
2107     if (input==NULL) XXH_ASSERT(len == 0);
2108 
2109     if (len>=16) {
2110         const xxh_u8* const bEnd = input + len;
2111         const xxh_u8* const limit = bEnd - 15;
2112         xxh_u32 v1 = seed + XXH_PRIME32_1 + XXH_PRIME32_2;
2113         xxh_u32 v2 = seed + XXH_PRIME32_2;
2114         xxh_u32 v3 = seed + 0;
2115         xxh_u32 v4 = seed - XXH_PRIME32_1;
2116 
2117         do {
2118             v1 = XXH32_round(v1, XXH_get32bits(input)); input += 4;
2119             v2 = XXH32_round(v2, XXH_get32bits(input)); input += 4;
2120             v3 = XXH32_round(v3, XXH_get32bits(input)); input += 4;
2121             v4 = XXH32_round(v4, XXH_get32bits(input)); input += 4;
2122         } while (input < limit);
2123 
2124         h32 = XXH_rotl32(v1, 1)  + XXH_rotl32(v2, 7)
2125             + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18);
2126     } else {
2127         h32  = seed + XXH_PRIME32_5;
2128     }
2129 
2130     h32 += (xxh_u32)len;
2131 
2132     return XXH32_finalize(h32, input, len&15, align);
2133 }
2134 
2135 /*! @ingroup xxh32_family */
XXH32(const void * input,size_t len,XXH32_hash_t seed)2136 XXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t len, XXH32_hash_t seed)
2137 {
2138 #if 0
2139     /* Simple version, good for code maintenance, but unfortunately slow for small inputs */
2140     XXH32_state_t state;
2141     XXH32_reset(&state, seed);
2142     XXH32_update(&state, (const xxh_u8*)input, len);
2143     return XXH32_digest(&state);
2144 #else
2145     if (XXH_FORCE_ALIGN_CHECK) {
2146         if ((((size_t)input) & 3) == 0) {   /* Input is 4-bytes aligned, leverage the speed benefit */
2147             return XXH32_endian_align((const xxh_u8*)input, len, seed, XXH_aligned);
2148     }   }
2149 
2150     return XXH32_endian_align((const xxh_u8*)input, len, seed, XXH_unaligned);
2151 #endif
2152 }
2153 
2154 
2155 
2156 /*******   Hash streaming   *******/
2157 /*!
2158  * @ingroup xxh32_family
2159  */
XXH32_createState(void)2160 XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void)
2161 {
2162     return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t));
2163 }
2164 /*! @ingroup xxh32_family */
XXH32_freeState(XXH32_state_t * statePtr)2165 XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr)
2166 {
2167     XXH_free(statePtr);
2168     return XXH_OK;
2169 }
2170 
2171 /*! @ingroup xxh32_family */
XXH32_copyState(XXH32_state_t * dstState,const XXH32_state_t * srcState)2172 XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dstState, const XXH32_state_t* srcState)
2173 {
2174     XXH_memcpy(dstState, srcState, sizeof(*dstState));
2175 }
2176 
2177 /*! @ingroup xxh32_family */
XXH32_reset(XXH32_state_t * statePtr,XXH32_hash_t seed)2178 XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, XXH32_hash_t seed)
2179 {
2180     XXH32_state_t state;   /* using a local state to memcpy() in order to avoid strict-aliasing warnings */
2181     memset(&state, 0, sizeof(state));
2182     state.v[0] = seed + XXH_PRIME32_1 + XXH_PRIME32_2;
2183     state.v[1] = seed + XXH_PRIME32_2;
2184     state.v[2] = seed + 0;
2185     state.v[3] = seed - XXH_PRIME32_1;
2186     /* do not write into reserved, planned to be removed in a future version */
2187     XXH_memcpy(statePtr, &state, sizeof(state) - sizeof(state.reserved));
2188     return XXH_OK;
2189 }
2190 
2191 
2192 /*! @ingroup xxh32_family */
2193 XXH_PUBLIC_API XXH_errorcode
XXH32_update(XXH32_state_t * state,const void * input,size_t len)2194 XXH32_update(XXH32_state_t* state, const void* input, size_t len)
2195 {
2196     if (input==NULL) {
2197         XXH_ASSERT(len == 0);
2198         return XXH_OK;
2199     }
2200 
2201     {   const xxh_u8* p = (const xxh_u8*)input;
2202         const xxh_u8* const bEnd = p + len;
2203 
2204         state->total_len_32 += (XXH32_hash_t)len;
2205         state->large_len |= (XXH32_hash_t)((len>=16) | (state->total_len_32>=16));
2206 
2207         if (state->memsize + len < 16)  {   /* fill in tmp buffer */
2208             XXH_memcpy((xxh_u8*)(state->mem32) + state->memsize, input, len);
2209             state->memsize += (XXH32_hash_t)len;
2210             return XXH_OK;
2211         }
2212 
2213         if (state->memsize) {   /* some data left from previous update */
2214             XXH_memcpy((xxh_u8*)(state->mem32) + state->memsize, input, 16-state->memsize);
2215             {   const xxh_u32* p32 = state->mem32;
2216                 state->v[0] = XXH32_round(state->v[0], XXH_readLE32(p32)); p32++;
2217                 state->v[1] = XXH32_round(state->v[1], XXH_readLE32(p32)); p32++;
2218                 state->v[2] = XXH32_round(state->v[2], XXH_readLE32(p32)); p32++;
2219                 state->v[3] = XXH32_round(state->v[3], XXH_readLE32(p32));
2220             }
2221             p += 16-state->memsize;
2222             state->memsize = 0;
2223         }
2224 
2225         if (p <= bEnd-16) {
2226             const xxh_u8* const limit = bEnd - 16;
2227 
2228             do {
2229                 state->v[0] = XXH32_round(state->v[0], XXH_readLE32(p)); p+=4;
2230                 state->v[1] = XXH32_round(state->v[1], XXH_readLE32(p)); p+=4;
2231                 state->v[2] = XXH32_round(state->v[2], XXH_readLE32(p)); p+=4;
2232                 state->v[3] = XXH32_round(state->v[3], XXH_readLE32(p)); p+=4;
2233             } while (p<=limit);
2234 
2235         }
2236 
2237         if (p < bEnd) {
2238             XXH_memcpy(state->mem32, p, (size_t)(bEnd-p));
2239             state->memsize = (unsigned)(bEnd-p);
2240         }
2241     }
2242 
2243     return XXH_OK;
2244 }
2245 
2246 
2247 /*! @ingroup xxh32_family */
XXH32_digest(const XXH32_state_t * state)2248 XXH_PUBLIC_API XXH32_hash_t XXH32_digest(const XXH32_state_t* state)
2249 {
2250     xxh_u32 h32;
2251 
2252     if (state->large_len) {
2253         h32 = XXH_rotl32(state->v[0], 1)
2254             + XXH_rotl32(state->v[1], 7)
2255             + XXH_rotl32(state->v[2], 12)
2256             + XXH_rotl32(state->v[3], 18);
2257     } else {
2258         h32 = state->v[2] /* == seed */ + XXH_PRIME32_5;
2259     }
2260 
2261     h32 += state->total_len_32;
2262 
2263     return XXH32_finalize(h32, (const xxh_u8*)state->mem32, state->memsize, XXH_aligned);
2264 }
2265 
2266 
2267 /*******   Canonical representation   *******/
2268 
2269 /*!
2270  * @ingroup xxh32_family
2271  * The default return values from XXH functions are unsigned 32 and 64 bit
2272  * integers.
2273  *
2274  * The canonical representation uses big endian convention, the same convention
2275  * as human-readable numbers (large digits first).
2276  *
2277  * This way, hash values can be written into a file or buffer, remaining
2278  * comparable across different systems.
2279  *
2280  * The following functions allow transformation of hash values to and from their
2281  * canonical format.
2282  */
XXH32_canonicalFromHash(XXH32_canonical_t * dst,XXH32_hash_t hash)2283 XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash)
2284 {
2285     XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t));
2286     if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap32(hash);
2287     XXH_memcpy(dst, &hash, sizeof(*dst));
2288 }
2289 /*! @ingroup xxh32_family */
XXH32_hashFromCanonical(const XXH32_canonical_t * src)2290 XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src)
2291 {
2292     return XXH_readBE32(src);
2293 }
2294 
2295 
2296 #ifndef XXH_NO_LONG_LONG
2297 
2298 /* *******************************************************************
2299 *  64-bit hash functions
2300 *********************************************************************/
2301 /*!
2302  * @}
2303  * @ingroup impl
2304  * @{
2305  */
2306 /*******   Memory access   *******/
2307 
2308 typedef XXH64_hash_t xxh_u64;
2309 
2310 #ifdef XXH_OLD_NAMES
2311 #  define U64 xxh_u64
2312 #endif
2313 
2314 #if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==3))
2315 /*
2316  * Manual byteshift. Best for old compilers which don't inline memcpy.
2317  * We actually directly use XXH_readLE64 and XXH_readBE64.
2318  */
2319 #elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2))
2320 
2321 /* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */
XXH_read64(const void * memPtr)2322 static xxh_u64 XXH_read64(const void* memPtr)
2323 {
2324     return *(const xxh_u64*) memPtr;
2325 }
2326 
2327 #elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1))
2328 
2329 /*
2330  * __pack instructions are safer, but compiler specific, hence potentially
2331  * problematic for some compilers.
2332  *
2333  * Currently only defined for GCC and ICC.
2334  */
2335 #ifdef XXH_OLD_NAMES
2336 typedef union { xxh_u32 u32; xxh_u64 u64; } __attribute__((packed)) unalign64;
2337 #endif
XXH_read64(const void * ptr)2338 static xxh_u64 XXH_read64(const void* ptr)
2339 {
2340     typedef union { xxh_u32 u32; xxh_u64 u64; } __attribute__((packed)) xxh_unalign64;
2341     return ((const xxh_unalign64*)ptr)->u64;
2342 }
2343 
2344 #else
2345 
2346 /*
2347  * Portable and safe solution. Generally efficient.
2348  * see: http://fastcompression.blogspot.com/2015/08/accessing-unaligned-memory.html
2349  */
XXH_read64(const void * memPtr)2350 static xxh_u64 XXH_read64(const void* memPtr)
2351 {
2352     xxh_u64 val;
2353     XXH_memcpy(&val, memPtr, sizeof(val));
2354     return val;
2355 }
2356 
2357 #endif   /* XXH_FORCE_DIRECT_MEMORY_ACCESS */
2358 
2359 #if defined(_MSC_VER)     /* Visual Studio */
2360 #  define XXH_swap64 _byteswap_uint64
2361 #elif XXH_GCC_VERSION >= 403
2362 #  define XXH_swap64 __builtin_bswap64
2363 #else
XXH_swap64(xxh_u64 x)2364 static xxh_u64 XXH_swap64(xxh_u64 x)
2365 {
2366     return  ((x << 56) & 0xff00000000000000ULL) |
2367             ((x << 40) & 0x00ff000000000000ULL) |
2368             ((x << 24) & 0x0000ff0000000000ULL) |
2369             ((x << 8)  & 0x000000ff00000000ULL) |
2370             ((x >> 8)  & 0x00000000ff000000ULL) |
2371             ((x >> 24) & 0x0000000000ff0000ULL) |
2372             ((x >> 40) & 0x000000000000ff00ULL) |
2373             ((x >> 56) & 0x00000000000000ffULL);
2374 }
2375 #endif
2376 
2377 
2378 /* XXH_FORCE_MEMORY_ACCESS==3 is an endian-independent byteshift load. */
2379 #if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==3))
2380 
XXH_readLE64(const void * memPtr)2381 XXH_FORCE_INLINE xxh_u64 XXH_readLE64(const void* memPtr)
2382 {
2383     const xxh_u8* bytePtr = (const xxh_u8 *)memPtr;
2384     return bytePtr[0]
2385          | ((xxh_u64)bytePtr[1] << 8)
2386          | ((xxh_u64)bytePtr[2] << 16)
2387          | ((xxh_u64)bytePtr[3] << 24)
2388          | ((xxh_u64)bytePtr[4] << 32)
2389          | ((xxh_u64)bytePtr[5] << 40)
2390          | ((xxh_u64)bytePtr[6] << 48)
2391          | ((xxh_u64)bytePtr[7] << 56);
2392 }
2393 
XXH_readBE64(const void * memPtr)2394 XXH_FORCE_INLINE xxh_u64 XXH_readBE64(const void* memPtr)
2395 {
2396     const xxh_u8* bytePtr = (const xxh_u8 *)memPtr;
2397     return bytePtr[7]
2398          | ((xxh_u64)bytePtr[6] << 8)
2399          | ((xxh_u64)bytePtr[5] << 16)
2400          | ((xxh_u64)bytePtr[4] << 24)
2401          | ((xxh_u64)bytePtr[3] << 32)
2402          | ((xxh_u64)bytePtr[2] << 40)
2403          | ((xxh_u64)bytePtr[1] << 48)
2404          | ((xxh_u64)bytePtr[0] << 56);
2405 }
2406 
2407 #else
XXH_readLE64(const void * ptr)2408 XXH_FORCE_INLINE xxh_u64 XXH_readLE64(const void* ptr)
2409 {
2410     return XXH_CPU_LITTLE_ENDIAN ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr));
2411 }
2412 
XXH_readBE64(const void * ptr)2413 static xxh_u64 XXH_readBE64(const void* ptr)
2414 {
2415     return XXH_CPU_LITTLE_ENDIAN ? XXH_swap64(XXH_read64(ptr)) : XXH_read64(ptr);
2416 }
2417 #endif
2418 
2419 XXH_FORCE_INLINE xxh_u64
XXH_readLE64_align(const void * ptr,XXH_alignment align)2420 XXH_readLE64_align(const void* ptr, XXH_alignment align)
2421 {
2422     if (align==XXH_unaligned)
2423         return XXH_readLE64(ptr);
2424     else
2425         return XXH_CPU_LITTLE_ENDIAN ? *(const xxh_u64*)ptr : XXH_swap64(*(const xxh_u64*)ptr);
2426 }
2427 
2428 
2429 /*******   xxh64   *******/
2430 /*!
2431  * @}
2432  * @defgroup xxh64_impl XXH64 implementation
2433  * @ingroup impl
2434  * @{
2435  */
2436 /* #define rather that static const, to be used as initializers */
2437 #define XXH_PRIME64_1  0x9E3779B185EBCA87ULL  /*!< 0b1001111000110111011110011011000110000101111010111100101010000111 */
2438 #define XXH_PRIME64_2  0xC2B2AE3D27D4EB4FULL  /*!< 0b1100001010110010101011100011110100100111110101001110101101001111 */
2439 #define XXH_PRIME64_3  0x165667B19E3779F9ULL  /*!< 0b0001011001010110011001111011000110011110001101110111100111111001 */
2440 #define XXH_PRIME64_4  0x85EBCA77C2B2AE63ULL  /*!< 0b1000010111101011110010100111011111000010101100101010111001100011 */
2441 #define XXH_PRIME64_5  0x27D4EB2F165667C5ULL  /*!< 0b0010011111010100111010110010111100010110010101100110011111000101 */
2442 
2443 #ifdef XXH_OLD_NAMES
2444 #  define PRIME64_1 XXH_PRIME64_1
2445 #  define PRIME64_2 XXH_PRIME64_2
2446 #  define PRIME64_3 XXH_PRIME64_3
2447 #  define PRIME64_4 XXH_PRIME64_4
2448 #  define PRIME64_5 XXH_PRIME64_5
2449 #endif
2450 
XXH64_round(xxh_u64 acc,xxh_u64 input)2451 static xxh_u64 XXH64_round(xxh_u64 acc, xxh_u64 input)
2452 {
2453     acc += input * XXH_PRIME64_2;
2454     acc  = XXH_rotl64(acc, 31);
2455     acc *= XXH_PRIME64_1;
2456     return acc;
2457 }
2458 
XXH64_mergeRound(xxh_u64 acc,xxh_u64 val)2459 static xxh_u64 XXH64_mergeRound(xxh_u64 acc, xxh_u64 val)
2460 {
2461     val  = XXH64_round(0, val);
2462     acc ^= val;
2463     acc  = acc * XXH_PRIME64_1 + XXH_PRIME64_4;
2464     return acc;
2465 }
2466 
XXH64_avalanche(xxh_u64 h64)2467 static xxh_u64 XXH64_avalanche(xxh_u64 h64)
2468 {
2469     h64 ^= h64 >> 33;
2470     h64 *= XXH_PRIME64_2;
2471     h64 ^= h64 >> 29;
2472     h64 *= XXH_PRIME64_3;
2473     h64 ^= h64 >> 32;
2474     return h64;
2475 }
2476 
2477 
2478 #define XXH_get64bits(p) XXH_readLE64_align(p, align)
2479 
2480 static xxh_u64
XXH64_finalize(xxh_u64 h64,const xxh_u8 * ptr,size_t len,XXH_alignment align)2481 XXH64_finalize(xxh_u64 h64, const xxh_u8* ptr, size_t len, XXH_alignment align)
2482 {
2483     if (ptr==NULL) XXH_ASSERT(len == 0);
2484     len &= 31;
2485     while (len >= 8) {
2486         xxh_u64 const k1 = XXH64_round(0, XXH_get64bits(ptr));
2487         ptr += 8;
2488         h64 ^= k1;
2489         h64  = XXH_rotl64(h64,27) * XXH_PRIME64_1 + XXH_PRIME64_4;
2490         len -= 8;
2491     }
2492     if (len >= 4) {
2493         h64 ^= (xxh_u64)(XXH_get32bits(ptr)) * XXH_PRIME64_1;
2494         ptr += 4;
2495         h64 = XXH_rotl64(h64, 23) * XXH_PRIME64_2 + XXH_PRIME64_3;
2496         len -= 4;
2497     }
2498     while (len > 0) {
2499         h64 ^= (*ptr++) * XXH_PRIME64_5;
2500         h64 = XXH_rotl64(h64, 11) * XXH_PRIME64_1;
2501         --len;
2502     }
2503     return  XXH64_avalanche(h64);
2504 }
2505 
2506 #ifdef XXH_OLD_NAMES
2507 #  define PROCESS1_64 XXH_PROCESS1_64
2508 #  define PROCESS4_64 XXH_PROCESS4_64
2509 #  define PROCESS8_64 XXH_PROCESS8_64
2510 #else
2511 #  undef XXH_PROCESS1_64
2512 #  undef XXH_PROCESS4_64
2513 #  undef XXH_PROCESS8_64
2514 #endif
2515 
2516 XXH_FORCE_INLINE xxh_u64
XXH64_endian_align(const xxh_u8 * input,size_t len,xxh_u64 seed,XXH_alignment align)2517 XXH64_endian_align(const xxh_u8* input, size_t len, xxh_u64 seed, XXH_alignment align)
2518 {
2519     xxh_u64 h64;
2520     if (input==NULL) XXH_ASSERT(len == 0);
2521 
2522     if (len>=32) {
2523         const xxh_u8* const bEnd = input + len;
2524         const xxh_u8* const limit = bEnd - 31;
2525         xxh_u64 v1 = seed + XXH_PRIME64_1 + XXH_PRIME64_2;
2526         xxh_u64 v2 = seed + XXH_PRIME64_2;
2527         xxh_u64 v3 = seed + 0;
2528         xxh_u64 v4 = seed - XXH_PRIME64_1;
2529 
2530         do {
2531             v1 = XXH64_round(v1, XXH_get64bits(input)); input+=8;
2532             v2 = XXH64_round(v2, XXH_get64bits(input)); input+=8;
2533             v3 = XXH64_round(v3, XXH_get64bits(input)); input+=8;
2534             v4 = XXH64_round(v4, XXH_get64bits(input)); input+=8;
2535         } while (input<limit);
2536 
2537         h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18);
2538         h64 = XXH64_mergeRound(h64, v1);
2539         h64 = XXH64_mergeRound(h64, v2);
2540         h64 = XXH64_mergeRound(h64, v3);
2541         h64 = XXH64_mergeRound(h64, v4);
2542 
2543     } else {
2544         h64  = seed + XXH_PRIME64_5;
2545     }
2546 
2547     h64 += (xxh_u64) len;
2548 
2549     return XXH64_finalize(h64, input, len, align);
2550 }
2551 
2552 
2553 /*! @ingroup xxh64_family */
XXH64(const void * input,size_t len,XXH64_hash_t seed)2554 XXH_PUBLIC_API XXH64_hash_t XXH64 (const void* input, size_t len, XXH64_hash_t seed)
2555 {
2556 #if 0
2557     /* Simple version, good for code maintenance, but unfortunately slow for small inputs */
2558     XXH64_state_t state;
2559     XXH64_reset(&state, seed);
2560     XXH64_update(&state, (const xxh_u8*)input, len);
2561     return XXH64_digest(&state);
2562 #else
2563     if (XXH_FORCE_ALIGN_CHECK) {
2564         if ((((size_t)input) & 7)==0) {  /* Input is aligned, let's leverage the speed advantage */
2565             return XXH64_endian_align((const xxh_u8*)input, len, seed, XXH_aligned);
2566     }   }
2567 
2568     return XXH64_endian_align((const xxh_u8*)input, len, seed, XXH_unaligned);
2569 
2570 #endif
2571 }
2572 
2573 /*******   Hash Streaming   *******/
2574 
2575 /*! @ingroup xxh64_family*/
XXH64_createState(void)2576 XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void)
2577 {
2578     return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t));
2579 }
2580 /*! @ingroup xxh64_family */
XXH64_freeState(XXH64_state_t * statePtr)2581 XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr)
2582 {
2583     XXH_free(statePtr);
2584     return XXH_OK;
2585 }
2586 
2587 /*! @ingroup xxh64_family */
XXH64_copyState(XXH64_state_t * dstState,const XXH64_state_t * srcState)2588 XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* dstState, const XXH64_state_t* srcState)
2589 {
2590     XXH_memcpy(dstState, srcState, sizeof(*dstState));
2591 }
2592 
2593 /*! @ingroup xxh64_family */
XXH64_reset(XXH64_state_t * statePtr,XXH64_hash_t seed)2594 XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH64_state_t* statePtr, XXH64_hash_t seed)
2595 {
2596     XXH64_state_t state;   /* use a local state to memcpy() in order to avoid strict-aliasing warnings */
2597     memset(&state, 0, sizeof(state));
2598     state.v[0] = seed + XXH_PRIME64_1 + XXH_PRIME64_2;
2599     state.v[1] = seed + XXH_PRIME64_2;
2600     state.v[2] = seed + 0;
2601     state.v[3] = seed - XXH_PRIME64_1;
2602      /* do not write into reserved64, might be removed in a future version */
2603     XXH_memcpy(statePtr, &state, sizeof(state) - sizeof(state.reserved64));
2604     return XXH_OK;
2605 }
2606 
2607 /*! @ingroup xxh64_family */
2608 XXH_PUBLIC_API XXH_errorcode
XXH64_update(XXH64_state_t * state,const void * input,size_t len)2609 XXH64_update (XXH64_state_t* state, const void* input, size_t len)
2610 {
2611     if (input==NULL) {
2612         XXH_ASSERT(len == 0);
2613         return XXH_OK;
2614     }
2615 
2616     {   const xxh_u8* p = (const xxh_u8*)input;
2617         const xxh_u8* const bEnd = p + len;
2618 
2619         state->total_len += len;
2620 
2621         if (state->memsize + len < 32) {  /* fill in tmp buffer */
2622             XXH_memcpy(((xxh_u8*)state->mem64) + state->memsize, input, len);
2623             state->memsize += (xxh_u32)len;
2624             return XXH_OK;
2625         }
2626 
2627         if (state->memsize) {   /* tmp buffer is full */
2628             XXH_memcpy(((xxh_u8*)state->mem64) + state->memsize, input, 32-state->memsize);
2629             state->v[0] = XXH64_round(state->v[0], XXH_readLE64(state->mem64+0));
2630             state->v[1] = XXH64_round(state->v[1], XXH_readLE64(state->mem64+1));
2631             state->v[2] = XXH64_round(state->v[2], XXH_readLE64(state->mem64+2));
2632             state->v[3] = XXH64_round(state->v[3], XXH_readLE64(state->mem64+3));
2633             p += 32 - state->memsize;
2634             state->memsize = 0;
2635         }
2636 
2637         if (p+32 <= bEnd) {
2638             const xxh_u8* const limit = bEnd - 32;
2639 
2640             do {
2641                 state->v[0] = XXH64_round(state->v[0], XXH_readLE64(p)); p+=8;
2642                 state->v[1] = XXH64_round(state->v[1], XXH_readLE64(p)); p+=8;
2643                 state->v[2] = XXH64_round(state->v[2], XXH_readLE64(p)); p+=8;
2644                 state->v[3] = XXH64_round(state->v[3], XXH_readLE64(p)); p+=8;
2645             } while (p<=limit);
2646 
2647         }
2648 
2649         if (p < bEnd) {
2650             XXH_memcpy(state->mem64, p, (size_t)(bEnd-p));
2651             state->memsize = (unsigned)(bEnd-p);
2652         }
2653     }
2654 
2655     return XXH_OK;
2656 }
2657 
2658 
2659 /*! @ingroup xxh64_family */
XXH64_digest(const XXH64_state_t * state)2660 XXH_PUBLIC_API XXH64_hash_t XXH64_digest(const XXH64_state_t* state)
2661 {
2662     xxh_u64 h64;
2663 
2664     if (state->total_len >= 32) {
2665         h64 = XXH_rotl64(state->v[0], 1) + XXH_rotl64(state->v[1], 7) + XXH_rotl64(state->v[2], 12) + XXH_rotl64(state->v[3], 18);
2666         h64 = XXH64_mergeRound(h64, state->v[0]);
2667         h64 = XXH64_mergeRound(h64, state->v[1]);
2668         h64 = XXH64_mergeRound(h64, state->v[2]);
2669         h64 = XXH64_mergeRound(h64, state->v[3]);
2670     } else {
2671         h64  = state->v[2] /*seed*/ + XXH_PRIME64_5;
2672     }
2673 
2674     h64 += (xxh_u64) state->total_len;
2675 
2676     return XXH64_finalize(h64, (const xxh_u8*)state->mem64, (size_t)state->total_len, XXH_aligned);
2677 }
2678 
2679 
2680 /******* Canonical representation   *******/
2681 
2682 /*! @ingroup xxh64_family */
XXH64_canonicalFromHash(XXH64_canonical_t * dst,XXH64_hash_t hash)2683 XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash)
2684 {
2685     XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t));
2686     if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap64(hash);
2687     XXH_memcpy(dst, &hash, sizeof(*dst));
2688 }
2689 
2690 /*! @ingroup xxh64_family */
XXH64_hashFromCanonical(const XXH64_canonical_t * src)2691 XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src)
2692 {
2693     return XXH_readBE64(src);
2694 }
2695 
2696 #ifndef XXH_NO_XXH3
2697 
2698 /* *********************************************************************
2699 *  XXH3
2700 *  New generation hash designed for speed on small keys and vectorization
2701 ************************************************************************ */
2702 /*!
2703  * @}
2704  * @defgroup xxh3_impl XXH3 implementation
2705  * @ingroup impl
2706  * @{
2707  */
2708 
2709 /* ===   Compiler specifics   === */
2710 
2711 #if ((defined(sun) || defined(__sun)) && __cplusplus) /* Solaris includes __STDC_VERSION__ with C++. Tested with GCC 5.5 */
2712 #  define XXH_RESTRICT /* disable */
2713 #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* >= C99 */
2714 #  define XXH_RESTRICT   restrict
2715 #else
2716 /* Note: it might be useful to define __restrict or __restrict__ for some C++ compilers */
2717 #  define XXH_RESTRICT   /* disable */
2718 #endif
2719 
2720 #if (defined(__GNUC__) && (__GNUC__ >= 3))  \
2721   || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) \
2722   || defined(__clang__)
2723 #    define XXH_likely(x) __builtin_expect(x, 1)
2724 #    define XXH_unlikely(x) __builtin_expect(x, 0)
2725 #else
2726 #    define XXH_likely(x) (x)
2727 #    define XXH_unlikely(x) (x)
2728 #endif
2729 
2730 #if defined(__GNUC__) || defined(__clang__)
2731 #  if defined(__ARM_NEON__) || defined(__ARM_NEON) \
2732    || defined(__aarch64__)  || defined(_M_ARM) \
2733    || defined(_M_ARM64)     || defined(_M_ARM64EC)
2734 #    define inline __inline__  /* circumvent a clang bug */
2735 #    include <arm_neon.h>
2736 #    undef inline
2737 #  elif defined(__AVX2__)
2738 #    include <immintrin.h>
2739 #  elif defined(__SSE2__)
2740 #    include <emmintrin.h>
2741 #  endif
2742 #endif
2743 
2744 #if defined(_MSC_VER)
2745 #  include <intrin.h>
2746 #endif
2747 
2748 /*
2749  * One goal of XXH3 is to make it fast on both 32-bit and 64-bit, while
2750  * remaining a true 64-bit/128-bit hash function.
2751  *
2752  * This is done by prioritizing a subset of 64-bit operations that can be
2753  * emulated without too many steps on the average 32-bit machine.
2754  *
2755  * For example, these two lines seem similar, and run equally fast on 64-bit:
2756  *
2757  *   xxh_u64 x;
2758  *   x ^= (x >> 47); // good
2759  *   x ^= (x >> 13); // bad
2760  *
2761  * However, to a 32-bit machine, there is a major difference.
2762  *
2763  * x ^= (x >> 47) looks like this:
2764  *
2765  *   x.lo ^= (x.hi >> (47 - 32));
2766  *
2767  * while x ^= (x >> 13) looks like this:
2768  *
2769  *   // note: funnel shifts are not usually cheap.
2770  *   x.lo ^= (x.lo >> 13) | (x.hi << (32 - 13));
2771  *   x.hi ^= (x.hi >> 13);
2772  *
2773  * The first one is significantly faster than the second, simply because the
2774  * shift is larger than 32. This means:
2775  *  - All the bits we need are in the upper 32 bits, so we can ignore the lower
2776  *    32 bits in the shift.
2777  *  - The shift result will always fit in the lower 32 bits, and therefore,
2778  *    we can ignore the upper 32 bits in the xor.
2779  *
2780  * Thanks to this optimization, XXH3 only requires these features to be efficient:
2781  *
2782  *  - Usable unaligned access
2783  *  - A 32-bit or 64-bit ALU
2784  *      - If 32-bit, a decent ADC instruction
2785  *  - A 32 or 64-bit multiply with a 64-bit result
2786  *  - For the 128-bit variant, a decent byteswap helps short inputs.
2787  *
2788  * The first two are already required by XXH32, and almost all 32-bit and 64-bit
2789  * platforms which can run XXH32 can run XXH3 efficiently.
2790  *
2791  * Thumb-1, the classic 16-bit only subset of ARM's instruction set, is one
2792  * notable exception.
2793  *
2794  * First of all, Thumb-1 lacks support for the UMULL instruction which
2795  * performs the important long multiply. This means numerous __aeabi_lmul
2796  * calls.
2797  *
2798  * Second of all, the 8 functional registers are just not enough.
2799  * Setup for __aeabi_lmul, byteshift loads, pointers, and all arithmetic need
2800  * Lo registers, and this shuffling results in thousands more MOVs than A32.
2801  *
2802  * A32 and T32 don't have this limitation. They can access all 14 registers,
2803  * do a 32->64 multiply with UMULL, and the flexible operand allowing free
2804  * shifts is helpful, too.
2805  *
2806  * Therefore, we do a quick sanity check.
2807  *
2808  * If compiling Thumb-1 for a target which supports ARM instructions, we will
2809  * emit a warning, as it is not a "sane" platform to compile for.
2810  *
2811  * Usually, if this happens, it is because of an accident and you probably need
2812  * to specify -march, as you likely meant to compile for a newer architecture.
2813  *
2814  * Credit: large sections of the vectorial and asm source code paths
2815  *         have been contributed by @easyaspi314
2816  */
2817 #if defined(__thumb__) && !defined(__thumb2__) && defined(__ARM_ARCH_ISA_ARM)
2818 #   warning "XXH3 is highly inefficient without ARM or Thumb-2."
2819 #endif
2820 
2821 /* ==========================================
2822  * Vectorization detection
2823  * ========================================== */
2824 
2825 #ifdef XXH_DOXYGEN
2826 /*!
2827  * @ingroup tuning
2828  * @brief Overrides the vectorization implementation chosen for XXH3.
2829  *
2830  * Can be defined to 0 to disable SIMD or any of the values mentioned in
2831  * @ref XXH_VECTOR_TYPE.
2832  *
2833  * If this is not defined, it uses predefined macros to determine the best
2834  * implementation.
2835  */
2836 #  define XXH_VECTOR XXH_SCALAR
2837 /*!
2838  * @ingroup tuning
2839  * @brief Possible values for @ref XXH_VECTOR.
2840  *
2841  * Note that these are actually implemented as macros.
2842  *
2843  * If this is not defined, it is detected automatically.
2844  * @ref XXH_X86DISPATCH overrides this.
2845  */
2846 enum XXH_VECTOR_TYPE /* fake enum */ {
2847     XXH_SCALAR = 0,  /*!< Portable scalar version */
2848     XXH_SSE2   = 1,  /*!<
2849                       * SSE2 for Pentium 4, Opteron, all x86_64.
2850                       *
2851                       * @note SSE2 is also guaranteed on Windows 10, macOS, and
2852                       * Android x86.
2853                       */
2854     XXH_AVX2   = 2,  /*!< AVX2 for Haswell and Bulldozer */
2855     XXH_AVX512 = 3,  /*!< AVX512 for Skylake and Icelake */
2856     XXH_NEON   = 4,  /*!< NEON for most ARMv7-A and all AArch64 */
2857     XXH_VSX    = 5,  /*!< VSX and ZVector for POWER8/z13 (64-bit) */
2858 };
2859 /*!
2860  * @ingroup tuning
2861  * @brief Selects the minimum alignment for XXH3's accumulators.
2862  *
2863  * When using SIMD, this should match the alignment reqired for said vector
2864  * type, so, for example, 32 for AVX2.
2865  *
2866  * Default: Auto detected.
2867  */
2868 #  define XXH_ACC_ALIGN 8
2869 #endif
2870 
2871 /* Actual definition */
2872 #ifndef XXH_DOXYGEN
2873 #  define XXH_SCALAR 0
2874 #  define XXH_SSE2   1
2875 #  define XXH_AVX2   2
2876 #  define XXH_AVX512 3
2877 #  define XXH_NEON   4
2878 #  define XXH_VSX    5
2879 #endif
2880 
2881 #ifndef XXH_VECTOR    /* can be defined on command line */
2882 #  if ( \
2883         defined(__ARM_NEON__) || defined(__ARM_NEON) /* gcc */ \
2884      || defined(_M_ARM) || defined(_M_ARM64) || defined(_M_ARM64EC) /* msvc */ \
2885    ) && ( \
2886         defined(_WIN32) || defined(__LITTLE_ENDIAN__) /* little endian only */ \
2887     || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) \
2888    )
2889 #    define XXH_VECTOR XXH_NEON
2890 #  elif defined(__AVX512F__)
2891 #    define XXH_VECTOR XXH_AVX512
2892 #  elif defined(__AVX2__)
2893 #    define XXH_VECTOR XXH_AVX2
2894 #  elif defined(__SSE2__) || defined(_M_AMD64) || defined(_M_X64) || (defined(_M_IX86_FP) && (_M_IX86_FP == 2))
2895 #    define XXH_VECTOR XXH_SSE2
2896 #  elif (defined(__PPC64__) && defined(__POWER8_VECTOR__)) \
2897      || (defined(__s390x__) && defined(__VEC__)) \
2898      && defined(__GNUC__) /* TODO: IBM XL */
2899 #    define XXH_VECTOR XXH_VSX
2900 #  else
2901 #    define XXH_VECTOR XXH_SCALAR
2902 #  endif
2903 #endif
2904 
2905 /*
2906  * Controls the alignment of the accumulator,
2907  * for compatibility with aligned vector loads, which are usually faster.
2908  */
2909 #ifndef XXH_ACC_ALIGN
2910 #  if defined(XXH_X86DISPATCH)
2911 #     define XXH_ACC_ALIGN 64  /* for compatibility with avx512 */
2912 #  elif XXH_VECTOR == XXH_SCALAR  /* scalar */
2913 #     define XXH_ACC_ALIGN 8
2914 #  elif XXH_VECTOR == XXH_SSE2  /* sse2 */
2915 #     define XXH_ACC_ALIGN 16
2916 #  elif XXH_VECTOR == XXH_AVX2  /* avx2 */
2917 #     define XXH_ACC_ALIGN 32
2918 #  elif XXH_VECTOR == XXH_NEON  /* neon */
2919 #     define XXH_ACC_ALIGN 16
2920 #  elif XXH_VECTOR == XXH_VSX   /* vsx */
2921 #     define XXH_ACC_ALIGN 16
2922 #  elif XXH_VECTOR == XXH_AVX512  /* avx512 */
2923 #     define XXH_ACC_ALIGN 64
2924 #  endif
2925 #endif
2926 
2927 #if defined(XXH_X86DISPATCH) || XXH_VECTOR == XXH_SSE2 \
2928     || XXH_VECTOR == XXH_AVX2 || XXH_VECTOR == XXH_AVX512
2929 #  define XXH_SEC_ALIGN XXH_ACC_ALIGN
2930 #else
2931 #  define XXH_SEC_ALIGN 8
2932 #endif
2933 
2934 /*
2935  * UGLY HACK:
2936  * GCC usually generates the best code with -O3 for xxHash.
2937  *
2938  * However, when targeting AVX2, it is overzealous in its unrolling resulting
2939  * in code roughly 3/4 the speed of Clang.
2940  *
2941  * There are other issues, such as GCC splitting _mm256_loadu_si256 into
2942  * _mm_loadu_si128 + _mm256_inserti128_si256. This is an optimization which
2943  * only applies to Sandy and Ivy Bridge... which don't even support AVX2.
2944  *
2945  * That is why when compiling the AVX2 version, it is recommended to use either
2946  *   -O2 -mavx2 -march=haswell
2947  * or
2948  *   -O2 -mavx2 -mno-avx256-split-unaligned-load
2949  * for decent performance, or to use Clang instead.
2950  *
2951  * Fortunately, we can control the first one with a pragma that forces GCC into
2952  * -O2, but the other one we can't control without "failed to inline always
2953  * inline function due to target mismatch" warnings.
2954  */
2955 #if XXH_VECTOR == XXH_AVX2 /* AVX2 */ \
2956   && defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \
2957   && defined(__OPTIMIZE__) && !defined(__OPTIMIZE_SIZE__) /* respect -O0 and -Os */
2958 #  pragma GCC push_options
2959 #  pragma GCC optimize("-O2")
2960 #endif
2961 
2962 
2963 #if XXH_VECTOR == XXH_NEON
2964 /*
2965  * NEON's setup for vmlal_u32 is a little more complicated than it is on
2966  * SSE2, AVX2, and VSX.
2967  *
2968  * While PMULUDQ and VMULEUW both perform a mask, VMLAL.U32 performs an upcast.
2969  *
2970  * To do the same operation, the 128-bit 'Q' register needs to be split into
2971  * two 64-bit 'D' registers, performing this operation::
2972  *
2973  *   [                a                 |                 b                ]
2974  *            |              '---------. .--------'                |
2975  *            |                         x                          |
2976  *            |              .---------' '--------.                |
2977  *   [ a & 0xFFFFFFFF | b & 0xFFFFFFFF ],[    a >> 32     |     b >> 32    ]
2978  *
2979  * Due to significant changes in aarch64, the fastest method for aarch64 is
2980  * completely different than the fastest method for ARMv7-A.
2981  *
2982  * ARMv7-A treats D registers as unions overlaying Q registers, so modifying
2983  * D11 will modify the high half of Q5. This is similar to how modifying AH
2984  * will only affect bits 8-15 of AX on x86.
2985  *
2986  * VZIP takes two registers, and puts even lanes in one register and odd lanes
2987  * in the other.
2988  *
2989  * On ARMv7-A, this strangely modifies both parameters in place instead of
2990  * taking the usual 3-operand form.
2991  *
2992  * Therefore, if we want to do this, we can simply use a D-form VZIP.32 on the
2993  * lower and upper halves of the Q register to end up with the high and low
2994  * halves where we want - all in one instruction.
2995  *
2996  *   vzip.32   d10, d11       @ d10 = { d10[0], d11[0] }; d11 = { d10[1], d11[1] }
2997  *
2998  * Unfortunately we need inline assembly for this: Instructions modifying two
2999  * registers at once is not possible in GCC or Clang's IR, and they have to
3000  * create a copy.
3001  *
3002  * aarch64 requires a different approach.
3003  *
3004  * In order to make it easier to write a decent compiler for aarch64, many
3005  * quirks were removed, such as conditional execution.
3006  *
3007  * NEON was also affected by this.
3008  *
3009  * aarch64 cannot access the high bits of a Q-form register, and writes to a
3010  * D-form register zero the high bits, similar to how writes to W-form scalar
3011  * registers (or DWORD registers on x86_64) work.
3012  *
3013  * The formerly free vget_high intrinsics now require a vext (with a few
3014  * exceptions)
3015  *
3016  * Additionally, VZIP was replaced by ZIP1 and ZIP2, which are the equivalent
3017  * of PUNPCKL* and PUNPCKH* in SSE, respectively, in order to only modify one
3018  * operand.
3019  *
3020  * The equivalent of the VZIP.32 on the lower and upper halves would be this
3021  * mess:
3022  *
3023  *   ext     v2.4s, v0.4s, v0.4s, #2 // v2 = { v0[2], v0[3], v0[0], v0[1] }
3024  *   zip1    v1.2s, v0.2s, v2.2s     // v1 = { v0[0], v2[0] }
3025  *   zip2    v0.2s, v0.2s, v1.2s     // v0 = { v0[1], v2[1] }
3026  *
3027  * Instead, we use a literal downcast, vmovn_u64 (XTN), and vshrn_n_u64 (SHRN):
3028  *
3029  *   shrn    v1.2s, v0.2d, #32  // v1 = (uint32x2_t)(v0 >> 32);
3030  *   xtn     v0.2s, v0.2d       // v0 = (uint32x2_t)(v0 & 0xFFFFFFFF);
3031  *
3032  * This is available on ARMv7-A, but is less efficient than a single VZIP.32.
3033  */
3034 
3035 /*!
3036  * Function-like macro:
3037  * void XXH_SPLIT_IN_PLACE(uint64x2_t &in, uint32x2_t &outLo, uint32x2_t &outHi)
3038  * {
3039  *     outLo = (uint32x2_t)(in & 0xFFFFFFFF);
3040  *     outHi = (uint32x2_t)(in >> 32);
3041  *     in = UNDEFINED;
3042  * }
3043  */
3044 # if !defined(XXH_NO_VZIP_HACK) /* define to disable */ \
3045    && (defined(__GNUC__) || defined(__clang__)) \
3046    && (defined(__arm__) || defined(__thumb__) || defined(_M_ARM))
3047 #  define XXH_SPLIT_IN_PLACE(in, outLo, outHi)                                              \
3048     do {                                                                                    \
3049       /* Undocumented GCC/Clang operand modifier: %e0 = lower D half, %f0 = upper D half */ \
3050       /* https://github.com/gcc-mirror/gcc/blob/38cf91e5/gcc/config/arm/arm.c#L22486 */     \
3051       /* https://github.com/llvm-mirror/llvm/blob/2c4ca683/lib/Target/ARM/ARMAsmPrinter.cpp#L399 */ \
3052       __asm__("vzip.32  %e0, %f0" : "+w" (in));                                             \
3053       (outLo) = vget_low_u32 (vreinterpretq_u32_u64(in));                                   \
3054       (outHi) = vget_high_u32(vreinterpretq_u32_u64(in));                                   \
3055    } while (0)
3056 # else
3057 #  define XXH_SPLIT_IN_PLACE(in, outLo, outHi)                                            \
3058     do {                                                                                  \
3059       (outLo) = vmovn_u64    (in);                                                        \
3060       (outHi) = vshrn_n_u64  ((in), 32);                                                  \
3061     } while (0)
3062 # endif
3063 
3064 /*!
3065  * @ingroup tuning
3066  * @brief Controls the NEON to scalar ratio for XXH3
3067  *
3068  * On aarch64, it is beneficial to use both scalar *and* NEON code to utilize
3069  * both pipelines. This results in a ~15-30% speedup compared to pure NEON,
3070  * depending on the compiler.
3071  *
3072  * The default uses 6 lanes for NEON and 2 lanes for scalar.
3073  *
3074  * This is disabled for code size optimizations, and it does not benefit ARMv7.
3075  *
3076  * Must be either 2, 4, 6, or 8.
3077  */
3078 # ifndef XXH3_NEON_LANES
3079 #  if (defined(__aarch64__) || defined(__arm64__) || defined(_M_ARM64) || defined(_M_ARM64EC)) \
3080    && !defined(__OPTIMIZE_SIZE__)
3081 #   define XXH3_NEON_LANES 6
3082 #  else
3083 #   define XXH3_NEON_LANES XXH_ACC_NB
3084 #  endif
3085 # endif
3086 #endif  /* XXH_VECTOR == XXH_NEON */
3087 
3088 /*
3089  * VSX and Z Vector helpers.
3090  *
3091  * This is very messy, and any pull requests to clean this up are welcome.
3092  *
3093  * There are a lot of problems with supporting VSX and s390x, due to
3094  * inconsistent intrinsics, spotty coverage, and multiple endiannesses.
3095  */
3096 #if XXH_VECTOR == XXH_VSX
3097 #  if defined(__s390x__)
3098 #    include <s390intrin.h>
3099 #  else
3100 /* gcc's altivec.h can have the unwanted consequence to unconditionally
3101  * #define bool, vector, and pixel keywords,
3102  * with bad consequences for programs already using these keywords for other purposes.
3103  * The paragraph defining these macros is skipped when __APPLE_ALTIVEC__ is defined.
3104  * __APPLE_ALTIVEC__ is _generally_ defined automatically by the compiler,
3105  * but it seems that, in some cases, it isn't.
3106  * Force the build macro to be defined, so that keywords are not altered.
3107  */
3108 #    if defined(__GNUC__) && !defined(__APPLE_ALTIVEC__)
3109 #      define __APPLE_ALTIVEC__
3110 #    endif
3111 #    include <altivec.h>
3112 #  endif
3113 
3114 typedef __vector unsigned long long xxh_u64x2;
3115 typedef __vector unsigned char xxh_u8x16;
3116 typedef __vector unsigned xxh_u32x4;
3117 
3118 # ifndef XXH_VSX_BE
3119 #  if defined(__BIG_ENDIAN__) \
3120   || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
3121 #    define XXH_VSX_BE 1
3122 #  elif defined(__VEC_ELEMENT_REG_ORDER__) && __VEC_ELEMENT_REG_ORDER__ == __ORDER_BIG_ENDIAN__
3123 #    warning "-maltivec=be is not recommended. Please use native endianness."
3124 #    define XXH_VSX_BE 1
3125 #  else
3126 #    define XXH_VSX_BE 0
3127 #  endif
3128 # endif /* !defined(XXH_VSX_BE) */
3129 
3130 # if XXH_VSX_BE
3131 #  if defined(__POWER9_VECTOR__) || (defined(__clang__) && defined(__s390x__))
3132 #    define XXH_vec_revb vec_revb
3133 #  else
3134 /*!
3135  * A polyfill for POWER9's vec_revb().
3136  */
XXH_vec_revb(xxh_u64x2 val)3137 XXH_FORCE_INLINE xxh_u64x2 XXH_vec_revb(xxh_u64x2 val)
3138 {
3139     xxh_u8x16 const vByteSwap = { 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
3140                                   0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08 };
3141     return vec_perm(val, val, vByteSwap);
3142 }
3143 #  endif
3144 # endif /* XXH_VSX_BE */
3145 
3146 /*!
3147  * Performs an unaligned vector load and byte swaps it on big endian.
3148  */
XXH_vec_loadu(const void * ptr)3149 XXH_FORCE_INLINE xxh_u64x2 XXH_vec_loadu(const void *ptr)
3150 {
3151     xxh_u64x2 ret;
3152     XXH_memcpy(&ret, ptr, sizeof(xxh_u64x2));
3153 # if XXH_VSX_BE
3154     ret = XXH_vec_revb(ret);
3155 # endif
3156     return ret;
3157 }
3158 
3159 /*
3160  * vec_mulo and vec_mule are very problematic intrinsics on PowerPC
3161  *
3162  * These intrinsics weren't added until GCC 8, despite existing for a while,
3163  * and they are endian dependent. Also, their meaning swap depending on version.
3164  * */
3165 # if defined(__s390x__)
3166  /* s390x is always big endian, no issue on this platform */
3167 #  define XXH_vec_mulo vec_mulo
3168 #  define XXH_vec_mule vec_mule
3169 # elif defined(__clang__) && XXH_HAS_BUILTIN(__builtin_altivec_vmuleuw)
3170 /* Clang has a better way to control this, we can just use the builtin which doesn't swap. */
3171 #  define XXH_vec_mulo __builtin_altivec_vmulouw
3172 #  define XXH_vec_mule __builtin_altivec_vmuleuw
3173 # else
3174 /* gcc needs inline assembly */
3175 /* Adapted from https://github.com/google/highwayhash/blob/master/highwayhash/hh_vsx.h. */
XXH_vec_mulo(xxh_u32x4 a,xxh_u32x4 b)3176 XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mulo(xxh_u32x4 a, xxh_u32x4 b)
3177 {
3178     xxh_u64x2 result;
3179     __asm__("vmulouw %0, %1, %2" : "=v" (result) : "v" (a), "v" (b));
3180     return result;
3181 }
XXH_vec_mule(xxh_u32x4 a,xxh_u32x4 b)3182 XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mule(xxh_u32x4 a, xxh_u32x4 b)
3183 {
3184     xxh_u64x2 result;
3185     __asm__("vmuleuw %0, %1, %2" : "=v" (result) : "v" (a), "v" (b));
3186     return result;
3187 }
3188 # endif /* XXH_vec_mulo, XXH_vec_mule */
3189 #endif /* XXH_VECTOR == XXH_VSX */
3190 
3191 
3192 /* prefetch
3193  * can be disabled, by declaring XXH_NO_PREFETCH build macro */
3194 #if defined(XXH_NO_PREFETCH)
3195 #  define XXH_PREFETCH(ptr)  (void)(ptr)  /* disabled */
3196 #else
3197 #  if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86))  /* _mm_prefetch() not defined outside of x86/x64 */
3198 #    include <mmintrin.h>   /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */
3199 #    define XXH_PREFETCH(ptr)  _mm_prefetch((const char*)(ptr), _MM_HINT_T0)
3200 #  elif defined(__GNUC__) && ( (__GNUC__ >= 4) || ( (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) ) )
3201 #    define XXH_PREFETCH(ptr)  __builtin_prefetch((ptr), 0 /* rw==read */, 3 /* locality */)
3202 #  else
3203 #    define XXH_PREFETCH(ptr) (void)(ptr)  /* disabled */
3204 #  endif
3205 #endif  /* XXH_NO_PREFETCH */
3206 
3207 
3208 /* ==========================================
3209  * XXH3 default settings
3210  * ========================================== */
3211 
3212 #define XXH_SECRET_DEFAULT_SIZE 192   /* minimum XXH3_SECRET_SIZE_MIN */
3213 
3214 #if (XXH_SECRET_DEFAULT_SIZE < XXH3_SECRET_SIZE_MIN)
3215 #  error "default keyset is not large enough"
3216 #endif
3217 
3218 /*! Pseudorandom secret taken directly from FARSH. */
3219 XXH_ALIGN(64) static const xxh_u8 XXH3_kSecret[XXH_SECRET_DEFAULT_SIZE] = {
3220     0xb8, 0xfe, 0x6c, 0x39, 0x23, 0xa4, 0x4b, 0xbe, 0x7c, 0x01, 0x81, 0x2c, 0xf7, 0x21, 0xad, 0x1c,
3221     0xde, 0xd4, 0x6d, 0xe9, 0x83, 0x90, 0x97, 0xdb, 0x72, 0x40, 0xa4, 0xa4, 0xb7, 0xb3, 0x67, 0x1f,
3222     0xcb, 0x79, 0xe6, 0x4e, 0xcc, 0xc0, 0xe5, 0x78, 0x82, 0x5a, 0xd0, 0x7d, 0xcc, 0xff, 0x72, 0x21,
3223     0xb8, 0x08, 0x46, 0x74, 0xf7, 0x43, 0x24, 0x8e, 0xe0, 0x35, 0x90, 0xe6, 0x81, 0x3a, 0x26, 0x4c,
3224     0x3c, 0x28, 0x52, 0xbb, 0x91, 0xc3, 0x00, 0xcb, 0x88, 0xd0, 0x65, 0x8b, 0x1b, 0x53, 0x2e, 0xa3,
3225     0x71, 0x64, 0x48, 0x97, 0xa2, 0x0d, 0xf9, 0x4e, 0x38, 0x19, 0xef, 0x46, 0xa9, 0xde, 0xac, 0xd8,
3226     0xa8, 0xfa, 0x76, 0x3f, 0xe3, 0x9c, 0x34, 0x3f, 0xf9, 0xdc, 0xbb, 0xc7, 0xc7, 0x0b, 0x4f, 0x1d,
3227     0x8a, 0x51, 0xe0, 0x4b, 0xcd, 0xb4, 0x59, 0x31, 0xc8, 0x9f, 0x7e, 0xc9, 0xd9, 0x78, 0x73, 0x64,
3228     0xea, 0xc5, 0xac, 0x83, 0x34, 0xd3, 0xeb, 0xc3, 0xc5, 0x81, 0xa0, 0xff, 0xfa, 0x13, 0x63, 0xeb,
3229     0x17, 0x0d, 0xdd, 0x51, 0xb7, 0xf0, 0xda, 0x49, 0xd3, 0x16, 0x55, 0x26, 0x29, 0xd4, 0x68, 0x9e,
3230     0x2b, 0x16, 0xbe, 0x58, 0x7d, 0x47, 0xa1, 0xfc, 0x8f, 0xf8, 0xb8, 0xd1, 0x7a, 0xd0, 0x31, 0xce,
3231     0x45, 0xcb, 0x3a, 0x8f, 0x95, 0x16, 0x04, 0x28, 0xaf, 0xd7, 0xfb, 0xca, 0xbb, 0x4b, 0x40, 0x7e,
3232 };
3233 
3234 
3235 #ifdef XXH_OLD_NAMES
3236 #  define kSecret XXH3_kSecret
3237 #endif
3238 
3239 #ifdef XXH_DOXYGEN
3240 /*!
3241  * @brief Calculates a 32-bit to 64-bit long multiply.
3242  *
3243  * Implemented as a macro.
3244  *
3245  * Wraps `__emulu` on MSVC x86 because it tends to call `__allmul` when it doesn't
3246  * need to (but it shouldn't need to anyways, it is about 7 instructions to do
3247  * a 64x64 multiply...). Since we know that this will _always_ emit `MULL`, we
3248  * use that instead of the normal method.
3249  *
3250  * If you are compiling for platforms like Thumb-1 and don't have a better option,
3251  * you may also want to write your own long multiply routine here.
3252  *
3253  * @param x, y Numbers to be multiplied
3254  * @return 64-bit product of the low 32 bits of @p x and @p y.
3255  */
3256 XXH_FORCE_INLINE xxh_u64
XXH_mult32to64(xxh_u64 x,xxh_u64 y)3257 XXH_mult32to64(xxh_u64 x, xxh_u64 y)
3258 {
3259    return (x & 0xFFFFFFFF) * (y & 0xFFFFFFFF);
3260 }
3261 #elif defined(_MSC_VER) && defined(_M_IX86)
3262 #    define XXH_mult32to64(x, y) __emulu((unsigned)(x), (unsigned)(y))
3263 #else
3264 /*
3265  * Downcast + upcast is usually better than masking on older compilers like
3266  * GCC 4.2 (especially 32-bit ones), all without affecting newer compilers.
3267  *
3268  * The other method, (x & 0xFFFFFFFF) * (y & 0xFFFFFFFF), will AND both operands
3269  * and perform a full 64x64 multiply -- entirely redundant on 32-bit.
3270  */
3271 #    define XXH_mult32to64(x, y) ((xxh_u64)(xxh_u32)(x) * (xxh_u64)(xxh_u32)(y))
3272 #endif
3273 
3274 /*!
3275  * @brief Calculates a 64->128-bit long multiply.
3276  *
3277  * Uses `__uint128_t` and `_umul128` if available, otherwise uses a scalar
3278  * version.
3279  *
3280  * @param lhs , rhs The 64-bit integers to be multiplied
3281  * @return The 128-bit result represented in an @ref XXH128_hash_t.
3282  */
3283 static XXH128_hash_t
XXH_mult64to128(xxh_u64 lhs,xxh_u64 rhs)3284 XXH_mult64to128(xxh_u64 lhs, xxh_u64 rhs)
3285 {
3286     /*
3287      * GCC/Clang __uint128_t method.
3288      *
3289      * On most 64-bit targets, GCC and Clang define a __uint128_t type.
3290      * This is usually the best way as it usually uses a native long 64-bit
3291      * multiply, such as MULQ on x86_64 or MUL + UMULH on aarch64.
3292      *
3293      * Usually.
3294      *
3295      * Despite being a 32-bit platform, Clang (and emscripten) define this type
3296      * despite not having the arithmetic for it. This results in a laggy
3297      * compiler builtin call which calculates a full 128-bit multiply.
3298      * In that case it is best to use the portable one.
3299      * https://github.com/Cyan4973/xxHash/issues/211#issuecomment-515575677
3300      */
3301 #if (defined(__GNUC__) || defined(__clang__)) && !defined(__wasm__) \
3302     && defined(__SIZEOF_INT128__) \
3303     || (defined(_INTEGRAL_MAX_BITS) && _INTEGRAL_MAX_BITS >= 128)
3304 
3305     __uint128_t const product = (__uint128_t)lhs * (__uint128_t)rhs;
3306     XXH128_hash_t r128;
3307     r128.low64  = (xxh_u64)(product);
3308     r128.high64 = (xxh_u64)(product >> 64);
3309     return r128;
3310 
3311     /*
3312      * MSVC for x64's _umul128 method.
3313      *
3314      * xxh_u64 _umul128(xxh_u64 Multiplier, xxh_u64 Multiplicand, xxh_u64 *HighProduct);
3315      *
3316      * This compiles to single operand MUL on x64.
3317      */
3318 #elif (defined(_M_X64) || defined(_M_IA64)) && !defined(_M_ARM64EC)
3319 
3320 #ifndef _MSC_VER
3321 #   pragma intrinsic(_umul128)
3322 #endif
3323     xxh_u64 product_high;
3324     xxh_u64 const product_low = _umul128(lhs, rhs, &product_high);
3325     XXH128_hash_t r128;
3326     r128.low64  = product_low;
3327     r128.high64 = product_high;
3328     return r128;
3329 
3330     /*
3331      * MSVC for ARM64's __umulh method.
3332      *
3333      * This compiles to the same MUL + UMULH as GCC/Clang's __uint128_t method.
3334      */
3335 #elif defined(_M_ARM64) || defined(_M_ARM64EC)
3336 
3337 #ifndef _MSC_VER
3338 #   pragma intrinsic(__umulh)
3339 #endif
3340     XXH128_hash_t r128;
3341     r128.low64  = lhs * rhs;
3342     r128.high64 = __umulh(lhs, rhs);
3343     return r128;
3344 
3345 #else
3346     /*
3347      * Portable scalar method. Optimized for 32-bit and 64-bit ALUs.
3348      *
3349      * This is a fast and simple grade school multiply, which is shown below
3350      * with base 10 arithmetic instead of base 0x100000000.
3351      *
3352      *           9 3 // D2 lhs = 93
3353      *         x 7 5 // D2 rhs = 75
3354      *     ----------
3355      *           1 5 // D2 lo_lo = (93 % 10) * (75 % 10) = 15
3356      *         4 5 | // D2 hi_lo = (93 / 10) * (75 % 10) = 45
3357      *         2 1 | // D2 lo_hi = (93 % 10) * (75 / 10) = 21
3358      *     + 6 3 | | // D2 hi_hi = (93 / 10) * (75 / 10) = 63
3359      *     ---------
3360      *         2 7 | // D2 cross = (15 / 10) + (45 % 10) + 21 = 27
3361      *     + 6 7 | | // D2 upper = (27 / 10) + (45 / 10) + 63 = 67
3362      *     ---------
3363      *       6 9 7 5 // D4 res = (27 * 10) + (15 % 10) + (67 * 100) = 6975
3364      *
3365      * The reasons for adding the products like this are:
3366      *  1. It avoids manual carry tracking. Just like how
3367      *     (9 * 9) + 9 + 9 = 99, the same applies with this for UINT64_MAX.
3368      *     This avoids a lot of complexity.
3369      *
3370      *  2. It hints for, and on Clang, compiles to, the powerful UMAAL
3371      *     instruction available in ARM's Digital Signal Processing extension
3372      *     in 32-bit ARMv6 and later, which is shown below:
3373      *
3374      *         void UMAAL(xxh_u32 *RdLo, xxh_u32 *RdHi, xxh_u32 Rn, xxh_u32 Rm)
3375      *         {
3376      *             xxh_u64 product = (xxh_u64)*RdLo * (xxh_u64)*RdHi + Rn + Rm;
3377      *             *RdLo = (xxh_u32)(product & 0xFFFFFFFF);
3378      *             *RdHi = (xxh_u32)(product >> 32);
3379      *         }
3380      *
3381      *     This instruction was designed for efficient long multiplication, and
3382      *     allows this to be calculated in only 4 instructions at speeds
3383      *     comparable to some 64-bit ALUs.
3384      *
3385      *  3. It isn't terrible on other platforms. Usually this will be a couple
3386      *     of 32-bit ADD/ADCs.
3387      */
3388 
3389     /* First calculate all of the cross products. */
3390     xxh_u64 const lo_lo = XXH_mult32to64(lhs & 0xFFFFFFFF, rhs & 0xFFFFFFFF);
3391     xxh_u64 const hi_lo = XXH_mult32to64(lhs >> 32,        rhs & 0xFFFFFFFF);
3392     xxh_u64 const lo_hi = XXH_mult32to64(lhs & 0xFFFFFFFF, rhs >> 32);
3393     xxh_u64 const hi_hi = XXH_mult32to64(lhs >> 32,        rhs >> 32);
3394 
3395     /* Now add the products together. These will never overflow. */
3396     xxh_u64 const cross = (lo_lo >> 32) + (hi_lo & 0xFFFFFFFF) + lo_hi;
3397     xxh_u64 const upper = (hi_lo >> 32) + (cross >> 32)        + hi_hi;
3398     xxh_u64 const lower = (cross << 32) | (lo_lo & 0xFFFFFFFF);
3399 
3400     XXH128_hash_t r128;
3401     r128.low64  = lower;
3402     r128.high64 = upper;
3403     return r128;
3404 #endif
3405 }
3406 
3407 /*!
3408  * @brief Calculates a 64-bit to 128-bit multiply, then XOR folds it.
3409  *
3410  * The reason for the separate function is to prevent passing too many structs
3411  * around by value. This will hopefully inline the multiply, but we don't force it.
3412  *
3413  * @param lhs , rhs The 64-bit integers to multiply
3414  * @return The low 64 bits of the product XOR'd by the high 64 bits.
3415  * @see XXH_mult64to128()
3416  */
3417 static xxh_u64
XXH3_mul128_fold64(xxh_u64 lhs,xxh_u64 rhs)3418 XXH3_mul128_fold64(xxh_u64 lhs, xxh_u64 rhs)
3419 {
3420     XXH128_hash_t product = XXH_mult64to128(lhs, rhs);
3421     return product.low64 ^ product.high64;
3422 }
3423 
3424 /*! Seems to produce slightly better code on GCC for some reason. */
XXH_xorshift64(xxh_u64 v64,int shift)3425 XXH_FORCE_INLINE xxh_u64 XXH_xorshift64(xxh_u64 v64, int shift)
3426 {
3427     XXH_ASSERT(0 <= shift && shift < 64);
3428     return v64 ^ (v64 >> shift);
3429 }
3430 
3431 /*
3432  * This is a fast avalanche stage,
3433  * suitable when input bits are already partially mixed
3434  */
XXH3_avalanche(xxh_u64 h64)3435 static XXH64_hash_t XXH3_avalanche(xxh_u64 h64)
3436 {
3437     h64 = XXH_xorshift64(h64, 37);
3438     h64 *= 0x165667919E3779F9ULL;
3439     h64 = XXH_xorshift64(h64, 32);
3440     return h64;
3441 }
3442 
3443 /*
3444  * This is a stronger avalanche,
3445  * inspired by Pelle Evensen's rrmxmx
3446  * preferable when input has not been previously mixed
3447  */
XXH3_rrmxmx(xxh_u64 h64,xxh_u64 len)3448 static XXH64_hash_t XXH3_rrmxmx(xxh_u64 h64, xxh_u64 len)
3449 {
3450     /* this mix is inspired by Pelle Evensen's rrmxmx */
3451     h64 ^= XXH_rotl64(h64, 49) ^ XXH_rotl64(h64, 24);
3452     h64 *= 0x9FB21C651E98DF25ULL;
3453     h64 ^= (h64 >> 35) + len ;
3454     h64 *= 0x9FB21C651E98DF25ULL;
3455     return XXH_xorshift64(h64, 28);
3456 }
3457 
3458 
3459 /* ==========================================
3460  * Short keys
3461  * ==========================================
3462  * One of the shortcomings of XXH32 and XXH64 was that their performance was
3463  * sub-optimal on short lengths. It used an iterative algorithm which strongly
3464  * favored lengths that were a multiple of 4 or 8.
3465  *
3466  * Instead of iterating over individual inputs, we use a set of single shot
3467  * functions which piece together a range of lengths and operate in constant time.
3468  *
3469  * Additionally, the number of multiplies has been significantly reduced. This
3470  * reduces latency, especially when emulating 64-bit multiplies on 32-bit.
3471  *
3472  * Depending on the platform, this may or may not be faster than XXH32, but it
3473  * is almost guaranteed to be faster than XXH64.
3474  */
3475 
3476 /*
3477  * At very short lengths, there isn't enough input to fully hide secrets, or use
3478  * the entire secret.
3479  *
3480  * There is also only a limited amount of mixing we can do before significantly
3481  * impacting performance.
3482  *
3483  * Therefore, we use different sections of the secret and always mix two secret
3484  * samples with an XOR. This should have no effect on performance on the
3485  * seedless or withSeed variants because everything _should_ be constant folded
3486  * by modern compilers.
3487  *
3488  * The XOR mixing hides individual parts of the secret and increases entropy.
3489  *
3490  * This adds an extra layer of strength for custom secrets.
3491  */
3492 XXH_FORCE_INLINE XXH64_hash_t
XXH3_len_1to3_64b(const xxh_u8 * input,size_t len,const xxh_u8 * secret,XXH64_hash_t seed)3493 XXH3_len_1to3_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
3494 {
3495     XXH_ASSERT(input != NULL);
3496     XXH_ASSERT(1 <= len && len <= 3);
3497     XXH_ASSERT(secret != NULL);
3498     /*
3499      * len = 1: combined = { input[0], 0x01, input[0], input[0] }
3500      * len = 2: combined = { input[1], 0x02, input[0], input[1] }
3501      * len = 3: combined = { input[2], 0x03, input[0], input[1] }
3502      */
3503     {   xxh_u8  const c1 = input[0];
3504         xxh_u8  const c2 = input[len >> 1];
3505         xxh_u8  const c3 = input[len - 1];
3506         xxh_u32 const combined = ((xxh_u32)c1 << 16) | ((xxh_u32)c2  << 24)
3507                                | ((xxh_u32)c3 <<  0) | ((xxh_u32)len << 8);
3508         xxh_u64 const bitflip = (XXH_readLE32(secret) ^ XXH_readLE32(secret+4)) + seed;
3509         xxh_u64 const keyed = (xxh_u64)combined ^ bitflip;
3510         return XXH64_avalanche(keyed);
3511     }
3512 }
3513 
3514 XXH_FORCE_INLINE XXH64_hash_t
XXH3_len_4to8_64b(const xxh_u8 * input,size_t len,const xxh_u8 * secret,XXH64_hash_t seed)3515 XXH3_len_4to8_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
3516 {
3517     XXH_ASSERT(input != NULL);
3518     XXH_ASSERT(secret != NULL);
3519     XXH_ASSERT(4 <= len && len <= 8);
3520     seed ^= (xxh_u64)XXH_swap32((xxh_u32)seed) << 32;
3521     {   xxh_u32 const input1 = XXH_readLE32(input);
3522         xxh_u32 const input2 = XXH_readLE32(input + len - 4);
3523         xxh_u64 const bitflip = (XXH_readLE64(secret+8) ^ XXH_readLE64(secret+16)) - seed;
3524         xxh_u64 const input64 = input2 + (((xxh_u64)input1) << 32);
3525         xxh_u64 const keyed = input64 ^ bitflip;
3526         return XXH3_rrmxmx(keyed, len);
3527     }
3528 }
3529 
3530 XXH_FORCE_INLINE XXH64_hash_t
XXH3_len_9to16_64b(const xxh_u8 * input,size_t len,const xxh_u8 * secret,XXH64_hash_t seed)3531 XXH3_len_9to16_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
3532 {
3533     XXH_ASSERT(input != NULL);
3534     XXH_ASSERT(secret != NULL);
3535     XXH_ASSERT(9 <= len && len <= 16);
3536     {   xxh_u64 const bitflip1 = (XXH_readLE64(secret+24) ^ XXH_readLE64(secret+32)) + seed;
3537         xxh_u64 const bitflip2 = (XXH_readLE64(secret+40) ^ XXH_readLE64(secret+48)) - seed;
3538         xxh_u64 const input_lo = XXH_readLE64(input)           ^ bitflip1;
3539         xxh_u64 const input_hi = XXH_readLE64(input + len - 8) ^ bitflip2;
3540         xxh_u64 const acc = len
3541                           + XXH_swap64(input_lo) + input_hi
3542                           + XXH3_mul128_fold64(input_lo, input_hi);
3543         return XXH3_avalanche(acc);
3544     }
3545 }
3546 
3547 XXH_FORCE_INLINE XXH64_hash_t
XXH3_len_0to16_64b(const xxh_u8 * input,size_t len,const xxh_u8 * secret,XXH64_hash_t seed)3548 XXH3_len_0to16_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
3549 {
3550     XXH_ASSERT(len <= 16);
3551     {   if (XXH_likely(len >  8)) return XXH3_len_9to16_64b(input, len, secret, seed);
3552         if (XXH_likely(len >= 4)) return XXH3_len_4to8_64b(input, len, secret, seed);
3553         if (len) return XXH3_len_1to3_64b(input, len, secret, seed);
3554         return XXH64_avalanche(seed ^ (XXH_readLE64(secret+56) ^ XXH_readLE64(secret+64)));
3555     }
3556 }
3557 
3558 /*
3559  * DISCLAIMER: There are known *seed-dependent* multicollisions here due to
3560  * multiplication by zero, affecting hashes of lengths 17 to 240.
3561  *
3562  * However, they are very unlikely.
3563  *
3564  * Keep this in mind when using the unseeded XXH3_64bits() variant: As with all
3565  * unseeded non-cryptographic hashes, it does not attempt to defend itself
3566  * against specially crafted inputs, only random inputs.
3567  *
3568  * Compared to classic UMAC where a 1 in 2^31 chance of 4 consecutive bytes
3569  * cancelling out the secret is taken an arbitrary number of times (addressed
3570  * in XXH3_accumulate_512), this collision is very unlikely with random inputs
3571  * and/or proper seeding:
3572  *
3573  * This only has a 1 in 2^63 chance of 8 consecutive bytes cancelling out, in a
3574  * function that is only called up to 16 times per hash with up to 240 bytes of
3575  * input.
3576  *
3577  * This is not too bad for a non-cryptographic hash function, especially with
3578  * only 64 bit outputs.
3579  *
3580  * The 128-bit variant (which trades some speed for strength) is NOT affected
3581  * by this, although it is always a good idea to use a proper seed if you care
3582  * about strength.
3583  */
XXH3_mix16B(const xxh_u8 * XXH_RESTRICT input,const xxh_u8 * XXH_RESTRICT secret,xxh_u64 seed64)3584 XXH_FORCE_INLINE xxh_u64 XXH3_mix16B(const xxh_u8* XXH_RESTRICT input,
3585                                      const xxh_u8* XXH_RESTRICT secret, xxh_u64 seed64)
3586 {
3587 #if defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \
3588   && defined(__i386__) && defined(__SSE2__)  /* x86 + SSE2 */ \
3589   && !defined(XXH_ENABLE_AUTOVECTORIZE)      /* Define to disable like XXH32 hack */
3590     /*
3591      * UGLY HACK:
3592      * GCC for x86 tends to autovectorize the 128-bit multiply, resulting in
3593      * slower code.
3594      *
3595      * By forcing seed64 into a register, we disrupt the cost model and
3596      * cause it to scalarize. See `XXH32_round()`
3597      *
3598      * FIXME: Clang's output is still _much_ faster -- On an AMD Ryzen 3600,
3599      * XXH3_64bits @ len=240 runs at 4.6 GB/s with Clang 9, but 3.3 GB/s on
3600      * GCC 9.2, despite both emitting scalar code.
3601      *
3602      * GCC generates much better scalar code than Clang for the rest of XXH3,
3603      * which is why finding a more optimal codepath is an interest.
3604      */
3605     XXH_COMPILER_GUARD(seed64);
3606 #endif
3607     {   xxh_u64 const input_lo = XXH_readLE64(input);
3608         xxh_u64 const input_hi = XXH_readLE64(input+8);
3609         return XXH3_mul128_fold64(
3610             input_lo ^ (XXH_readLE64(secret)   + seed64),
3611             input_hi ^ (XXH_readLE64(secret+8) - seed64)
3612         );
3613     }
3614 }
3615 
3616 /* For mid range keys, XXH3 uses a Mum-hash variant. */
3617 XXH_FORCE_INLINE XXH64_hash_t
XXH3_len_17to128_64b(const xxh_u8 * XXH_RESTRICT input,size_t len,const xxh_u8 * XXH_RESTRICT secret,size_t secretSize,XXH64_hash_t seed)3618 XXH3_len_17to128_64b(const xxh_u8* XXH_RESTRICT input, size_t len,
3619                      const xxh_u8* XXH_RESTRICT secret, size_t secretSize,
3620                      XXH64_hash_t seed)
3621 {
3622     XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize;
3623     XXH_ASSERT(16 < len && len <= 128);
3624 
3625     {   xxh_u64 acc = len * XXH_PRIME64_1;
3626         if (len > 32) {
3627             if (len > 64) {
3628                 if (len > 96) {
3629                     acc += XXH3_mix16B(input+48, secret+96, seed);
3630                     acc += XXH3_mix16B(input+len-64, secret+112, seed);
3631                 }
3632                 acc += XXH3_mix16B(input+32, secret+64, seed);
3633                 acc += XXH3_mix16B(input+len-48, secret+80, seed);
3634             }
3635             acc += XXH3_mix16B(input+16, secret+32, seed);
3636             acc += XXH3_mix16B(input+len-32, secret+48, seed);
3637         }
3638         acc += XXH3_mix16B(input+0, secret+0, seed);
3639         acc += XXH3_mix16B(input+len-16, secret+16, seed);
3640 
3641         return XXH3_avalanche(acc);
3642     }
3643 }
3644 
3645 #define XXH3_MIDSIZE_MAX 240
3646 
3647 XXH_NO_INLINE XXH64_hash_t
XXH3_len_129to240_64b(const xxh_u8 * XXH_RESTRICT input,size_t len,const xxh_u8 * XXH_RESTRICT secret,size_t secretSize,XXH64_hash_t seed)3648 XXH3_len_129to240_64b(const xxh_u8* XXH_RESTRICT input, size_t len,
3649                       const xxh_u8* XXH_RESTRICT secret, size_t secretSize,
3650                       XXH64_hash_t seed)
3651 {
3652     XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize;
3653     XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX);
3654 
3655     #define XXH3_MIDSIZE_STARTOFFSET 3
3656     #define XXH3_MIDSIZE_LASTOFFSET  17
3657 
3658     {   xxh_u64 acc = len * XXH_PRIME64_1;
3659         int const nbRounds = (int)len / 16;
3660         int i;
3661         for (i=0; i<8; i++) {
3662             acc += XXH3_mix16B(input+(16*i), secret+(16*i), seed);
3663         }
3664         acc = XXH3_avalanche(acc);
3665         XXH_ASSERT(nbRounds >= 8);
3666 #if defined(__clang__)                                /* Clang */ \
3667     && (defined(__ARM_NEON) || defined(__ARM_NEON__)) /* NEON */ \
3668     && !defined(XXH_ENABLE_AUTOVECTORIZE)             /* Define to disable */
3669         /*
3670          * UGLY HACK:
3671          * Clang for ARMv7-A tries to vectorize this loop, similar to GCC x86.
3672          * In everywhere else, it uses scalar code.
3673          *
3674          * For 64->128-bit multiplies, even if the NEON was 100% optimal, it
3675          * would still be slower than UMAAL (see XXH_mult64to128).
3676          *
3677          * Unfortunately, Clang doesn't handle the long multiplies properly and
3678          * converts them to the nonexistent "vmulq_u64" intrinsic, which is then
3679          * scalarized into an ugly mess of VMOV.32 instructions.
3680          *
3681          * This mess is difficult to avoid without turning autovectorization
3682          * off completely, but they are usually relatively minor and/or not
3683          * worth it to fix.
3684          *
3685          * This loop is the easiest to fix, as unlike XXH32, this pragma
3686          * _actually works_ because it is a loop vectorization instead of an
3687          * SLP vectorization.
3688          */
3689         #pragma clang loop vectorize(disable)
3690 #endif
3691         for (i=8 ; i < nbRounds; i++) {
3692             acc += XXH3_mix16B(input+(16*i), secret+(16*(i-8)) + XXH3_MIDSIZE_STARTOFFSET, seed);
3693         }
3694         /* last bytes */
3695         acc += XXH3_mix16B(input + len - 16, secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET, seed);
3696         return XXH3_avalanche(acc);
3697     }
3698 }
3699 
3700 
3701 /* =======     Long Keys     ======= */
3702 
3703 #define XXH_STRIPE_LEN 64
3704 #define XXH_SECRET_CONSUME_RATE 8   /* nb of secret bytes consumed at each accumulation */
3705 #define XXH_ACC_NB (XXH_STRIPE_LEN / sizeof(xxh_u64))
3706 
3707 #ifdef XXH_OLD_NAMES
3708 #  define STRIPE_LEN XXH_STRIPE_LEN
3709 #  define ACC_NB XXH_ACC_NB
3710 #endif
3711 
XXH_writeLE64(void * dst,xxh_u64 v64)3712 XXH_FORCE_INLINE void XXH_writeLE64(void* dst, xxh_u64 v64)
3713 {
3714     if (!XXH_CPU_LITTLE_ENDIAN) v64 = XXH_swap64(v64);
3715     XXH_memcpy(dst, &v64, sizeof(v64));
3716 }
3717 
3718 /* Several intrinsic functions below are supposed to accept __int64 as argument,
3719  * as documented in https://software.intel.com/sites/landingpage/IntrinsicsGuide/ .
3720  * However, several environments do not define __int64 type,
3721  * requiring a workaround.
3722  */
3723 #if !defined (__VMS) \
3724   && (defined (__cplusplus) \
3725   || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
3726     typedef int64_t xxh_i64;
3727 #else
3728     /* the following type must have a width of 64-bit */
3729     typedef long long xxh_i64;
3730 #endif
3731 
3732 
3733 /*
3734  * XXH3_accumulate_512 is the tightest loop for long inputs, and it is the most optimized.
3735  *
3736  * It is a hardened version of UMAC, based off of FARSH's implementation.
3737  *
3738  * This was chosen because it adapts quite well to 32-bit, 64-bit, and SIMD
3739  * implementations, and it is ridiculously fast.
3740  *
3741  * We harden it by mixing the original input to the accumulators as well as the product.
3742  *
3743  * This means that in the (relatively likely) case of a multiply by zero, the
3744  * original input is preserved.
3745  *
3746  * On 128-bit inputs, we swap 64-bit pairs when we add the input to improve
3747  * cross-pollination, as otherwise the upper and lower halves would be
3748  * essentially independent.
3749  *
3750  * This doesn't matter on 64-bit hashes since they all get merged together in
3751  * the end, so we skip the extra step.
3752  *
3753  * Both XXH3_64bits and XXH3_128bits use this subroutine.
3754  */
3755 
3756 /*!
3757  * @internal
3758  * @brief Scalar round for @ref XXH3_accumulate_512_scalar.
3759  */
3760 XXH_FORCE_INLINE void
XXH3_scalarRound(void * XXH_RESTRICT acc,void const * XXH_RESTRICT input,void const * XXH_RESTRICT secret,size_t i)3761 XXH3_scalarRound(void* XXH_RESTRICT acc,
3762                  void const* XXH_RESTRICT input,
3763                  void const* XXH_RESTRICT secret,
3764                  size_t i)
3765 {
3766     xxh_u64* xacc = (xxh_u64*) acc;
3767     xxh_u8 const* xinput = (xxh_u8 const*) input;
3768     xxh_u8 const* xsecret = (xxh_u8 const *)secret;
3769     XXH_ASSERT(i < XXH_ACC_NB);
3770     XXH_ASSERT(((size_t)acc & (XXH_ACC_ALIGN-1)) == 0);
3771     {
3772         xxh_u64 const data_val = XXH_readLE64(xinput + 8*i);
3773         xxh_u64 const data_key = data_val ^ XXH_readLE64(xsecret + i*8);
3774         xacc[i ^ 1] += data_val; /* swap adjacent lanes */
3775         xacc[i] += XXH_mult32to64(data_key & 0xFFFFFFFF, data_key >> 32);
3776     }
3777 }
3778 
3779 /*!
3780  * @internal
3781  * @brief Scalar scramble step for @ref XXH3_scrambleAcc_scalar
3782  */
3783 
3784 XXH_FORCE_INLINE void
XXH3_scalarScrambleRound(void * XXH_RESTRICT acc,void const * XXH_RESTRICT secret,size_t i)3785 XXH3_scalarScrambleRound(void* XXH_RESTRICT acc,
3786                          void const* XXH_RESTRICT secret,
3787                          size_t i)
3788 {
3789     xxh_u64* const xacc = (xxh_u64*) acc;   /* presumed aligned */
3790     const xxh_u8* const xsecret = (const xxh_u8*) secret;   /* no alignment restriction */
3791     XXH_ASSERT((((size_t)acc) & (XXH_ACC_ALIGN-1)) == 0);
3792     XXH_ASSERT(i < XXH_ACC_NB);
3793     {
3794         xxh_u64 const key64 = XXH_readLE64(xsecret + 8*i);
3795         xxh_u64 acc64 = xacc[i];
3796         acc64 = XXH_xorshift64(acc64, 47);
3797         acc64 ^= key64;
3798         acc64 *= XXH_PRIME32_1;
3799         xacc[i] = acc64;
3800     }
3801 }
3802 
3803 #if (XXH_VECTOR == XXH_AVX512) \
3804      || (defined(XXH_DISPATCH_AVX512) && XXH_DISPATCH_AVX512 != 0)
3805 
3806 #ifndef XXH_TARGET_AVX512
3807 # define XXH_TARGET_AVX512  /* disable attribute target */
3808 #endif
3809 
3810 XXH_FORCE_INLINE XXH_TARGET_AVX512 void
XXH3_accumulate_512_avx512(void * XXH_RESTRICT acc,const void * XXH_RESTRICT input,const void * XXH_RESTRICT secret)3811 XXH3_accumulate_512_avx512(void* XXH_RESTRICT acc,
3812                      const void* XXH_RESTRICT input,
3813                      const void* XXH_RESTRICT secret)
3814 {
3815     __m512i* const xacc = (__m512i *) acc;
3816     XXH_ASSERT((((size_t)acc) & 63) == 0);
3817     XXH_STATIC_ASSERT(XXH_STRIPE_LEN == sizeof(__m512i));
3818 
3819     {
3820         /* data_vec    = input[0]; */
3821         __m512i const data_vec    = _mm512_loadu_si512   (input);
3822         /* key_vec     = secret[0]; */
3823         __m512i const key_vec     = _mm512_loadu_si512   (secret);
3824         /* data_key    = data_vec ^ key_vec; */
3825         __m512i const data_key    = _mm512_xor_si512     (data_vec, key_vec);
3826         /* data_key_lo = data_key >> 32; */
3827         __m512i const data_key_lo = _mm512_shuffle_epi32 (data_key, (_MM_PERM_ENUM)_MM_SHUFFLE(0, 3, 0, 1));
3828         /* product     = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */
3829         __m512i const product     = _mm512_mul_epu32     (data_key, data_key_lo);
3830         /* xacc[0] += swap(data_vec); */
3831         __m512i const data_swap = _mm512_shuffle_epi32(data_vec, (_MM_PERM_ENUM)_MM_SHUFFLE(1, 0, 3, 2));
3832         __m512i const sum       = _mm512_add_epi64(*xacc, data_swap);
3833         /* xacc[0] += product; */
3834         *xacc = _mm512_add_epi64(product, sum);
3835     }
3836 }
3837 
3838 /*
3839  * XXH3_scrambleAcc: Scrambles the accumulators to improve mixing.
3840  *
3841  * Multiplication isn't perfect, as explained by Google in HighwayHash:
3842  *
3843  *  // Multiplication mixes/scrambles bytes 0-7 of the 64-bit result to
3844  *  // varying degrees. In descending order of goodness, bytes
3845  *  // 3 4 2 5 1 6 0 7 have quality 228 224 164 160 100 96 36 32.
3846  *  // As expected, the upper and lower bytes are much worse.
3847  *
3848  * Source: https://github.com/google/highwayhash/blob/0aaf66b/highwayhash/hh_avx2.h#L291
3849  *
3850  * Since our algorithm uses a pseudorandom secret to add some variance into the
3851  * mix, we don't need to (or want to) mix as often or as much as HighwayHash does.
3852  *
3853  * This isn't as tight as XXH3_accumulate, but still written in SIMD to avoid
3854  * extraction.
3855  *
3856  * Both XXH3_64bits and XXH3_128bits use this subroutine.
3857  */
3858 
3859 XXH_FORCE_INLINE XXH_TARGET_AVX512 void
XXH3_scrambleAcc_avx512(void * XXH_RESTRICT acc,const void * XXH_RESTRICT secret)3860 XXH3_scrambleAcc_avx512(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
3861 {
3862     XXH_ASSERT((((size_t)acc) & 63) == 0);
3863     XXH_STATIC_ASSERT(XXH_STRIPE_LEN == sizeof(__m512i));
3864     {   __m512i* const xacc = (__m512i*) acc;
3865         const __m512i prime32 = _mm512_set1_epi32((int)XXH_PRIME32_1);
3866 
3867         /* xacc[0] ^= (xacc[0] >> 47) */
3868         __m512i const acc_vec     = *xacc;
3869         __m512i const shifted     = _mm512_srli_epi64    (acc_vec, 47);
3870         __m512i const data_vec    = _mm512_xor_si512     (acc_vec, shifted);
3871         /* xacc[0] ^= secret; */
3872         __m512i const key_vec     = _mm512_loadu_si512   (secret);
3873         __m512i const data_key    = _mm512_xor_si512     (data_vec, key_vec);
3874 
3875         /* xacc[0] *= XXH_PRIME32_1; */
3876         __m512i const data_key_hi = _mm512_shuffle_epi32 (data_key, (_MM_PERM_ENUM)_MM_SHUFFLE(0, 3, 0, 1));
3877         __m512i const prod_lo     = _mm512_mul_epu32     (data_key, prime32);
3878         __m512i const prod_hi     = _mm512_mul_epu32     (data_key_hi, prime32);
3879         *xacc = _mm512_add_epi64(prod_lo, _mm512_slli_epi64(prod_hi, 32));
3880     }
3881 }
3882 
3883 XXH_FORCE_INLINE XXH_TARGET_AVX512 void
XXH3_initCustomSecret_avx512(void * XXH_RESTRICT customSecret,xxh_u64 seed64)3884 XXH3_initCustomSecret_avx512(void* XXH_RESTRICT customSecret, xxh_u64 seed64)
3885 {
3886     XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 63) == 0);
3887     XXH_STATIC_ASSERT(XXH_SEC_ALIGN == 64);
3888     XXH_ASSERT(((size_t)customSecret & 63) == 0);
3889     (void)(&XXH_writeLE64);
3890     {   int const nbRounds = XXH_SECRET_DEFAULT_SIZE / sizeof(__m512i);
3891         __m512i const seed = _mm512_mask_set1_epi64(_mm512_set1_epi64((xxh_i64)seed64), 0xAA, (xxh_i64)(0U - seed64));
3892 
3893         const __m512i* const src  = (const __m512i*) ((const void*) XXH3_kSecret);
3894               __m512i* const dest = (      __m512i*) customSecret;
3895         int i;
3896         XXH_ASSERT(((size_t)src & 63) == 0); /* control alignment */
3897         XXH_ASSERT(((size_t)dest & 63) == 0);
3898         for (i=0; i < nbRounds; ++i) {
3899             /* GCC has a bug, _mm512_stream_load_si512 accepts 'void*', not 'void const*',
3900              * this will warn "discards 'const' qualifier". */
3901             union {
3902                 const __m512i* cp;
3903                 void* p;
3904             } remote_const_void;
3905             remote_const_void.cp = src + i;
3906             dest[i] = _mm512_add_epi64(_mm512_stream_load_si512(remote_const_void.p), seed);
3907     }   }
3908 }
3909 
3910 #endif
3911 
3912 #if (XXH_VECTOR == XXH_AVX2) \
3913     || (defined(XXH_DISPATCH_AVX2) && XXH_DISPATCH_AVX2 != 0)
3914 
3915 #ifndef XXH_TARGET_AVX2
3916 # define XXH_TARGET_AVX2  /* disable attribute target */
3917 #endif
3918 
3919 XXH_FORCE_INLINE XXH_TARGET_AVX2 void
XXH3_accumulate_512_avx2(void * XXH_RESTRICT acc,const void * XXH_RESTRICT input,const void * XXH_RESTRICT secret)3920 XXH3_accumulate_512_avx2( void* XXH_RESTRICT acc,
3921                     const void* XXH_RESTRICT input,
3922                     const void* XXH_RESTRICT secret)
3923 {
3924     XXH_ASSERT((((size_t)acc) & 31) == 0);
3925     {   __m256i* const xacc    =       (__m256i *) acc;
3926         /* Unaligned. This is mainly for pointer arithmetic, and because
3927          * _mm256_loadu_si256 requires  a const __m256i * pointer for some reason. */
3928         const         __m256i* const xinput  = (const __m256i *) input;
3929         /* Unaligned. This is mainly for pointer arithmetic, and because
3930          * _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */
3931         const         __m256i* const xsecret = (const __m256i *) secret;
3932 
3933         size_t i;
3934         for (i=0; i < XXH_STRIPE_LEN/sizeof(__m256i); i++) {
3935             /* data_vec    = xinput[i]; */
3936             __m256i const data_vec    = _mm256_loadu_si256    (xinput+i);
3937             /* key_vec     = xsecret[i]; */
3938             __m256i const key_vec     = _mm256_loadu_si256   (xsecret+i);
3939             /* data_key    = data_vec ^ key_vec; */
3940             __m256i const data_key    = _mm256_xor_si256     (data_vec, key_vec);
3941             /* data_key_lo = data_key >> 32; */
3942             __m256i const data_key_lo = _mm256_shuffle_epi32 (data_key, _MM_SHUFFLE(0, 3, 0, 1));
3943             /* product     = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */
3944             __m256i const product     = _mm256_mul_epu32     (data_key, data_key_lo);
3945             /* xacc[i] += swap(data_vec); */
3946             __m256i const data_swap = _mm256_shuffle_epi32(data_vec, _MM_SHUFFLE(1, 0, 3, 2));
3947             __m256i const sum       = _mm256_add_epi64(xacc[i], data_swap);
3948             /* xacc[i] += product; */
3949             xacc[i] = _mm256_add_epi64(product, sum);
3950     }   }
3951 }
3952 
3953 XXH_FORCE_INLINE XXH_TARGET_AVX2 void
XXH3_scrambleAcc_avx2(void * XXH_RESTRICT acc,const void * XXH_RESTRICT secret)3954 XXH3_scrambleAcc_avx2(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
3955 {
3956     XXH_ASSERT((((size_t)acc) & 31) == 0);
3957     {   __m256i* const xacc = (__m256i*) acc;
3958         /* Unaligned. This is mainly for pointer arithmetic, and because
3959          * _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */
3960         const         __m256i* const xsecret = (const __m256i *) secret;
3961         const __m256i prime32 = _mm256_set1_epi32((int)XXH_PRIME32_1);
3962 
3963         size_t i;
3964         for (i=0; i < XXH_STRIPE_LEN/sizeof(__m256i); i++) {
3965             /* xacc[i] ^= (xacc[i] >> 47) */
3966             __m256i const acc_vec     = xacc[i];
3967             __m256i const shifted     = _mm256_srli_epi64    (acc_vec, 47);
3968             __m256i const data_vec    = _mm256_xor_si256     (acc_vec, shifted);
3969             /* xacc[i] ^= xsecret; */
3970             __m256i const key_vec     = _mm256_loadu_si256   (xsecret+i);
3971             __m256i const data_key    = _mm256_xor_si256     (data_vec, key_vec);
3972 
3973             /* xacc[i] *= XXH_PRIME32_1; */
3974             __m256i const data_key_hi = _mm256_shuffle_epi32 (data_key, _MM_SHUFFLE(0, 3, 0, 1));
3975             __m256i const prod_lo     = _mm256_mul_epu32     (data_key, prime32);
3976             __m256i const prod_hi     = _mm256_mul_epu32     (data_key_hi, prime32);
3977             xacc[i] = _mm256_add_epi64(prod_lo, _mm256_slli_epi64(prod_hi, 32));
3978         }
3979     }
3980 }
3981 
XXH3_initCustomSecret_avx2(void * XXH_RESTRICT customSecret,xxh_u64 seed64)3982 XXH_FORCE_INLINE XXH_TARGET_AVX2 void XXH3_initCustomSecret_avx2(void* XXH_RESTRICT customSecret, xxh_u64 seed64)
3983 {
3984     XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 31) == 0);
3985     XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE / sizeof(__m256i)) == 6);
3986     XXH_STATIC_ASSERT(XXH_SEC_ALIGN <= 64);
3987     (void)(&XXH_writeLE64);
3988     XXH_PREFETCH(customSecret);
3989     {   __m256i const seed = _mm256_set_epi64x((xxh_i64)(0U - seed64), (xxh_i64)seed64, (xxh_i64)(0U - seed64), (xxh_i64)seed64);
3990 
3991         const __m256i* const src  = (const __m256i*) ((const void*) XXH3_kSecret);
3992               __m256i*       dest = (      __m256i*) customSecret;
3993 
3994 #       if defined(__GNUC__) || defined(__clang__)
3995         /*
3996          * On GCC & Clang, marking 'dest' as modified will cause the compiler:
3997          *   - do not extract the secret from sse registers in the internal loop
3998          *   - use less common registers, and avoid pushing these reg into stack
3999          */
4000         XXH_COMPILER_GUARD(dest);
4001 #       endif
4002         XXH_ASSERT(((size_t)src & 31) == 0); /* control alignment */
4003         XXH_ASSERT(((size_t)dest & 31) == 0);
4004 
4005         /* GCC -O2 need unroll loop manually */
4006         dest[0] = _mm256_add_epi64(_mm256_stream_load_si256(src+0), seed);
4007         dest[1] = _mm256_add_epi64(_mm256_stream_load_si256(src+1), seed);
4008         dest[2] = _mm256_add_epi64(_mm256_stream_load_si256(src+2), seed);
4009         dest[3] = _mm256_add_epi64(_mm256_stream_load_si256(src+3), seed);
4010         dest[4] = _mm256_add_epi64(_mm256_stream_load_si256(src+4), seed);
4011         dest[5] = _mm256_add_epi64(_mm256_stream_load_si256(src+5), seed);
4012     }
4013 }
4014 
4015 #endif
4016 
4017 /* x86dispatch always generates SSE2 */
4018 #if (XXH_VECTOR == XXH_SSE2) || defined(XXH_X86DISPATCH)
4019 
4020 #ifndef XXH_TARGET_SSE2
4021 # define XXH_TARGET_SSE2  /* disable attribute target */
4022 #endif
4023 
4024 XXH_FORCE_INLINE XXH_TARGET_SSE2 void
XXH3_accumulate_512_sse2(void * XXH_RESTRICT acc,const void * XXH_RESTRICT input,const void * XXH_RESTRICT secret)4025 XXH3_accumulate_512_sse2( void* XXH_RESTRICT acc,
4026                     const void* XXH_RESTRICT input,
4027                     const void* XXH_RESTRICT secret)
4028 {
4029     /* SSE2 is just a half-scale version of the AVX2 version. */
4030     XXH_ASSERT((((size_t)acc) & 15) == 0);
4031     {   __m128i* const xacc    =       (__m128i *) acc;
4032         /* Unaligned. This is mainly for pointer arithmetic, and because
4033          * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */
4034         const         __m128i* const xinput  = (const __m128i *) input;
4035         /* Unaligned. This is mainly for pointer arithmetic, and because
4036          * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */
4037         const         __m128i* const xsecret = (const __m128i *) secret;
4038 
4039         size_t i;
4040         for (i=0; i < XXH_STRIPE_LEN/sizeof(__m128i); i++) {
4041             /* data_vec    = xinput[i]; */
4042             __m128i const data_vec    = _mm_loadu_si128   (xinput+i);
4043             /* key_vec     = xsecret[i]; */
4044             __m128i const key_vec     = _mm_loadu_si128   (xsecret+i);
4045             /* data_key    = data_vec ^ key_vec; */
4046             __m128i const data_key    = _mm_xor_si128     (data_vec, key_vec);
4047             /* data_key_lo = data_key >> 32; */
4048             __m128i const data_key_lo = _mm_shuffle_epi32 (data_key, _MM_SHUFFLE(0, 3, 0, 1));
4049             /* product     = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */
4050             __m128i const product     = _mm_mul_epu32     (data_key, data_key_lo);
4051             /* xacc[i] += swap(data_vec); */
4052             __m128i const data_swap = _mm_shuffle_epi32(data_vec, _MM_SHUFFLE(1,0,3,2));
4053             __m128i const sum       = _mm_add_epi64(xacc[i], data_swap);
4054             /* xacc[i] += product; */
4055             xacc[i] = _mm_add_epi64(product, sum);
4056     }   }
4057 }
4058 
4059 XXH_FORCE_INLINE XXH_TARGET_SSE2 void
XXH3_scrambleAcc_sse2(void * XXH_RESTRICT acc,const void * XXH_RESTRICT secret)4060 XXH3_scrambleAcc_sse2(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
4061 {
4062     XXH_ASSERT((((size_t)acc) & 15) == 0);
4063     {   __m128i* const xacc = (__m128i*) acc;
4064         /* Unaligned. This is mainly for pointer arithmetic, and because
4065          * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */
4066         const         __m128i* const xsecret = (const __m128i *) secret;
4067         const __m128i prime32 = _mm_set1_epi32((int)XXH_PRIME32_1);
4068 
4069         size_t i;
4070         for (i=0; i < XXH_STRIPE_LEN/sizeof(__m128i); i++) {
4071             /* xacc[i] ^= (xacc[i] >> 47) */
4072             __m128i const acc_vec     = xacc[i];
4073             __m128i const shifted     = _mm_srli_epi64    (acc_vec, 47);
4074             __m128i const data_vec    = _mm_xor_si128     (acc_vec, shifted);
4075             /* xacc[i] ^= xsecret[i]; */
4076             __m128i const key_vec     = _mm_loadu_si128   (xsecret+i);
4077             __m128i const data_key    = _mm_xor_si128     (data_vec, key_vec);
4078 
4079             /* xacc[i] *= XXH_PRIME32_1; */
4080             __m128i const data_key_hi = _mm_shuffle_epi32 (data_key, _MM_SHUFFLE(0, 3, 0, 1));
4081             __m128i const prod_lo     = _mm_mul_epu32     (data_key, prime32);
4082             __m128i const prod_hi     = _mm_mul_epu32     (data_key_hi, prime32);
4083             xacc[i] = _mm_add_epi64(prod_lo, _mm_slli_epi64(prod_hi, 32));
4084         }
4085     }
4086 }
4087 
XXH3_initCustomSecret_sse2(void * XXH_RESTRICT customSecret,xxh_u64 seed64)4088 XXH_FORCE_INLINE XXH_TARGET_SSE2 void XXH3_initCustomSecret_sse2(void* XXH_RESTRICT customSecret, xxh_u64 seed64)
4089 {
4090     XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 15) == 0);
4091     (void)(&XXH_writeLE64);
4092     {   int const nbRounds = XXH_SECRET_DEFAULT_SIZE / sizeof(__m128i);
4093 
4094 #       if defined(_MSC_VER) && defined(_M_IX86) && _MSC_VER < 1900
4095         /* MSVC 32bit mode does not support _mm_set_epi64x before 2015 */
4096         XXH_ALIGN(16) const xxh_i64 seed64x2[2] = { (xxh_i64)seed64, (xxh_i64)(0U - seed64) };
4097         __m128i const seed = _mm_load_si128((__m128i const*)seed64x2);
4098 #       else
4099         __m128i const seed = _mm_set_epi64x((xxh_i64)(0U - seed64), (xxh_i64)seed64);
4100 #       endif
4101         int i;
4102 
4103         const void* const src16 = XXH3_kSecret;
4104         __m128i* dst16 = (__m128i*) customSecret;
4105 #       if defined(__GNUC__) || defined(__clang__)
4106         /*
4107          * On GCC & Clang, marking 'dest' as modified will cause the compiler:
4108          *   - do not extract the secret from sse registers in the internal loop
4109          *   - use less common registers, and avoid pushing these reg into stack
4110          */
4111         XXH_COMPILER_GUARD(dst16);
4112 #       endif
4113         XXH_ASSERT(((size_t)src16 & 15) == 0); /* control alignment */
4114         XXH_ASSERT(((size_t)dst16 & 15) == 0);
4115 
4116         for (i=0; i < nbRounds; ++i) {
4117             dst16[i] = _mm_add_epi64(_mm_load_si128((const __m128i *)src16+i), seed);
4118     }   }
4119 }
4120 
4121 #endif
4122 
4123 #if (XXH_VECTOR == XXH_NEON)
4124 
4125 XXH_FORCE_INLINE void
XXH3_accumulate_512_neon(void * XXH_RESTRICT acc,const void * XXH_RESTRICT input,const void * XXH_RESTRICT secret)4126 XXH3_accumulate_512_neon( void* XXH_RESTRICT acc,
4127                     const void* XXH_RESTRICT input,
4128                     const void* XXH_RESTRICT secret)
4129 {
4130     XXH_ASSERT((((size_t)acc) & 15) == 0);
4131     XXH_STATIC_ASSERT(XXH3_NEON_LANES > 0 && XXH3_NEON_LANES <= XXH_ACC_NB && XXH3_NEON_LANES % 2 == 0);
4132     {
4133         uint64x2_t* const xacc = (uint64x2_t *) acc;
4134         /* We don't use a uint32x4_t pointer because it causes bus errors on ARMv7. */
4135         uint8_t const* const xinput = (const uint8_t *) input;
4136         uint8_t const* const xsecret  = (const uint8_t *) secret;
4137 
4138         size_t i;
4139         for (i=0; i < XXH3_NEON_LANES / 2; i++) {
4140             /* data_vec = xinput[i]; */
4141             uint8x16_t data_vec    = vld1q_u8(xinput  + (i * 16));
4142             /* key_vec  = xsecret[i];  */
4143             uint8x16_t key_vec     = vld1q_u8(xsecret + (i * 16));
4144             uint64x2_t data_key;
4145             uint32x2_t data_key_lo, data_key_hi;
4146             /* xacc[i] += swap(data_vec); */
4147             uint64x2_t const data64  = vreinterpretq_u64_u8(data_vec);
4148             uint64x2_t const swapped = vextq_u64(data64, data64, 1);
4149             xacc[i] = vaddq_u64 (xacc[i], swapped);
4150             /* data_key = data_vec ^ key_vec; */
4151             data_key = vreinterpretq_u64_u8(veorq_u8(data_vec, key_vec));
4152             /* data_key_lo = (uint32x2_t) (data_key & 0xFFFFFFFF);
4153              * data_key_hi = (uint32x2_t) (data_key >> 32);
4154              * data_key = UNDEFINED; */
4155             XXH_SPLIT_IN_PLACE(data_key, data_key_lo, data_key_hi);
4156             /* xacc[i] += (uint64x2_t) data_key_lo * (uint64x2_t) data_key_hi; */
4157             xacc[i] = vmlal_u32 (xacc[i], data_key_lo, data_key_hi);
4158 
4159         }
4160         /* AArch64 uses both scalar and neon at the same time */
4161         for (i = XXH3_NEON_LANES; i < XXH_ACC_NB; i++) {
4162             XXH3_scalarRound(acc, input, secret, i);
4163         }
4164     }
4165 }
4166 
4167 XXH_FORCE_INLINE void
XXH3_scrambleAcc_neon(void * XXH_RESTRICT acc,const void * XXH_RESTRICT secret)4168 XXH3_scrambleAcc_neon(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
4169 {
4170     XXH_ASSERT((((size_t)acc) & 15) == 0);
4171 
4172     {   uint64x2_t* xacc       = (uint64x2_t*) acc;
4173         uint8_t const* xsecret = (uint8_t const*) secret;
4174         uint32x2_t prime       = vdup_n_u32 (XXH_PRIME32_1);
4175 
4176         size_t i;
4177         for (i=0; i < XXH3_NEON_LANES / 2; i++) {
4178             /* xacc[i] ^= (xacc[i] >> 47); */
4179             uint64x2_t acc_vec  = xacc[i];
4180             uint64x2_t shifted  = vshrq_n_u64 (acc_vec, 47);
4181             uint64x2_t data_vec = veorq_u64   (acc_vec, shifted);
4182 
4183             /* xacc[i] ^= xsecret[i]; */
4184             uint8x16_t key_vec  = vld1q_u8    (xsecret + (i * 16));
4185             uint64x2_t data_key = veorq_u64   (data_vec, vreinterpretq_u64_u8(key_vec));
4186 
4187             /* xacc[i] *= XXH_PRIME32_1 */
4188             uint32x2_t data_key_lo, data_key_hi;
4189             /* data_key_lo = (uint32x2_t) (xacc[i] & 0xFFFFFFFF);
4190              * data_key_hi = (uint32x2_t) (xacc[i] >> 32);
4191              * xacc[i] = UNDEFINED; */
4192             XXH_SPLIT_IN_PLACE(data_key, data_key_lo, data_key_hi);
4193             {   /*
4194                  * prod_hi = (data_key >> 32) * XXH_PRIME32_1;
4195                  *
4196                  * Avoid vmul_u32 + vshll_n_u32 since Clang 6 and 7 will
4197                  * incorrectly "optimize" this:
4198                  *   tmp     = vmul_u32(vmovn_u64(a), vmovn_u64(b));
4199                  *   shifted = vshll_n_u32(tmp, 32);
4200                  * to this:
4201                  *   tmp     = "vmulq_u64"(a, b); // no such thing!
4202                  *   shifted = vshlq_n_u64(tmp, 32);
4203                  *
4204                  * However, unlike SSE, Clang lacks a 64-bit multiply routine
4205                  * for NEON, and it scalarizes two 64-bit multiplies instead.
4206                  *
4207                  * vmull_u32 has the same timing as vmul_u32, and it avoids
4208                  * this bug completely.
4209                  * See https://bugs.llvm.org/show_bug.cgi?id=39967
4210                  */
4211                 uint64x2_t prod_hi = vmull_u32 (data_key_hi, prime);
4212                 /* xacc[i] = prod_hi << 32; */
4213                 xacc[i] = vshlq_n_u64(prod_hi, 32);
4214                 /* xacc[i] += (prod_hi & 0xFFFFFFFF) * XXH_PRIME32_1; */
4215                 xacc[i] = vmlal_u32(xacc[i], data_key_lo, prime);
4216             }
4217         }
4218         /* AArch64 uses both scalar and neon at the same time */
4219         for (i = XXH3_NEON_LANES; i < XXH_ACC_NB; i++) {
4220             XXH3_scalarScrambleRound(acc, secret, i);
4221         }
4222     }
4223 }
4224 
4225 #endif
4226 
4227 #if (XXH_VECTOR == XXH_VSX)
4228 
4229 XXH_FORCE_INLINE void
XXH3_accumulate_512_vsx(void * XXH_RESTRICT acc,const void * XXH_RESTRICT input,const void * XXH_RESTRICT secret)4230 XXH3_accumulate_512_vsx(  void* XXH_RESTRICT acc,
4231                     const void* XXH_RESTRICT input,
4232                     const void* XXH_RESTRICT secret)
4233 {
4234     /* presumed aligned */
4235     unsigned int* const xacc = (unsigned int*) acc;
4236     xxh_u64x2 const* const xinput   = (xxh_u64x2 const*) input;   /* no alignment restriction */
4237     xxh_u64x2 const* const xsecret  = (xxh_u64x2 const*) secret;    /* no alignment restriction */
4238     xxh_u64x2 const v32 = { 32, 32 };
4239     size_t i;
4240     for (i = 0; i < XXH_STRIPE_LEN / sizeof(xxh_u64x2); i++) {
4241         /* data_vec = xinput[i]; */
4242         xxh_u64x2 const data_vec = XXH_vec_loadu(xinput + i);
4243         /* key_vec = xsecret[i]; */
4244         xxh_u64x2 const key_vec  = XXH_vec_loadu(xsecret + i);
4245         xxh_u64x2 const data_key = data_vec ^ key_vec;
4246         /* shuffled = (data_key << 32) | (data_key >> 32); */
4247         xxh_u32x4 const shuffled = (xxh_u32x4)vec_rl(data_key, v32);
4248         /* product = ((xxh_u64x2)data_key & 0xFFFFFFFF) * ((xxh_u64x2)shuffled & 0xFFFFFFFF); */
4249         xxh_u64x2 const product  = XXH_vec_mulo((xxh_u32x4)data_key, shuffled);
4250         /* acc_vec = xacc[i]; */
4251         xxh_u64x2 acc_vec        = (xxh_u64x2)vec_xl(0, xacc + 4 * i);
4252         acc_vec += product;
4253 
4254         /* swap high and low halves */
4255 #ifdef __s390x__
4256         acc_vec += vec_permi(data_vec, data_vec, 2);
4257 #else
4258         acc_vec += vec_xxpermdi(data_vec, data_vec, 2);
4259 #endif
4260         /* xacc[i] = acc_vec; */
4261         vec_xst((xxh_u32x4)acc_vec, 0, xacc + 4 * i);
4262     }
4263 }
4264 
4265 XXH_FORCE_INLINE void
XXH3_scrambleAcc_vsx(void * XXH_RESTRICT acc,const void * XXH_RESTRICT secret)4266 XXH3_scrambleAcc_vsx(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
4267 {
4268     XXH_ASSERT((((size_t)acc) & 15) == 0);
4269 
4270     {         xxh_u64x2* const xacc    =       (xxh_u64x2*) acc;
4271         const xxh_u64x2* const xsecret = (const xxh_u64x2*) secret;
4272         /* constants */
4273         xxh_u64x2 const v32  = { 32, 32 };
4274         xxh_u64x2 const v47 = { 47, 47 };
4275         xxh_u32x4 const prime = { XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1, XXH_PRIME32_1 };
4276         size_t i;
4277         for (i = 0; i < XXH_STRIPE_LEN / sizeof(xxh_u64x2); i++) {
4278             /* xacc[i] ^= (xacc[i] >> 47); */
4279             xxh_u64x2 const acc_vec  = xacc[i];
4280             xxh_u64x2 const data_vec = acc_vec ^ (acc_vec >> v47);
4281 
4282             /* xacc[i] ^= xsecret[i]; */
4283             xxh_u64x2 const key_vec  = XXH_vec_loadu(xsecret + i);
4284             xxh_u64x2 const data_key = data_vec ^ key_vec;
4285 
4286             /* xacc[i] *= XXH_PRIME32_1 */
4287             /* prod_lo = ((xxh_u64x2)data_key & 0xFFFFFFFF) * ((xxh_u64x2)prime & 0xFFFFFFFF);  */
4288             xxh_u64x2 const prod_even  = XXH_vec_mule((xxh_u32x4)data_key, prime);
4289             /* prod_hi = ((xxh_u64x2)data_key >> 32) * ((xxh_u64x2)prime >> 32);  */
4290             xxh_u64x2 const prod_odd  = XXH_vec_mulo((xxh_u32x4)data_key, prime);
4291             xacc[i] = prod_odd + (prod_even << v32);
4292     }   }
4293 }
4294 
4295 #endif
4296 
4297 /* scalar variants - universal */
4298 
4299 XXH_FORCE_INLINE void
XXH3_accumulate_512_scalar(void * XXH_RESTRICT acc,const void * XXH_RESTRICT input,const void * XXH_RESTRICT secret)4300 XXH3_accumulate_512_scalar(void* XXH_RESTRICT acc,
4301                      const void* XXH_RESTRICT input,
4302                      const void* XXH_RESTRICT secret)
4303 {
4304     size_t i;
4305     for (i=0; i < XXH_ACC_NB; i++) {
4306         XXH3_scalarRound(acc, input, secret, i);
4307     }
4308 }
4309 
4310 XXH_FORCE_INLINE void
XXH3_scrambleAcc_scalar(void * XXH_RESTRICT acc,const void * XXH_RESTRICT secret)4311 XXH3_scrambleAcc_scalar(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
4312 {
4313     size_t i;
4314     for (i=0; i < XXH_ACC_NB; i++) {
4315         XXH3_scalarScrambleRound(acc, secret, i);
4316     }
4317 }
4318 
4319 XXH_FORCE_INLINE void
XXH3_initCustomSecret_scalar(void * XXH_RESTRICT customSecret,xxh_u64 seed64)4320 XXH3_initCustomSecret_scalar(void* XXH_RESTRICT customSecret, xxh_u64 seed64)
4321 {
4322     /*
4323      * We need a separate pointer for the hack below,
4324      * which requires a non-const pointer.
4325      * Any decent compiler will optimize this out otherwise.
4326      */
4327     const xxh_u8* kSecretPtr = XXH3_kSecret;
4328     XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 15) == 0);
4329 
4330 #if defined(__clang__) && defined(__aarch64__)
4331     /*
4332      * UGLY HACK:
4333      * Clang generates a bunch of MOV/MOVK pairs for aarch64, and they are
4334      * placed sequentially, in order, at the top of the unrolled loop.
4335      *
4336      * While MOVK is great for generating constants (2 cycles for a 64-bit
4337      * constant compared to 4 cycles for LDR), long MOVK chains stall the
4338      * integer pipelines:
4339      *   I   L   S
4340      * MOVK
4341      * MOVK
4342      * MOVK
4343      * MOVK
4344      * ADD
4345      * SUB      STR
4346      *          STR
4347      * By forcing loads from memory (as the asm line causes Clang to assume
4348      * that XXH3_kSecretPtr has been changed), the pipelines are used more
4349      * efficiently:
4350      *   I   L   S
4351      *      LDR
4352      *  ADD LDR
4353      *  SUB     STR
4354      *          STR
4355      * XXH3_64bits_withSeed, len == 256, Snapdragon 835
4356      *   without hack: 2654.4 MB/s
4357      *   with hack:    3202.9 MB/s
4358      */
4359     XXH_COMPILER_GUARD(kSecretPtr);
4360 #endif
4361     /*
4362      * Note: in debug mode, this overrides the asm optimization
4363      * and Clang will emit MOVK chains again.
4364      */
4365     XXH_ASSERT(kSecretPtr == XXH3_kSecret);
4366 
4367     {   int const nbRounds = XXH_SECRET_DEFAULT_SIZE / 16;
4368         int i;
4369         for (i=0; i < nbRounds; i++) {
4370             /*
4371              * The asm hack causes Clang to assume that kSecretPtr aliases with
4372              * customSecret, and on aarch64, this prevented LDP from merging two
4373              * loads together for free. Putting the loads together before the stores
4374              * properly generates LDP.
4375              */
4376             xxh_u64 lo = XXH_readLE64(kSecretPtr + 16*i)     + seed64;
4377             xxh_u64 hi = XXH_readLE64(kSecretPtr + 16*i + 8) - seed64;
4378             XXH_writeLE64((xxh_u8*)customSecret + 16*i,     lo);
4379             XXH_writeLE64((xxh_u8*)customSecret + 16*i + 8, hi);
4380     }   }
4381 }
4382 
4383 
4384 typedef void (*XXH3_f_accumulate_512)(void* XXH_RESTRICT, const void*, const void*);
4385 typedef void (*XXH3_f_scrambleAcc)(void* XXH_RESTRICT, const void*);
4386 typedef void (*XXH3_f_initCustomSecret)(void* XXH_RESTRICT, xxh_u64);
4387 
4388 
4389 #if (XXH_VECTOR == XXH_AVX512)
4390 
4391 #define XXH3_accumulate_512 XXH3_accumulate_512_avx512
4392 #define XXH3_scrambleAcc    XXH3_scrambleAcc_avx512
4393 #define XXH3_initCustomSecret XXH3_initCustomSecret_avx512
4394 
4395 #elif (XXH_VECTOR == XXH_AVX2)
4396 
4397 #define XXH3_accumulate_512 XXH3_accumulate_512_avx2
4398 #define XXH3_scrambleAcc    XXH3_scrambleAcc_avx2
4399 #define XXH3_initCustomSecret XXH3_initCustomSecret_avx2
4400 
4401 #elif (XXH_VECTOR == XXH_SSE2)
4402 
4403 #define XXH3_accumulate_512 XXH3_accumulate_512_sse2
4404 #define XXH3_scrambleAcc    XXH3_scrambleAcc_sse2
4405 #define XXH3_initCustomSecret XXH3_initCustomSecret_sse2
4406 
4407 #elif (XXH_VECTOR == XXH_NEON)
4408 
4409 #define XXH3_accumulate_512 XXH3_accumulate_512_neon
4410 #define XXH3_scrambleAcc    XXH3_scrambleAcc_neon
4411 #define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
4412 
4413 #elif (XXH_VECTOR == XXH_VSX)
4414 
4415 #define XXH3_accumulate_512 XXH3_accumulate_512_vsx
4416 #define XXH3_scrambleAcc    XXH3_scrambleAcc_vsx
4417 #define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
4418 
4419 #else /* scalar */
4420 
4421 #define XXH3_accumulate_512 XXH3_accumulate_512_scalar
4422 #define XXH3_scrambleAcc    XXH3_scrambleAcc_scalar
4423 #define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
4424 
4425 #endif
4426 
4427 
4428 
4429 #ifndef XXH_PREFETCH_DIST
4430 #  ifdef __clang__
4431 #    define XXH_PREFETCH_DIST 320
4432 #  else
4433 #    if (XXH_VECTOR == XXH_AVX512)
4434 #      define XXH_PREFETCH_DIST 512
4435 #    else
4436 #      define XXH_PREFETCH_DIST 384
4437 #    endif
4438 #  endif  /* __clang__ */
4439 #endif  /* XXH_PREFETCH_DIST */
4440 
4441 /*
4442  * XXH3_accumulate()
4443  * Loops over XXH3_accumulate_512().
4444  * Assumption: nbStripes will not overflow the secret size
4445  */
4446 XXH_FORCE_INLINE void
XXH3_accumulate(xxh_u64 * XXH_RESTRICT acc,const xxh_u8 * XXH_RESTRICT input,const xxh_u8 * XXH_RESTRICT secret,size_t nbStripes,XXH3_f_accumulate_512 f_acc512)4447 XXH3_accumulate(     xxh_u64* XXH_RESTRICT acc,
4448                 const xxh_u8* XXH_RESTRICT input,
4449                 const xxh_u8* XXH_RESTRICT secret,
4450                       size_t nbStripes,
4451                       XXH3_f_accumulate_512 f_acc512)
4452 {
4453     size_t n;
4454     for (n = 0; n < nbStripes; n++ ) {
4455         const xxh_u8* const in = input + n*XXH_STRIPE_LEN;
4456         XXH_PREFETCH(in + XXH_PREFETCH_DIST);
4457         f_acc512(acc,
4458                  in,
4459                  secret + n*XXH_SECRET_CONSUME_RATE);
4460     }
4461 }
4462 
4463 XXH_FORCE_INLINE void
XXH3_hashLong_internal_loop(xxh_u64 * XXH_RESTRICT acc,const xxh_u8 * XXH_RESTRICT input,size_t len,const xxh_u8 * XXH_RESTRICT secret,size_t secretSize,XXH3_f_accumulate_512 f_acc512,XXH3_f_scrambleAcc f_scramble)4464 XXH3_hashLong_internal_loop(xxh_u64* XXH_RESTRICT acc,
4465                       const xxh_u8* XXH_RESTRICT input, size_t len,
4466                       const xxh_u8* XXH_RESTRICT secret, size_t secretSize,
4467                             XXH3_f_accumulate_512 f_acc512,
4468                             XXH3_f_scrambleAcc f_scramble)
4469 {
4470     size_t const nbStripesPerBlock = (secretSize - XXH_STRIPE_LEN) / XXH_SECRET_CONSUME_RATE;
4471     size_t const block_len = XXH_STRIPE_LEN * nbStripesPerBlock;
4472     size_t const nb_blocks = (len - 1) / block_len;
4473 
4474     size_t n;
4475 
4476     XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
4477 
4478     for (n = 0; n < nb_blocks; n++) {
4479         XXH3_accumulate(acc, input + n*block_len, secret, nbStripesPerBlock, f_acc512);
4480         f_scramble(acc, secret + secretSize - XXH_STRIPE_LEN);
4481     }
4482 
4483     /* last partial block */
4484     XXH_ASSERT(len > XXH_STRIPE_LEN);
4485     {   size_t const nbStripes = ((len - 1) - (block_len * nb_blocks)) / XXH_STRIPE_LEN;
4486         XXH_ASSERT(nbStripes <= (secretSize / XXH_SECRET_CONSUME_RATE));
4487         XXH3_accumulate(acc, input + nb_blocks*block_len, secret, nbStripes, f_acc512);
4488 
4489         /* last stripe */
4490         {   const xxh_u8* const p = input + len - XXH_STRIPE_LEN;
4491 #define XXH_SECRET_LASTACC_START 7  /* not aligned on 8, last secret is different from acc & scrambler */
4492             f_acc512(acc, p, secret + secretSize - XXH_STRIPE_LEN - XXH_SECRET_LASTACC_START);
4493     }   }
4494 }
4495 
4496 XXH_FORCE_INLINE xxh_u64
XXH3_mix2Accs(const xxh_u64 * XXH_RESTRICT acc,const xxh_u8 * XXH_RESTRICT secret)4497 XXH3_mix2Accs(const xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT secret)
4498 {
4499     return XXH3_mul128_fold64(
4500                acc[0] ^ XXH_readLE64(secret),
4501                acc[1] ^ XXH_readLE64(secret+8) );
4502 }
4503 
4504 static XXH64_hash_t
XXH3_mergeAccs(const xxh_u64 * XXH_RESTRICT acc,const xxh_u8 * XXH_RESTRICT secret,xxh_u64 start)4505 XXH3_mergeAccs(const xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT secret, xxh_u64 start)
4506 {
4507     xxh_u64 result64 = start;
4508     size_t i = 0;
4509 
4510     for (i = 0; i < 4; i++) {
4511         result64 += XXH3_mix2Accs(acc+2*i, secret + 16*i);
4512 #if defined(__clang__)                                /* Clang */ \
4513     && (defined(__arm__) || defined(__thumb__))       /* ARMv7 */ \
4514     && (defined(__ARM_NEON) || defined(__ARM_NEON__)) /* NEON */  \
4515     && !defined(XXH_ENABLE_AUTOVECTORIZE)             /* Define to disable */
4516         /*
4517          * UGLY HACK:
4518          * Prevent autovectorization on Clang ARMv7-a. Exact same problem as
4519          * the one in XXH3_len_129to240_64b. Speeds up shorter keys > 240b.
4520          * XXH3_64bits, len == 256, Snapdragon 835:
4521          *   without hack: 2063.7 MB/s
4522          *   with hack:    2560.7 MB/s
4523          */
4524         XXH_COMPILER_GUARD(result64);
4525 #endif
4526     }
4527 
4528     return XXH3_avalanche(result64);
4529 }
4530 
4531 #define XXH3_INIT_ACC { XXH_PRIME32_3, XXH_PRIME64_1, XXH_PRIME64_2, XXH_PRIME64_3, \
4532                         XXH_PRIME64_4, XXH_PRIME32_2, XXH_PRIME64_5, XXH_PRIME32_1 }
4533 
4534 XXH_FORCE_INLINE XXH64_hash_t
XXH3_hashLong_64b_internal(const void * XXH_RESTRICT input,size_t len,const void * XXH_RESTRICT secret,size_t secretSize,XXH3_f_accumulate_512 f_acc512,XXH3_f_scrambleAcc f_scramble)4535 XXH3_hashLong_64b_internal(const void* XXH_RESTRICT input, size_t len,
4536                            const void* XXH_RESTRICT secret, size_t secretSize,
4537                            XXH3_f_accumulate_512 f_acc512,
4538                            XXH3_f_scrambleAcc f_scramble)
4539 {
4540     XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[XXH_ACC_NB] = XXH3_INIT_ACC;
4541 
4542     XXH3_hashLong_internal_loop(acc, (const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize, f_acc512, f_scramble);
4543 
4544     /* converge into final hash */
4545     XXH_STATIC_ASSERT(sizeof(acc) == 64);
4546     /* do not align on 8, so that the secret is different from the accumulator */
4547 #define XXH_SECRET_MERGEACCS_START 11
4548     XXH_ASSERT(secretSize >= sizeof(acc) + XXH_SECRET_MERGEACCS_START);
4549     return XXH3_mergeAccs(acc, (const xxh_u8*)secret + XXH_SECRET_MERGEACCS_START, (xxh_u64)len * XXH_PRIME64_1);
4550 }
4551 
4552 /*
4553  * It's important for performance to transmit secret's size (when it's static)
4554  * so that the compiler can properly optimize the vectorized loop.
4555  * This makes a big performance difference for "medium" keys (<1 KB) when using AVX instruction set.
4556  */
4557 XXH_FORCE_INLINE XXH64_hash_t
XXH3_hashLong_64b_withSecret(const void * XXH_RESTRICT input,size_t len,XXH64_hash_t seed64,const xxh_u8 * XXH_RESTRICT secret,size_t secretLen)4558 XXH3_hashLong_64b_withSecret(const void* XXH_RESTRICT input, size_t len,
4559                              XXH64_hash_t seed64, const xxh_u8* XXH_RESTRICT secret, size_t secretLen)
4560 {
4561     (void)seed64;
4562     return XXH3_hashLong_64b_internal(input, len, secret, secretLen, XXH3_accumulate_512, XXH3_scrambleAcc);
4563 }
4564 
4565 /*
4566  * It's preferable for performance that XXH3_hashLong is not inlined,
4567  * as it results in a smaller function for small data, easier to the instruction cache.
4568  * Note that inside this no_inline function, we do inline the internal loop,
4569  * and provide a statically defined secret size to allow optimization of vector loop.
4570  */
4571 XXH_NO_INLINE XXH64_hash_t
XXH3_hashLong_64b_default(const void * XXH_RESTRICT input,size_t len,XXH64_hash_t seed64,const xxh_u8 * XXH_RESTRICT secret,size_t secretLen)4572 XXH3_hashLong_64b_default(const void* XXH_RESTRICT input, size_t len,
4573                           XXH64_hash_t seed64, const xxh_u8* XXH_RESTRICT secret, size_t secretLen)
4574 {
4575     (void)seed64; (void)secret; (void)secretLen;
4576     return XXH3_hashLong_64b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate_512, XXH3_scrambleAcc);
4577 }
4578 
4579 /*
4580  * XXH3_hashLong_64b_withSeed():
4581  * Generate a custom key based on alteration of default XXH3_kSecret with the seed,
4582  * and then use this key for long mode hashing.
4583  *
4584  * This operation is decently fast but nonetheless costs a little bit of time.
4585  * Try to avoid it whenever possible (typically when seed==0).
4586  *
4587  * It's important for performance that XXH3_hashLong is not inlined. Not sure
4588  * why (uop cache maybe?), but the difference is large and easily measurable.
4589  */
4590 XXH_FORCE_INLINE XXH64_hash_t
XXH3_hashLong_64b_withSeed_internal(const void * input,size_t len,XXH64_hash_t seed,XXH3_f_accumulate_512 f_acc512,XXH3_f_scrambleAcc f_scramble,XXH3_f_initCustomSecret f_initSec)4591 XXH3_hashLong_64b_withSeed_internal(const void* input, size_t len,
4592                                     XXH64_hash_t seed,
4593                                     XXH3_f_accumulate_512 f_acc512,
4594                                     XXH3_f_scrambleAcc f_scramble,
4595                                     XXH3_f_initCustomSecret f_initSec)
4596 {
4597     if (seed == 0)
4598         return XXH3_hashLong_64b_internal(input, len,
4599                                           XXH3_kSecret, sizeof(XXH3_kSecret),
4600                                           f_acc512, f_scramble);
4601     {   XXH_ALIGN(XXH_SEC_ALIGN) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE];
4602         f_initSec(secret, seed);
4603         return XXH3_hashLong_64b_internal(input, len, secret, sizeof(secret),
4604                                           f_acc512, f_scramble);
4605     }
4606 }
4607 
4608 /*
4609  * It's important for performance that XXH3_hashLong is not inlined.
4610  */
4611 XXH_NO_INLINE XXH64_hash_t
XXH3_hashLong_64b_withSeed(const void * input,size_t len,XXH64_hash_t seed,const xxh_u8 * secret,size_t secretLen)4612 XXH3_hashLong_64b_withSeed(const void* input, size_t len,
4613                            XXH64_hash_t seed, const xxh_u8* secret, size_t secretLen)
4614 {
4615     (void)secret; (void)secretLen;
4616     return XXH3_hashLong_64b_withSeed_internal(input, len, seed,
4617                 XXH3_accumulate_512, XXH3_scrambleAcc, XXH3_initCustomSecret);
4618 }
4619 
4620 
4621 typedef XXH64_hash_t (*XXH3_hashLong64_f)(const void* XXH_RESTRICT, size_t,
4622                                           XXH64_hash_t, const xxh_u8* XXH_RESTRICT, size_t);
4623 
4624 XXH_FORCE_INLINE XXH64_hash_t
XXH3_64bits_internal(const void * XXH_RESTRICT input,size_t len,XXH64_hash_t seed64,const void * XXH_RESTRICT secret,size_t secretLen,XXH3_hashLong64_f f_hashLong)4625 XXH3_64bits_internal(const void* XXH_RESTRICT input, size_t len,
4626                      XXH64_hash_t seed64, const void* XXH_RESTRICT secret, size_t secretLen,
4627                      XXH3_hashLong64_f f_hashLong)
4628 {
4629     XXH_ASSERT(secretLen >= XXH3_SECRET_SIZE_MIN);
4630     /*
4631      * If an action is to be taken if `secretLen` condition is not respected,
4632      * it should be done here.
4633      * For now, it's a contract pre-condition.
4634      * Adding a check and a branch here would cost performance at every hash.
4635      * Also, note that function signature doesn't offer room to return an error.
4636      */
4637     if (len <= 16)
4638         return XXH3_len_0to16_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, seed64);
4639     if (len <= 128)
4640         return XXH3_len_17to128_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretLen, seed64);
4641     if (len <= XXH3_MIDSIZE_MAX)
4642         return XXH3_len_129to240_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretLen, seed64);
4643     return f_hashLong(input, len, seed64, (const xxh_u8*)secret, secretLen);
4644 }
4645 
4646 
4647 /* ===   Public entry point   === */
4648 
4649 /*! @ingroup xxh3_family */
XXH3_64bits(const void * input,size_t len)4650 XXH_PUBLIC_API XXH64_hash_t XXH3_64bits(const void* input, size_t len)
4651 {
4652     return XXH3_64bits_internal(input, len, 0, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_default);
4653 }
4654 
4655 /*! @ingroup xxh3_family */
4656 XXH_PUBLIC_API XXH64_hash_t
XXH3_64bits_withSecret(const void * input,size_t len,const void * secret,size_t secretSize)4657 XXH3_64bits_withSecret(const void* input, size_t len, const void* secret, size_t secretSize)
4658 {
4659     return XXH3_64bits_internal(input, len, 0, secret, secretSize, XXH3_hashLong_64b_withSecret);
4660 }
4661 
4662 /*! @ingroup xxh3_family */
4663 XXH_PUBLIC_API XXH64_hash_t
XXH3_64bits_withSeed(const void * input,size_t len,XXH64_hash_t seed)4664 XXH3_64bits_withSeed(const void* input, size_t len, XXH64_hash_t seed)
4665 {
4666     return XXH3_64bits_internal(input, len, seed, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_withSeed);
4667 }
4668 
4669 XXH_PUBLIC_API XXH64_hash_t
XXH3_64bits_withSecretandSeed(const void * input,size_t len,const void * secret,size_t secretSize,XXH64_hash_t seed)4670 XXH3_64bits_withSecretandSeed(const void* input, size_t len, const void* secret, size_t secretSize, XXH64_hash_t seed)
4671 {
4672     if (len <= XXH3_MIDSIZE_MAX)
4673         return XXH3_64bits_internal(input, len, seed, XXH3_kSecret, sizeof(XXH3_kSecret), NULL);
4674     return XXH3_hashLong_64b_withSecret(input, len, seed, (const xxh_u8*)secret, secretSize);
4675 }
4676 
4677 
4678 /* ===   XXH3 streaming   === */
4679 
4680 /*
4681  * Malloc's a pointer that is always aligned to align.
4682  *
4683  * This must be freed with `XXH_alignedFree()`.
4684  *
4685  * malloc typically guarantees 16 byte alignment on 64-bit systems and 8 byte
4686  * alignment on 32-bit. This isn't enough for the 32 byte aligned loads in AVX2
4687  * or on 32-bit, the 16 byte aligned loads in SSE2 and NEON.
4688  *
4689  * This underalignment previously caused a rather obvious crash which went
4690  * completely unnoticed due to XXH3_createState() not actually being tested.
4691  * Credit to RedSpah for noticing this bug.
4692  *
4693  * The alignment is done manually: Functions like posix_memalign or _mm_malloc
4694  * are avoided: To maintain portability, we would have to write a fallback
4695  * like this anyways, and besides, testing for the existence of library
4696  * functions without relying on external build tools is impossible.
4697  *
4698  * The method is simple: Overallocate, manually align, and store the offset
4699  * to the original behind the returned pointer.
4700  *
4701  * Align must be a power of 2 and 8 <= align <= 128.
4702  */
XXH_alignedMalloc(size_t s,size_t align)4703 static void* XXH_alignedMalloc(size_t s, size_t align)
4704 {
4705     XXH_ASSERT(align <= 128 && align >= 8); /* range check */
4706     XXH_ASSERT((align & (align-1)) == 0);   /* power of 2 */
4707     XXH_ASSERT(s != 0 && s < (s + align));  /* empty/overflow */
4708     {   /* Overallocate to make room for manual realignment and an offset byte */
4709         xxh_u8* base = (xxh_u8*)XXH_malloc(s + align);
4710         if (base != NULL) {
4711             /*
4712              * Get the offset needed to align this pointer.
4713              *
4714              * Even if the returned pointer is aligned, there will always be
4715              * at least one byte to store the offset to the original pointer.
4716              */
4717             size_t offset = align - ((size_t)base & (align - 1)); /* base % align */
4718             /* Add the offset for the now-aligned pointer */
4719             xxh_u8* ptr = base + offset;
4720 
4721             XXH_ASSERT((size_t)ptr % align == 0);
4722 
4723             /* Store the offset immediately before the returned pointer. */
4724             ptr[-1] = (xxh_u8)offset;
4725             return ptr;
4726         }
4727         return NULL;
4728     }
4729 }
4730 /*
4731  * Frees an aligned pointer allocated by XXH_alignedMalloc(). Don't pass
4732  * normal malloc'd pointers, XXH_alignedMalloc has a specific data layout.
4733  */
XXH_alignedFree(void * p)4734 static void XXH_alignedFree(void* p)
4735 {
4736     if (p != NULL) {
4737         xxh_u8* ptr = (xxh_u8*)p;
4738         /* Get the offset byte we added in XXH_malloc. */
4739         xxh_u8 offset = ptr[-1];
4740         /* Free the original malloc'd pointer */
4741         xxh_u8* base = ptr - offset;
4742         XXH_free(base);
4743     }
4744 }
4745 /*! @ingroup xxh3_family */
XXH3_createState(void)4746 XXH_PUBLIC_API XXH3_state_t* XXH3_createState(void)
4747 {
4748     XXH3_state_t* const state = (XXH3_state_t*)XXH_alignedMalloc(sizeof(XXH3_state_t), 64);
4749     if (state==NULL) return NULL;
4750     XXH3_INITSTATE(state);
4751     return state;
4752 }
4753 
4754 /*! @ingroup xxh3_family */
XXH3_freeState(XXH3_state_t * statePtr)4755 XXH_PUBLIC_API XXH_errorcode XXH3_freeState(XXH3_state_t* statePtr)
4756 {
4757     XXH_alignedFree(statePtr);
4758     return XXH_OK;
4759 }
4760 
4761 /*! @ingroup xxh3_family */
4762 XXH_PUBLIC_API void
XXH3_copyState(XXH3_state_t * dst_state,const XXH3_state_t * src_state)4763 XXH3_copyState(XXH3_state_t* dst_state, const XXH3_state_t* src_state)
4764 {
4765     XXH_memcpy(dst_state, src_state, sizeof(*dst_state));
4766 }
4767 
4768 static void
XXH3_reset_internal(XXH3_state_t * statePtr,XXH64_hash_t seed,const void * secret,size_t secretSize)4769 XXH3_reset_internal(XXH3_state_t* statePtr,
4770                     XXH64_hash_t seed,
4771                     const void* secret, size_t secretSize)
4772 {
4773     size_t const initStart = offsetof(XXH3_state_t, bufferedSize);
4774     size_t const initLength = offsetof(XXH3_state_t, nbStripesPerBlock) - initStart;
4775     XXH_ASSERT(offsetof(XXH3_state_t, nbStripesPerBlock) > initStart);
4776     XXH_ASSERT(statePtr != NULL);
4777     /* set members from bufferedSize to nbStripesPerBlock (excluded) to 0 */
4778     memset((char*)statePtr + initStart, 0, initLength);
4779     statePtr->acc[0] = XXH_PRIME32_3;
4780     statePtr->acc[1] = XXH_PRIME64_1;
4781     statePtr->acc[2] = XXH_PRIME64_2;
4782     statePtr->acc[3] = XXH_PRIME64_3;
4783     statePtr->acc[4] = XXH_PRIME64_4;
4784     statePtr->acc[5] = XXH_PRIME32_2;
4785     statePtr->acc[6] = XXH_PRIME64_5;
4786     statePtr->acc[7] = XXH_PRIME32_1;
4787     statePtr->seed = seed;
4788     statePtr->useSeed = (seed != 0);
4789     statePtr->extSecret = (const unsigned char*)secret;
4790     XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
4791     statePtr->secretLimit = secretSize - XXH_STRIPE_LEN;
4792     statePtr->nbStripesPerBlock = statePtr->secretLimit / XXH_SECRET_CONSUME_RATE;
4793 }
4794 
4795 /*! @ingroup xxh3_family */
4796 XXH_PUBLIC_API XXH_errorcode
XXH3_64bits_reset(XXH3_state_t * statePtr)4797 XXH3_64bits_reset(XXH3_state_t* statePtr)
4798 {
4799     if (statePtr == NULL) return XXH_ERROR;
4800     XXH3_reset_internal(statePtr, 0, XXH3_kSecret, XXH_SECRET_DEFAULT_SIZE);
4801     return XXH_OK;
4802 }
4803 
4804 /*! @ingroup xxh3_family */
4805 XXH_PUBLIC_API XXH_errorcode
XXH3_64bits_reset_withSecret(XXH3_state_t * statePtr,const void * secret,size_t secretSize)4806 XXH3_64bits_reset_withSecret(XXH3_state_t* statePtr, const void* secret, size_t secretSize)
4807 {
4808     if (statePtr == NULL) return XXH_ERROR;
4809     XXH3_reset_internal(statePtr, 0, secret, secretSize);
4810     if (secret == NULL) return XXH_ERROR;
4811     if (secretSize < XXH3_SECRET_SIZE_MIN) return XXH_ERROR;
4812     return XXH_OK;
4813 }
4814 
4815 /*! @ingroup xxh3_family */
4816 XXH_PUBLIC_API XXH_errorcode
XXH3_64bits_reset_withSeed(XXH3_state_t * statePtr,XXH64_hash_t seed)4817 XXH3_64bits_reset_withSeed(XXH3_state_t* statePtr, XXH64_hash_t seed)
4818 {
4819     if (statePtr == NULL) return XXH_ERROR;
4820     if (seed==0) return XXH3_64bits_reset(statePtr);
4821     if ((seed != statePtr->seed) || (statePtr->extSecret != NULL))
4822         XXH3_initCustomSecret(statePtr->customSecret, seed);
4823     XXH3_reset_internal(statePtr, seed, NULL, XXH_SECRET_DEFAULT_SIZE);
4824     return XXH_OK;
4825 }
4826 
4827 /*! @ingroup xxh3_family */
4828 XXH_PUBLIC_API XXH_errorcode
XXH3_64bits_reset_withSecretandSeed(XXH3_state_t * statePtr,const void * secret,size_t secretSize,XXH64_hash_t seed64)4829 XXH3_64bits_reset_withSecretandSeed(XXH3_state_t* statePtr, const void* secret, size_t secretSize, XXH64_hash_t seed64)
4830 {
4831     if (statePtr == NULL) return XXH_ERROR;
4832     if (secret == NULL) return XXH_ERROR;
4833     if (secretSize < XXH3_SECRET_SIZE_MIN) return XXH_ERROR;
4834     XXH3_reset_internal(statePtr, seed64, secret, secretSize);
4835     statePtr->useSeed = 1; /* always, even if seed64==0 */
4836     return XXH_OK;
4837 }
4838 
4839 /* Note : when XXH3_consumeStripes() is invoked,
4840  * there must be a guarantee that at least one more byte must be consumed from input
4841  * so that the function can blindly consume all stripes using the "normal" secret segment */
4842 XXH_FORCE_INLINE void
XXH3_consumeStripes(xxh_u64 * XXH_RESTRICT acc,size_t * XXH_RESTRICT nbStripesSoFarPtr,size_t nbStripesPerBlock,const xxh_u8 * XXH_RESTRICT input,size_t nbStripes,const xxh_u8 * XXH_RESTRICT secret,size_t secretLimit,XXH3_f_accumulate_512 f_acc512,XXH3_f_scrambleAcc f_scramble)4843 XXH3_consumeStripes(xxh_u64* XXH_RESTRICT acc,
4844                     size_t* XXH_RESTRICT nbStripesSoFarPtr, size_t nbStripesPerBlock,
4845                     const xxh_u8* XXH_RESTRICT input, size_t nbStripes,
4846                     const xxh_u8* XXH_RESTRICT secret, size_t secretLimit,
4847                     XXH3_f_accumulate_512 f_acc512,
4848                     XXH3_f_scrambleAcc f_scramble)
4849 {
4850     XXH_ASSERT(nbStripes <= nbStripesPerBlock);  /* can handle max 1 scramble per invocation */
4851     XXH_ASSERT(*nbStripesSoFarPtr < nbStripesPerBlock);
4852     if (nbStripesPerBlock - *nbStripesSoFarPtr <= nbStripes) {
4853         /* need a scrambling operation */
4854         size_t const nbStripesToEndofBlock = nbStripesPerBlock - *nbStripesSoFarPtr;
4855         size_t const nbStripesAfterBlock = nbStripes - nbStripesToEndofBlock;
4856         XXH3_accumulate(acc, input, secret + nbStripesSoFarPtr[0] * XXH_SECRET_CONSUME_RATE, nbStripesToEndofBlock, f_acc512);
4857         f_scramble(acc, secret + secretLimit);
4858         XXH3_accumulate(acc, input + nbStripesToEndofBlock * XXH_STRIPE_LEN, secret, nbStripesAfterBlock, f_acc512);
4859         *nbStripesSoFarPtr = nbStripesAfterBlock;
4860     } else {
4861         XXH3_accumulate(acc, input, secret + nbStripesSoFarPtr[0] * XXH_SECRET_CONSUME_RATE, nbStripes, f_acc512);
4862         *nbStripesSoFarPtr += nbStripes;
4863     }
4864 }
4865 
4866 #ifndef XXH3_STREAM_USE_STACK
4867 # ifndef __clang__ /* clang doesn't need additional stack space */
4868 #   define XXH3_STREAM_USE_STACK 1
4869 # endif
4870 #endif
4871 /*
4872  * Both XXH3_64bits_update and XXH3_128bits_update use this routine.
4873  */
4874 XXH_FORCE_INLINE XXH_errorcode
XXH3_update(XXH3_state_t * XXH_RESTRICT const state,const xxh_u8 * XXH_RESTRICT input,size_t len,XXH3_f_accumulate_512 f_acc512,XXH3_f_scrambleAcc f_scramble)4875 XXH3_update(XXH3_state_t* XXH_RESTRICT const state,
4876             const xxh_u8* XXH_RESTRICT input, size_t len,
4877             XXH3_f_accumulate_512 f_acc512,
4878             XXH3_f_scrambleAcc f_scramble)
4879 {
4880     if (input==NULL) {
4881         XXH_ASSERT(len == 0);
4882         return XXH_OK;
4883     }
4884 
4885     XXH_ASSERT(state != NULL);
4886     {   const xxh_u8* const bEnd = input + len;
4887         const unsigned char* const secret = (state->extSecret == NULL) ? state->customSecret : state->extSecret;
4888 #if defined(XXH3_STREAM_USE_STACK) && XXH3_STREAM_USE_STACK >= 1
4889         /* For some reason, gcc and MSVC seem to suffer greatly
4890          * when operating accumulators directly into state.
4891          * Operating into stack space seems to enable proper optimization.
4892          * clang, on the other hand, doesn't seem to need this trick */
4893         XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[8]; memcpy(acc, state->acc, sizeof(acc));
4894 #else
4895         xxh_u64* XXH_RESTRICT const acc = state->acc;
4896 #endif
4897         state->totalLen += len;
4898         XXH_ASSERT(state->bufferedSize <= XXH3_INTERNALBUFFER_SIZE);
4899 
4900         /* small input : just fill in tmp buffer */
4901         if (state->bufferedSize + len <= XXH3_INTERNALBUFFER_SIZE) {
4902             XXH_memcpy(state->buffer + state->bufferedSize, input, len);
4903             state->bufferedSize += (XXH32_hash_t)len;
4904             return XXH_OK;
4905         }
4906 
4907         /* total input is now > XXH3_INTERNALBUFFER_SIZE */
4908         #define XXH3_INTERNALBUFFER_STRIPES (XXH3_INTERNALBUFFER_SIZE / XXH_STRIPE_LEN)
4909         XXH_STATIC_ASSERT(XXH3_INTERNALBUFFER_SIZE % XXH_STRIPE_LEN == 0);   /* clean multiple */
4910 
4911         /*
4912          * Internal buffer is partially filled (always, except at beginning)
4913          * Complete it, then consume it.
4914          */
4915         if (state->bufferedSize) {
4916             size_t const loadSize = XXH3_INTERNALBUFFER_SIZE - state->bufferedSize;
4917             XXH_memcpy(state->buffer + state->bufferedSize, input, loadSize);
4918             input += loadSize;
4919             XXH3_consumeStripes(acc,
4920                                &state->nbStripesSoFar, state->nbStripesPerBlock,
4921                                 state->buffer, XXH3_INTERNALBUFFER_STRIPES,
4922                                 secret, state->secretLimit,
4923                                 f_acc512, f_scramble);
4924             state->bufferedSize = 0;
4925         }
4926         XXH_ASSERT(input < bEnd);
4927 
4928         /* large input to consume : ingest per full block */
4929         if ((size_t)(bEnd - input) > state->nbStripesPerBlock * XXH_STRIPE_LEN) {
4930             size_t nbStripes = (size_t)(bEnd - 1 - input) / XXH_STRIPE_LEN;
4931             XXH_ASSERT(state->nbStripesPerBlock >= state->nbStripesSoFar);
4932             /* join to current block's end */
4933             {   size_t const nbStripesToEnd = state->nbStripesPerBlock - state->nbStripesSoFar;
4934                 XXH_ASSERT(nbStripesToEnd <= nbStripes);
4935                 XXH3_accumulate(acc, input, secret + state->nbStripesSoFar * XXH_SECRET_CONSUME_RATE, nbStripesToEnd, f_acc512);
4936                 f_scramble(acc, secret + state->secretLimit);
4937                 state->nbStripesSoFar = 0;
4938                 input += nbStripesToEnd * XXH_STRIPE_LEN;
4939                 nbStripes -= nbStripesToEnd;
4940             }
4941             /* consume per entire blocks */
4942             while(nbStripes >= state->nbStripesPerBlock) {
4943                 XXH3_accumulate(acc, input, secret, state->nbStripesPerBlock, f_acc512);
4944                 f_scramble(acc, secret + state->secretLimit);
4945                 input += state->nbStripesPerBlock * XXH_STRIPE_LEN;
4946                 nbStripes -= state->nbStripesPerBlock;
4947             }
4948             /* consume last partial block */
4949             XXH3_accumulate(acc, input, secret, nbStripes, f_acc512);
4950             input += nbStripes * XXH_STRIPE_LEN;
4951             XXH_ASSERT(input < bEnd);  /* at least some bytes left */
4952             state->nbStripesSoFar = nbStripes;
4953             /* buffer predecessor of last partial stripe */
4954             XXH_memcpy(state->buffer + sizeof(state->buffer) - XXH_STRIPE_LEN, input - XXH_STRIPE_LEN, XXH_STRIPE_LEN);
4955             XXH_ASSERT(bEnd - input <= XXH_STRIPE_LEN);
4956         } else {
4957             /* content to consume <= block size */
4958             /* Consume input by a multiple of internal buffer size */
4959             if (bEnd - input > XXH3_INTERNALBUFFER_SIZE) {
4960                 const xxh_u8* const limit = bEnd - XXH3_INTERNALBUFFER_SIZE;
4961                 do {
4962                     XXH3_consumeStripes(acc,
4963                                        &state->nbStripesSoFar, state->nbStripesPerBlock,
4964                                         input, XXH3_INTERNALBUFFER_STRIPES,
4965                                         secret, state->secretLimit,
4966                                         f_acc512, f_scramble);
4967                     input += XXH3_INTERNALBUFFER_SIZE;
4968                 } while (input<limit);
4969                 /* buffer predecessor of last partial stripe */
4970                 XXH_memcpy(state->buffer + sizeof(state->buffer) - XXH_STRIPE_LEN, input - XXH_STRIPE_LEN, XXH_STRIPE_LEN);
4971             }
4972         }
4973 
4974         /* Some remaining input (always) : buffer it */
4975         XXH_ASSERT(input < bEnd);
4976         XXH_ASSERT(bEnd - input <= XXH3_INTERNALBUFFER_SIZE);
4977         XXH_ASSERT(state->bufferedSize == 0);
4978         XXH_memcpy(state->buffer, input, (size_t)(bEnd-input));
4979         state->bufferedSize = (XXH32_hash_t)(bEnd-input);
4980 #if defined(XXH3_STREAM_USE_STACK) && XXH3_STREAM_USE_STACK >= 1
4981         /* save stack accumulators into state */
4982         memcpy(state->acc, acc, sizeof(acc));
4983 #endif
4984     }
4985 
4986     return XXH_OK;
4987 }
4988 
4989 /*! @ingroup xxh3_family */
4990 XXH_PUBLIC_API XXH_errorcode
XXH3_64bits_update(XXH3_state_t * state,const void * input,size_t len)4991 XXH3_64bits_update(XXH3_state_t* state, const void* input, size_t len)
4992 {
4993     return XXH3_update(state, (const xxh_u8*)input, len,
4994                        XXH3_accumulate_512, XXH3_scrambleAcc);
4995 }
4996 
4997 
4998 XXH_FORCE_INLINE void
XXH3_digest_long(XXH64_hash_t * acc,const XXH3_state_t * state,const unsigned char * secret)4999 XXH3_digest_long (XXH64_hash_t* acc,
5000                   const XXH3_state_t* state,
5001                   const unsigned char* secret)
5002 {
5003     /*
5004      * Digest on a local copy. This way, the state remains unaltered, and it can
5005      * continue ingesting more input afterwards.
5006      */
5007     XXH_memcpy(acc, state->acc, sizeof(state->acc));
5008     if (state->bufferedSize >= XXH_STRIPE_LEN) {
5009         size_t const nbStripes = (state->bufferedSize - 1) / XXH_STRIPE_LEN;
5010         size_t nbStripesSoFar = state->nbStripesSoFar;
5011         XXH3_consumeStripes(acc,
5012                            &nbStripesSoFar, state->nbStripesPerBlock,
5013                             state->buffer, nbStripes,
5014                             secret, state->secretLimit,
5015                             XXH3_accumulate_512, XXH3_scrambleAcc);
5016         /* last stripe */
5017         XXH3_accumulate_512(acc,
5018                             state->buffer + state->bufferedSize - XXH_STRIPE_LEN,
5019                             secret + state->secretLimit - XXH_SECRET_LASTACC_START);
5020     } else {  /* bufferedSize < XXH_STRIPE_LEN */
5021         xxh_u8 lastStripe[XXH_STRIPE_LEN];
5022         size_t const catchupSize = XXH_STRIPE_LEN - state->bufferedSize;
5023         XXH_ASSERT(state->bufferedSize > 0);  /* there is always some input buffered */
5024         XXH_memcpy(lastStripe, state->buffer + sizeof(state->buffer) - catchupSize, catchupSize);
5025         XXH_memcpy(lastStripe + catchupSize, state->buffer, state->bufferedSize);
5026         XXH3_accumulate_512(acc,
5027                             lastStripe,
5028                             secret + state->secretLimit - XXH_SECRET_LASTACC_START);
5029     }
5030 }
5031 
5032 /*! @ingroup xxh3_family */
XXH3_64bits_digest(const XXH3_state_t * state)5033 XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_digest (const XXH3_state_t* state)
5034 {
5035     const unsigned char* const secret = (state->extSecret == NULL) ? state->customSecret : state->extSecret;
5036     if (state->totalLen > XXH3_MIDSIZE_MAX) {
5037         XXH_ALIGN(XXH_ACC_ALIGN) XXH64_hash_t acc[XXH_ACC_NB];
5038         XXH3_digest_long(acc, state, secret);
5039         return XXH3_mergeAccs(acc,
5040                               secret + XXH_SECRET_MERGEACCS_START,
5041                               (xxh_u64)state->totalLen * XXH_PRIME64_1);
5042     }
5043     /* totalLen <= XXH3_MIDSIZE_MAX: digesting a short input */
5044     if (state->useSeed)
5045         return XXH3_64bits_withSeed(state->buffer, (size_t)state->totalLen, state->seed);
5046     return XXH3_64bits_withSecret(state->buffer, (size_t)(state->totalLen),
5047                                   secret, state->secretLimit + XXH_STRIPE_LEN);
5048 }
5049 
5050 
5051 
5052 /* ==========================================
5053  * XXH3 128 bits (a.k.a XXH128)
5054  * ==========================================
5055  * XXH3's 128-bit variant has better mixing and strength than the 64-bit variant,
5056  * even without counting the significantly larger output size.
5057  *
5058  * For example, extra steps are taken to avoid the seed-dependent collisions
5059  * in 17-240 byte inputs (See XXH3_mix16B and XXH128_mix32B).
5060  *
5061  * This strength naturally comes at the cost of some speed, especially on short
5062  * lengths. Note that longer hashes are about as fast as the 64-bit version
5063  * due to it using only a slight modification of the 64-bit loop.
5064  *
5065  * XXH128 is also more oriented towards 64-bit machines. It is still extremely
5066  * fast for a _128-bit_ hash on 32-bit (it usually clears XXH64).
5067  */
5068 
5069 XXH_FORCE_INLINE XXH128_hash_t
XXH3_len_1to3_128b(const xxh_u8 * input,size_t len,const xxh_u8 * secret,XXH64_hash_t seed)5070 XXH3_len_1to3_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
5071 {
5072     /* A doubled version of 1to3_64b with different constants. */
5073     XXH_ASSERT(input != NULL);
5074     XXH_ASSERT(1 <= len && len <= 3);
5075     XXH_ASSERT(secret != NULL);
5076     /*
5077      * len = 1: combinedl = { input[0], 0x01, input[0], input[0] }
5078      * len = 2: combinedl = { input[1], 0x02, input[0], input[1] }
5079      * len = 3: combinedl = { input[2], 0x03, input[0], input[1] }
5080      */
5081     {   xxh_u8 const c1 = input[0];
5082         xxh_u8 const c2 = input[len >> 1];
5083         xxh_u8 const c3 = input[len - 1];
5084         xxh_u32 const combinedl = ((xxh_u32)c1 <<16) | ((xxh_u32)c2 << 24)
5085                                 | ((xxh_u32)c3 << 0) | ((xxh_u32)len << 8);
5086         xxh_u32 const combinedh = XXH_rotl32(XXH_swap32(combinedl), 13);
5087         xxh_u64 const bitflipl = (XXH_readLE32(secret) ^ XXH_readLE32(secret+4)) + seed;
5088         xxh_u64 const bitfliph = (XXH_readLE32(secret+8) ^ XXH_readLE32(secret+12)) - seed;
5089         xxh_u64 const keyed_lo = (xxh_u64)combinedl ^ bitflipl;
5090         xxh_u64 const keyed_hi = (xxh_u64)combinedh ^ bitfliph;
5091         XXH128_hash_t h128;
5092         h128.low64  = XXH64_avalanche(keyed_lo);
5093         h128.high64 = XXH64_avalanche(keyed_hi);
5094         return h128;
5095     }
5096 }
5097 
5098 XXH_FORCE_INLINE XXH128_hash_t
XXH3_len_4to8_128b(const xxh_u8 * input,size_t len,const xxh_u8 * secret,XXH64_hash_t seed)5099 XXH3_len_4to8_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
5100 {
5101     XXH_ASSERT(input != NULL);
5102     XXH_ASSERT(secret != NULL);
5103     XXH_ASSERT(4 <= len && len <= 8);
5104     seed ^= (xxh_u64)XXH_swap32((xxh_u32)seed) << 32;
5105     {   xxh_u32 const input_lo = XXH_readLE32(input);
5106         xxh_u32 const input_hi = XXH_readLE32(input + len - 4);
5107         xxh_u64 const input_64 = input_lo + ((xxh_u64)input_hi << 32);
5108         xxh_u64 const bitflip = (XXH_readLE64(secret+16) ^ XXH_readLE64(secret+24)) + seed;
5109         xxh_u64 const keyed = input_64 ^ bitflip;
5110 
5111         /* Shift len to the left to ensure it is even, this avoids even multiplies. */
5112         XXH128_hash_t m128 = XXH_mult64to128(keyed, XXH_PRIME64_1 + (len << 2));
5113 
5114         m128.high64 += (m128.low64 << 1);
5115         m128.low64  ^= (m128.high64 >> 3);
5116 
5117         m128.low64   = XXH_xorshift64(m128.low64, 35);
5118         m128.low64  *= 0x9FB21C651E98DF25ULL;
5119         m128.low64   = XXH_xorshift64(m128.low64, 28);
5120         m128.high64  = XXH3_avalanche(m128.high64);
5121         return m128;
5122     }
5123 }
5124 
5125 XXH_FORCE_INLINE XXH128_hash_t
XXH3_len_9to16_128b(const xxh_u8 * input,size_t len,const xxh_u8 * secret,XXH64_hash_t seed)5126 XXH3_len_9to16_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
5127 {
5128     XXH_ASSERT(input != NULL);
5129     XXH_ASSERT(secret != NULL);
5130     XXH_ASSERT(9 <= len && len <= 16);
5131     {   xxh_u64 const bitflipl = (XXH_readLE64(secret+32) ^ XXH_readLE64(secret+40)) - seed;
5132         xxh_u64 const bitfliph = (XXH_readLE64(secret+48) ^ XXH_readLE64(secret+56)) + seed;
5133         xxh_u64 const input_lo = XXH_readLE64(input);
5134         xxh_u64       input_hi = XXH_readLE64(input + len - 8);
5135         XXH128_hash_t m128 = XXH_mult64to128(input_lo ^ input_hi ^ bitflipl, XXH_PRIME64_1);
5136         /*
5137          * Put len in the middle of m128 to ensure that the length gets mixed to
5138          * both the low and high bits in the 128x64 multiply below.
5139          */
5140         m128.low64 += (xxh_u64)(len - 1) << 54;
5141         input_hi   ^= bitfliph;
5142         /*
5143          * Add the high 32 bits of input_hi to the high 32 bits of m128, then
5144          * add the long product of the low 32 bits of input_hi and XXH_PRIME32_2 to
5145          * the high 64 bits of m128.
5146          *
5147          * The best approach to this operation is different on 32-bit and 64-bit.
5148          */
5149         if (sizeof(void *) < sizeof(xxh_u64)) { /* 32-bit */
5150             /*
5151              * 32-bit optimized version, which is more readable.
5152              *
5153              * On 32-bit, it removes an ADC and delays a dependency between the two
5154              * halves of m128.high64, but it generates an extra mask on 64-bit.
5155              */
5156             m128.high64 += (input_hi & 0xFFFFFFFF00000000ULL) + XXH_mult32to64((xxh_u32)input_hi, XXH_PRIME32_2);
5157         } else {
5158             /*
5159              * 64-bit optimized (albeit more confusing) version.
5160              *
5161              * Uses some properties of addition and multiplication to remove the mask:
5162              *
5163              * Let:
5164              *    a = input_hi.lo = (input_hi & 0x00000000FFFFFFFF)
5165              *    b = input_hi.hi = (input_hi & 0xFFFFFFFF00000000)
5166              *    c = XXH_PRIME32_2
5167              *
5168              *    a + (b * c)
5169              * Inverse Property: x + y - x == y
5170              *    a + (b * (1 + c - 1))
5171              * Distributive Property: x * (y + z) == (x * y) + (x * z)
5172              *    a + (b * 1) + (b * (c - 1))
5173              * Identity Property: x * 1 == x
5174              *    a + b + (b * (c - 1))
5175              *
5176              * Substitute a, b, and c:
5177              *    input_hi.hi + input_hi.lo + ((xxh_u64)input_hi.lo * (XXH_PRIME32_2 - 1))
5178              *
5179              * Since input_hi.hi + input_hi.lo == input_hi, we get this:
5180              *    input_hi + ((xxh_u64)input_hi.lo * (XXH_PRIME32_2 - 1))
5181              */
5182             m128.high64 += input_hi + XXH_mult32to64((xxh_u32)input_hi, XXH_PRIME32_2 - 1);
5183         }
5184         /* m128 ^= XXH_swap64(m128 >> 64); */
5185         m128.low64  ^= XXH_swap64(m128.high64);
5186 
5187         {   /* 128x64 multiply: h128 = m128 * XXH_PRIME64_2; */
5188             XXH128_hash_t h128 = XXH_mult64to128(m128.low64, XXH_PRIME64_2);
5189             h128.high64 += m128.high64 * XXH_PRIME64_2;
5190 
5191             h128.low64   = XXH3_avalanche(h128.low64);
5192             h128.high64  = XXH3_avalanche(h128.high64);
5193             return h128;
5194     }   }
5195 }
5196 
5197 /*
5198  * Assumption: `secret` size is >= XXH3_SECRET_SIZE_MIN
5199  */
5200 XXH_FORCE_INLINE XXH128_hash_t
XXH3_len_0to16_128b(const xxh_u8 * input,size_t len,const xxh_u8 * secret,XXH64_hash_t seed)5201 XXH3_len_0to16_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
5202 {
5203     XXH_ASSERT(len <= 16);
5204     {   if (len > 8) return XXH3_len_9to16_128b(input, len, secret, seed);
5205         if (len >= 4) return XXH3_len_4to8_128b(input, len, secret, seed);
5206         if (len) return XXH3_len_1to3_128b(input, len, secret, seed);
5207         {   XXH128_hash_t h128;
5208             xxh_u64 const bitflipl = XXH_readLE64(secret+64) ^ XXH_readLE64(secret+72);
5209             xxh_u64 const bitfliph = XXH_readLE64(secret+80) ^ XXH_readLE64(secret+88);
5210             h128.low64 = XXH64_avalanche(seed ^ bitflipl);
5211             h128.high64 = XXH64_avalanche( seed ^ bitfliph);
5212             return h128;
5213     }   }
5214 }
5215 
5216 /*
5217  * A bit slower than XXH3_mix16B, but handles multiply by zero better.
5218  */
5219 XXH_FORCE_INLINE XXH128_hash_t
XXH128_mix32B(XXH128_hash_t acc,const xxh_u8 * input_1,const xxh_u8 * input_2,const xxh_u8 * secret,XXH64_hash_t seed)5220 XXH128_mix32B(XXH128_hash_t acc, const xxh_u8* input_1, const xxh_u8* input_2,
5221               const xxh_u8* secret, XXH64_hash_t seed)
5222 {
5223     acc.low64  += XXH3_mix16B (input_1, secret+0, seed);
5224     acc.low64  ^= XXH_readLE64(input_2) + XXH_readLE64(input_2 + 8);
5225     acc.high64 += XXH3_mix16B (input_2, secret+16, seed);
5226     acc.high64 ^= XXH_readLE64(input_1) + XXH_readLE64(input_1 + 8);
5227     return acc;
5228 }
5229 
5230 
5231 XXH_FORCE_INLINE XXH128_hash_t
XXH3_len_17to128_128b(const xxh_u8 * XXH_RESTRICT input,size_t len,const xxh_u8 * XXH_RESTRICT secret,size_t secretSize,XXH64_hash_t seed)5232 XXH3_len_17to128_128b(const xxh_u8* XXH_RESTRICT input, size_t len,
5233                       const xxh_u8* XXH_RESTRICT secret, size_t secretSize,
5234                       XXH64_hash_t seed)
5235 {
5236     XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize;
5237     XXH_ASSERT(16 < len && len <= 128);
5238 
5239     {   XXH128_hash_t acc;
5240         acc.low64 = len * XXH_PRIME64_1;
5241         acc.high64 = 0;
5242         if (len > 32) {
5243             if (len > 64) {
5244                 if (len > 96) {
5245                     acc = XXH128_mix32B(acc, input+48, input+len-64, secret+96, seed);
5246                 }
5247                 acc = XXH128_mix32B(acc, input+32, input+len-48, secret+64, seed);
5248             }
5249             acc = XXH128_mix32B(acc, input+16, input+len-32, secret+32, seed);
5250         }
5251         acc = XXH128_mix32B(acc, input, input+len-16, secret, seed);
5252         {   XXH128_hash_t h128;
5253             h128.low64  = acc.low64 + acc.high64;
5254             h128.high64 = (acc.low64    * XXH_PRIME64_1)
5255                         + (acc.high64   * XXH_PRIME64_4)
5256                         + ((len - seed) * XXH_PRIME64_2);
5257             h128.low64  = XXH3_avalanche(h128.low64);
5258             h128.high64 = (XXH64_hash_t)0 - XXH3_avalanche(h128.high64);
5259             return h128;
5260         }
5261     }
5262 }
5263 
5264 XXH_NO_INLINE XXH128_hash_t
XXH3_len_129to240_128b(const xxh_u8 * XXH_RESTRICT input,size_t len,const xxh_u8 * XXH_RESTRICT secret,size_t secretSize,XXH64_hash_t seed)5265 XXH3_len_129to240_128b(const xxh_u8* XXH_RESTRICT input, size_t len,
5266                        const xxh_u8* XXH_RESTRICT secret, size_t secretSize,
5267                        XXH64_hash_t seed)
5268 {
5269     XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize;
5270     XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX);
5271 
5272     {   XXH128_hash_t acc;
5273         int const nbRounds = (int)len / 32;
5274         int i;
5275         acc.low64 = len * XXH_PRIME64_1;
5276         acc.high64 = 0;
5277         for (i=0; i<4; i++) {
5278             acc = XXH128_mix32B(acc,
5279                                 input  + (32 * i),
5280                                 input  + (32 * i) + 16,
5281                                 secret + (32 * i),
5282                                 seed);
5283         }
5284         acc.low64 = XXH3_avalanche(acc.low64);
5285         acc.high64 = XXH3_avalanche(acc.high64);
5286         XXH_ASSERT(nbRounds >= 4);
5287         for (i=4 ; i < nbRounds; i++) {
5288             acc = XXH128_mix32B(acc,
5289                                 input + (32 * i),
5290                                 input + (32 * i) + 16,
5291                                 secret + XXH3_MIDSIZE_STARTOFFSET + (32 * (i - 4)),
5292                                 seed);
5293         }
5294         /* last bytes */
5295         acc = XXH128_mix32B(acc,
5296                             input + len - 16,
5297                             input + len - 32,
5298                             secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET - 16,
5299                             0ULL - seed);
5300 
5301         {   XXH128_hash_t h128;
5302             h128.low64  = acc.low64 + acc.high64;
5303             h128.high64 = (acc.low64    * XXH_PRIME64_1)
5304                         + (acc.high64   * XXH_PRIME64_4)
5305                         + ((len - seed) * XXH_PRIME64_2);
5306             h128.low64  = XXH3_avalanche(h128.low64);
5307             h128.high64 = (XXH64_hash_t)0 - XXH3_avalanche(h128.high64);
5308             return h128;
5309         }
5310     }
5311 }
5312 
5313 XXH_FORCE_INLINE XXH128_hash_t
XXH3_hashLong_128b_internal(const void * XXH_RESTRICT input,size_t len,const xxh_u8 * XXH_RESTRICT secret,size_t secretSize,XXH3_f_accumulate_512 f_acc512,XXH3_f_scrambleAcc f_scramble)5314 XXH3_hashLong_128b_internal(const void* XXH_RESTRICT input, size_t len,
5315                             const xxh_u8* XXH_RESTRICT secret, size_t secretSize,
5316                             XXH3_f_accumulate_512 f_acc512,
5317                             XXH3_f_scrambleAcc f_scramble)
5318 {
5319     XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[XXH_ACC_NB] = XXH3_INIT_ACC;
5320 
5321     XXH3_hashLong_internal_loop(acc, (const xxh_u8*)input, len, secret, secretSize, f_acc512, f_scramble);
5322 
5323     /* converge into final hash */
5324     XXH_STATIC_ASSERT(sizeof(acc) == 64);
5325     XXH_ASSERT(secretSize >= sizeof(acc) + XXH_SECRET_MERGEACCS_START);
5326     {   XXH128_hash_t h128;
5327         h128.low64  = XXH3_mergeAccs(acc,
5328                                      secret + XXH_SECRET_MERGEACCS_START,
5329                                      (xxh_u64)len * XXH_PRIME64_1);
5330         h128.high64 = XXH3_mergeAccs(acc,
5331                                      secret + secretSize
5332                                             - sizeof(acc) - XXH_SECRET_MERGEACCS_START,
5333                                      ~((xxh_u64)len * XXH_PRIME64_2));
5334         return h128;
5335     }
5336 }
5337 
5338 /*
5339  * It's important for performance that XXH3_hashLong is not inlined.
5340  */
5341 XXH_NO_INLINE XXH128_hash_t
XXH3_hashLong_128b_default(const void * XXH_RESTRICT input,size_t len,XXH64_hash_t seed64,const void * XXH_RESTRICT secret,size_t secretLen)5342 XXH3_hashLong_128b_default(const void* XXH_RESTRICT input, size_t len,
5343                            XXH64_hash_t seed64,
5344                            const void* XXH_RESTRICT secret, size_t secretLen)
5345 {
5346     (void)seed64; (void)secret; (void)secretLen;
5347     return XXH3_hashLong_128b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret),
5348                                        XXH3_accumulate_512, XXH3_scrambleAcc);
5349 }
5350 
5351 /*
5352  * It's important for performance to pass @secretLen (when it's static)
5353  * to the compiler, so that it can properly optimize the vectorized loop.
5354  */
5355 XXH_FORCE_INLINE XXH128_hash_t
XXH3_hashLong_128b_withSecret(const void * XXH_RESTRICT input,size_t len,XXH64_hash_t seed64,const void * XXH_RESTRICT secret,size_t secretLen)5356 XXH3_hashLong_128b_withSecret(const void* XXH_RESTRICT input, size_t len,
5357                               XXH64_hash_t seed64,
5358                               const void* XXH_RESTRICT secret, size_t secretLen)
5359 {
5360     (void)seed64;
5361     return XXH3_hashLong_128b_internal(input, len, (const xxh_u8*)secret, secretLen,
5362                                        XXH3_accumulate_512, XXH3_scrambleAcc);
5363 }
5364 
5365 XXH_FORCE_INLINE XXH128_hash_t
XXH3_hashLong_128b_withSeed_internal(const void * XXH_RESTRICT input,size_t len,XXH64_hash_t seed64,XXH3_f_accumulate_512 f_acc512,XXH3_f_scrambleAcc f_scramble,XXH3_f_initCustomSecret f_initSec)5366 XXH3_hashLong_128b_withSeed_internal(const void* XXH_RESTRICT input, size_t len,
5367                                 XXH64_hash_t seed64,
5368                                 XXH3_f_accumulate_512 f_acc512,
5369                                 XXH3_f_scrambleAcc f_scramble,
5370                                 XXH3_f_initCustomSecret f_initSec)
5371 {
5372     if (seed64 == 0)
5373         return XXH3_hashLong_128b_internal(input, len,
5374                                            XXH3_kSecret, sizeof(XXH3_kSecret),
5375                                            f_acc512, f_scramble);
5376     {   XXH_ALIGN(XXH_SEC_ALIGN) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE];
5377         f_initSec(secret, seed64);
5378         return XXH3_hashLong_128b_internal(input, len, (const xxh_u8*)secret, sizeof(secret),
5379                                            f_acc512, f_scramble);
5380     }
5381 }
5382 
5383 /*
5384  * It's important for performance that XXH3_hashLong is not inlined.
5385  */
5386 XXH_NO_INLINE XXH128_hash_t
XXH3_hashLong_128b_withSeed(const void * input,size_t len,XXH64_hash_t seed64,const void * XXH_RESTRICT secret,size_t secretLen)5387 XXH3_hashLong_128b_withSeed(const void* input, size_t len,
5388                             XXH64_hash_t seed64, const void* XXH_RESTRICT secret, size_t secretLen)
5389 {
5390     (void)secret; (void)secretLen;
5391     return XXH3_hashLong_128b_withSeed_internal(input, len, seed64,
5392                 XXH3_accumulate_512, XXH3_scrambleAcc, XXH3_initCustomSecret);
5393 }
5394 
5395 typedef XXH128_hash_t (*XXH3_hashLong128_f)(const void* XXH_RESTRICT, size_t,
5396                                             XXH64_hash_t, const void* XXH_RESTRICT, size_t);
5397 
5398 XXH_FORCE_INLINE XXH128_hash_t
XXH3_128bits_internal(const void * input,size_t len,XXH64_hash_t seed64,const void * XXH_RESTRICT secret,size_t secretLen,XXH3_hashLong128_f f_hl128)5399 XXH3_128bits_internal(const void* input, size_t len,
5400                       XXH64_hash_t seed64, const void* XXH_RESTRICT secret, size_t secretLen,
5401                       XXH3_hashLong128_f f_hl128)
5402 {
5403     XXH_ASSERT(secretLen >= XXH3_SECRET_SIZE_MIN);
5404     /*
5405      * If an action is to be taken if `secret` conditions are not respected,
5406      * it should be done here.
5407      * For now, it's a contract pre-condition.
5408      * Adding a check and a branch here would cost performance at every hash.
5409      */
5410     if (len <= 16)
5411         return XXH3_len_0to16_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, seed64);
5412     if (len <= 128)
5413         return XXH3_len_17to128_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretLen, seed64);
5414     if (len <= XXH3_MIDSIZE_MAX)
5415         return XXH3_len_129to240_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretLen, seed64);
5416     return f_hl128(input, len, seed64, secret, secretLen);
5417 }
5418 
5419 
5420 /* ===   Public XXH128 API   === */
5421 
5422 /*! @ingroup xxh3_family */
XXH3_128bits(const void * input,size_t len)5423 XXH_PUBLIC_API XXH128_hash_t XXH3_128bits(const void* input, size_t len)
5424 {
5425     return XXH3_128bits_internal(input, len, 0,
5426                                  XXH3_kSecret, sizeof(XXH3_kSecret),
5427                                  XXH3_hashLong_128b_default);
5428 }
5429 
5430 /*! @ingroup xxh3_family */
5431 XXH_PUBLIC_API XXH128_hash_t
XXH3_128bits_withSecret(const void * input,size_t len,const void * secret,size_t secretSize)5432 XXH3_128bits_withSecret(const void* input, size_t len, const void* secret, size_t secretSize)
5433 {
5434     return XXH3_128bits_internal(input, len, 0,
5435                                  (const xxh_u8*)secret, secretSize,
5436                                  XXH3_hashLong_128b_withSecret);
5437 }
5438 
5439 /*! @ingroup xxh3_family */
5440 XXH_PUBLIC_API XXH128_hash_t
XXH3_128bits_withSeed(const void * input,size_t len,XXH64_hash_t seed)5441 XXH3_128bits_withSeed(const void* input, size_t len, XXH64_hash_t seed)
5442 {
5443     return XXH3_128bits_internal(input, len, seed,
5444                                  XXH3_kSecret, sizeof(XXH3_kSecret),
5445                                  XXH3_hashLong_128b_withSeed);
5446 }
5447 
5448 /*! @ingroup xxh3_family */
5449 XXH_PUBLIC_API XXH128_hash_t
XXH3_128bits_withSecretandSeed(const void * input,size_t len,const void * secret,size_t secretSize,XXH64_hash_t seed)5450 XXH3_128bits_withSecretandSeed(const void* input, size_t len, const void* secret, size_t secretSize, XXH64_hash_t seed)
5451 {
5452     if (len <= XXH3_MIDSIZE_MAX)
5453         return XXH3_128bits_internal(input, len, seed, XXH3_kSecret, sizeof(XXH3_kSecret), NULL);
5454     return XXH3_hashLong_128b_withSecret(input, len, seed, secret, secretSize);
5455 }
5456 
5457 /*! @ingroup xxh3_family */
5458 XXH_PUBLIC_API XXH128_hash_t
XXH128(const void * input,size_t len,XXH64_hash_t seed)5459 XXH128(const void* input, size_t len, XXH64_hash_t seed)
5460 {
5461     return XXH3_128bits_withSeed(input, len, seed);
5462 }
5463 
5464 
5465 /* ===   XXH3 128-bit streaming   === */
5466 
5467 /*
5468  * All initialization and update functions are identical to 64-bit streaming variant.
5469  * The only difference is the finalization routine.
5470  */
5471 
5472 /*! @ingroup xxh3_family */
5473 XXH_PUBLIC_API XXH_errorcode
XXH3_128bits_reset(XXH3_state_t * statePtr)5474 XXH3_128bits_reset(XXH3_state_t* statePtr)
5475 {
5476     return XXH3_64bits_reset(statePtr);
5477 }
5478 
5479 /*! @ingroup xxh3_family */
5480 XXH_PUBLIC_API XXH_errorcode
XXH3_128bits_reset_withSecret(XXH3_state_t * statePtr,const void * secret,size_t secretSize)5481 XXH3_128bits_reset_withSecret(XXH3_state_t* statePtr, const void* secret, size_t secretSize)
5482 {
5483     return XXH3_64bits_reset_withSecret(statePtr, secret, secretSize);
5484 }
5485 
5486 /*! @ingroup xxh3_family */
5487 XXH_PUBLIC_API XXH_errorcode
XXH3_128bits_reset_withSeed(XXH3_state_t * statePtr,XXH64_hash_t seed)5488 XXH3_128bits_reset_withSeed(XXH3_state_t* statePtr, XXH64_hash_t seed)
5489 {
5490     return XXH3_64bits_reset_withSeed(statePtr, seed);
5491 }
5492 
5493 /*! @ingroup xxh3_family */
5494 XXH_PUBLIC_API XXH_errorcode
XXH3_128bits_reset_withSecretandSeed(XXH3_state_t * statePtr,const void * secret,size_t secretSize,XXH64_hash_t seed)5495 XXH3_128bits_reset_withSecretandSeed(XXH3_state_t* statePtr, const void* secret, size_t secretSize, XXH64_hash_t seed)
5496 {
5497     return XXH3_64bits_reset_withSecretandSeed(statePtr, secret, secretSize, seed);
5498 }
5499 
5500 /*! @ingroup xxh3_family */
5501 XXH_PUBLIC_API XXH_errorcode
XXH3_128bits_update(XXH3_state_t * state,const void * input,size_t len)5502 XXH3_128bits_update(XXH3_state_t* state, const void* input, size_t len)
5503 {
5504     return XXH3_update(state, (const xxh_u8*)input, len,
5505                        XXH3_accumulate_512, XXH3_scrambleAcc);
5506 }
5507 
5508 /*! @ingroup xxh3_family */
XXH3_128bits_digest(const XXH3_state_t * state)5509 XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_digest (const XXH3_state_t* state)
5510 {
5511     const unsigned char* const secret = (state->extSecret == NULL) ? state->customSecret : state->extSecret;
5512     if (state->totalLen > XXH3_MIDSIZE_MAX) {
5513         XXH_ALIGN(XXH_ACC_ALIGN) XXH64_hash_t acc[XXH_ACC_NB];
5514         XXH3_digest_long(acc, state, secret);
5515         XXH_ASSERT(state->secretLimit + XXH_STRIPE_LEN >= sizeof(acc) + XXH_SECRET_MERGEACCS_START);
5516         {   XXH128_hash_t h128;
5517             h128.low64  = XXH3_mergeAccs(acc,
5518                                          secret + XXH_SECRET_MERGEACCS_START,
5519                                          (xxh_u64)state->totalLen * XXH_PRIME64_1);
5520             h128.high64 = XXH3_mergeAccs(acc,
5521                                          secret + state->secretLimit + XXH_STRIPE_LEN
5522                                                 - sizeof(acc) - XXH_SECRET_MERGEACCS_START,
5523                                          ~((xxh_u64)state->totalLen * XXH_PRIME64_2));
5524             return h128;
5525         }
5526     }
5527     /* len <= XXH3_MIDSIZE_MAX : short code */
5528     if (state->seed)
5529         return XXH3_128bits_withSeed(state->buffer, (size_t)state->totalLen, state->seed);
5530     return XXH3_128bits_withSecret(state->buffer, (size_t)(state->totalLen),
5531                                    secret, state->secretLimit + XXH_STRIPE_LEN);
5532 }
5533 
5534 /* 128-bit utility functions */
5535 
5536 #include <string.h>   /* memcmp, memcpy */
5537 
5538 /* return : 1 is equal, 0 if different */
5539 /*! @ingroup xxh3_family */
XXH128_isEqual(XXH128_hash_t h1,XXH128_hash_t h2)5540 XXH_PUBLIC_API int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2)
5541 {
5542     /* note : XXH128_hash_t is compact, it has no padding byte */
5543     return !(memcmp(&h1, &h2, sizeof(h1)));
5544 }
5545 
5546 /* This prototype is compatible with stdlib's qsort().
5547  * return : >0 if *h128_1  > *h128_2
5548  *          <0 if *h128_1  < *h128_2
5549  *          =0 if *h128_1 == *h128_2  */
5550 /*! @ingroup xxh3_family */
XXH128_cmp(const void * h128_1,const void * h128_2)5551 XXH_PUBLIC_API int XXH128_cmp(const void* h128_1, const void* h128_2)
5552 {
5553     XXH128_hash_t const h1 = *(const XXH128_hash_t*)h128_1;
5554     XXH128_hash_t const h2 = *(const XXH128_hash_t*)h128_2;
5555     int const hcmp = (h1.high64 > h2.high64) - (h2.high64 > h1.high64);
5556     /* note : bets that, in most cases, hash values are different */
5557     if (hcmp) return hcmp;
5558     return (h1.low64 > h2.low64) - (h2.low64 > h1.low64);
5559 }
5560 
5561 
5562 /*======   Canonical representation   ======*/
5563 /*! @ingroup xxh3_family */
5564 XXH_PUBLIC_API void
XXH128_canonicalFromHash(XXH128_canonical_t * dst,XXH128_hash_t hash)5565 XXH128_canonicalFromHash(XXH128_canonical_t* dst, XXH128_hash_t hash)
5566 {
5567     XXH_STATIC_ASSERT(sizeof(XXH128_canonical_t) == sizeof(XXH128_hash_t));
5568     if (XXH_CPU_LITTLE_ENDIAN) {
5569         hash.high64 = XXH_swap64(hash.high64);
5570         hash.low64  = XXH_swap64(hash.low64);
5571     }
5572     XXH_memcpy(dst, &hash.high64, sizeof(hash.high64));
5573     XXH_memcpy((char*)dst + sizeof(hash.high64), &hash.low64, sizeof(hash.low64));
5574 }
5575 
5576 /*! @ingroup xxh3_family */
5577 XXH_PUBLIC_API XXH128_hash_t
XXH128_hashFromCanonical(const XXH128_canonical_t * src)5578 XXH128_hashFromCanonical(const XXH128_canonical_t* src)
5579 {
5580     XXH128_hash_t h;
5581     h.high64 = XXH_readBE64(src);
5582     h.low64  = XXH_readBE64(src->digest + 8);
5583     return h;
5584 }
5585 
5586 
5587 
5588 /* ==========================================
5589  * Secret generators
5590  * ==========================================
5591  */
5592 #define XXH_MIN(x, y) (((x) > (y)) ? (y) : (x))
5593 
XXH3_combine16(void * dst,XXH128_hash_t h128)5594 static void XXH3_combine16(void* dst, XXH128_hash_t h128)
5595 {
5596     XXH_writeLE64( dst, XXH_readLE64(dst) ^ h128.low64 );
5597     XXH_writeLE64( (char*)dst+8, XXH_readLE64((char*)dst+8) ^ h128.high64 );
5598 }
5599 
5600 /*! @ingroup xxh3_family */
5601 XXH_PUBLIC_API XXH_errorcode
XXH3_generateSecret(void * secretBuffer,size_t secretSize,const void * customSeed,size_t customSeedSize)5602 XXH3_generateSecret(void* secretBuffer, size_t secretSize, const void* customSeed, size_t customSeedSize)
5603 {
5604     XXH_ASSERT(secretBuffer != NULL);
5605     if (secretBuffer == NULL) return XXH_ERROR;
5606     XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
5607     if (secretSize < XXH3_SECRET_SIZE_MIN) return XXH_ERROR;
5608     if (customSeedSize == 0) {
5609         customSeed = XXH3_kSecret;
5610         customSeedSize = XXH_SECRET_DEFAULT_SIZE;
5611     }
5612     XXH_ASSERT(customSeed != NULL);
5613     if (customSeed == NULL) return XXH_ERROR;
5614 
5615     /* Fill secretBuffer with a copy of customSeed - repeat as needed */
5616     {   size_t pos = 0;
5617         while (pos < secretSize) {
5618             size_t const toCopy = XXH_MIN((secretSize - pos), customSeedSize);
5619             memcpy((char*)secretBuffer + pos, customSeed, toCopy);
5620             pos += toCopy;
5621     }   }
5622 
5623     {   size_t const nbSeg16 = secretSize / 16;
5624         size_t n;
5625         XXH128_canonical_t scrambler;
5626         XXH128_canonicalFromHash(&scrambler, XXH128(customSeed, customSeedSize, 0));
5627         for (n=0; n<nbSeg16; n++) {
5628             XXH128_hash_t const h128 = XXH128(&scrambler, sizeof(scrambler), n);
5629             XXH3_combine16((char*)secretBuffer + n*16, h128);
5630         }
5631         /* last segment */
5632         XXH3_combine16((char*)secretBuffer + secretSize - 16, XXH128_hashFromCanonical(&scrambler));
5633     }
5634     return XXH_OK;
5635 }
5636 
5637 /*! @ingroup xxh3_family */
5638 XXH_PUBLIC_API void
XXH3_generateSecret_fromSeed(void * secretBuffer,XXH64_hash_t seed)5639 XXH3_generateSecret_fromSeed(void* secretBuffer, XXH64_hash_t seed)
5640 {
5641     XXH_ALIGN(XXH_SEC_ALIGN) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE];
5642     XXH3_initCustomSecret(secret, seed);
5643     XXH_ASSERT(secretBuffer != NULL);
5644     memcpy(secretBuffer, secret, XXH_SECRET_DEFAULT_SIZE);
5645 }
5646 
5647 
5648 
5649 /* Pop our optimization override from above */
5650 #if XXH_VECTOR == XXH_AVX2 /* AVX2 */ \
5651   && defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \
5652   && defined(__OPTIMIZE__) && !defined(__OPTIMIZE_SIZE__) /* respect -O0 and -Os */
5653 #  pragma GCC pop_options
5654 #endif
5655 
5656 #endif  /* XXH_NO_LONG_LONG */
5657 
5658 #endif  /* XXH_NO_XXH3 */
5659 
5660 /*!
5661  * @}
5662  */
5663 #endif  /* XXH_IMPLEMENTATION */
5664 
5665 
5666 #if defined (__cplusplus)
5667 }
5668 #endif
5669 
5670 #endif /* ! HAVE_XXHASH_H */
5671 
5672 #endif
5673