Awesome
xxhash.nim
xxhash wrapper for Nim
This is a wrapper for the xxhash
hashing library in Nim, which provides fast, non-cryptographic hashing for various use cases such as file integrity checks, data storage, and more.
Features
- Supports
XXH32
,XXH64
, andXXH128
hashing algorithms. - Designed to work seamlessly with the Nim language.
- Efficient and fast hashing suitable for performance-sensitive applications.
Installation
To use xxhash.nim
, install the library using Nimble:
nimble install xxhash
Alternatively, you can clone the repository from the official source and add it to your project manually.
Basic Usage
Below is a simple example of how to use the xxhash
library in a Nim project.
Importing the Module
import xxhash
Hashing a String
To compute a 32-bit hash of a string using XXH32
:
let hash32 = XXH32("Hello, world!")
echo hash32
To compute a 64-bit hash using XXH64
:
let hash64 = XXH64("Hello, world!")
echo hash64
For larger data or more security, use XXH128
:
let hash128 = XXH3_128bits("Hello, world!")
echo hash128
Hashing a File
To hash a file, you can use:
import os
let fileContent = readFile("path/to/file")
let fileHash = XXH64(fileContent)
echo fileHash
Streaming Hash Computation
For large files or streams, the xxhash library provides stateful hashing that allows hashing in chunks. Here's an example using XXH64
:
var state = newXxh64()
# Process in chunks
state.update("Hello, ")
state.update("world!")
let finalHash = state.digest()
echo finalHash
# Important: Free the state after use in Nim 1.x.x
state.free()
Note for Nim version 1.x.x
In Nim versions older than 2.0.0, you should manually call state.free()
to deallocate resources because Nim does not automatically call destructors (=destroy
). This step is crucial to avoid memory leaks when using the stateful API.
Performance Considerations
xxhash
is designed to be very fast and is optimized for bulk data processing.XXH128
is slightly slower but provides more robust hashing for larger datasets.
Additional Information
This wrapper supports both 32-bit and 64-bit systems, ensuring compatibility across various platforms.
Credits
- This module utilizes @rockcavera's
nint128
for XXH128 computation.
License
This project is distributed under the MIT License.
This README was generated by ChatGPT.