Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Checksum

Even though this is not strictly necessary in order to decode compressed Zstandard files, it is advised to implement checksum verification. Remember, you have already read the checksum value if it is present.

You can compute the checksum as you decode data by adding an appropriate hasher to the decoding context and feeding it every byte you decode; or, since your decoder currently keeps the whole decoded frame in memory, simply hash the decoded data once the last block has been decoded. The XxHash64 type of the twox_hash crate implements the right algorithm. You can truncate the final result to 32 bit, and compare it to the value found in the compressed Zstandard file: if they match, the data is likely not corrupt.

XxHash64 implements the standard std::hash::Hasher trait, so the only methods you need are write() to feed it bytes and finish() to get the 64 bit digest:

use std::hash::Hasher;
use twox_hash::XxHash64;

let mut hasher = XxHash64::default();   // seed 0, as mandated by the RFC
hasher.write(&decoded_bytes);           // call as many times as needed
let checksum = hasher.finish() as u32;  // keep the lowest 32 bits

✅ Implement the checksum verification.