Skip to main content

turbo_tasks_hash/
lib.rs

1//! Hashing and encoding functions for turbopack.
2//!
3//! An example use of this module is hashing a file's content for cache
4//! invalidation, and encoding the hash to an hexadecimal string for use in a
5//! file name.
6
7mod deterministic_hash;
8mod hex;
9mod sha;
10mod xxh3_hash64;
11
12use bincode::{Decode, Encode};
13
14#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Decode, Encode)]
15pub enum HashAlgorithm {
16    /// The default hash algorithm, use this when the exact hashing algorithm doesn't matter.
17    #[default]
18    Xxh3Hash64Hex,
19    /// Used for https://nextjs.org/docs/app/guides/content-security-policy#enabling-sri
20    Sha256Base64,
21    /// Used for https://nextjs.org/docs/app/guides/content-security-policy#enabling-sri
22    Sha384Base64,
23    /// Used for https://nextjs.org/docs/app/guides/content-security-policy#enabling-sri
24    Sha512Base64,
25}
26
27pub fn deterministic_hash<T: DeterministicHash>(input: T, algorithm: HashAlgorithm) -> String {
28    match algorithm {
29        HashAlgorithm::Xxh3Hash64Hex => {
30            let mut hasher = Xxh3Hash64Hasher::new();
31            input.deterministic_hash(&mut hasher);
32            encode_hex(hasher.finish())
33        }
34        HashAlgorithm::Sha256Base64 => {
35            let mut hasher = ShaHasher::new_sha256();
36            input.deterministic_hash(&mut hasher);
37            hasher.finish_base64()
38        }
39        HashAlgorithm::Sha384Base64 => {
40            let mut hasher = ShaHasher::new_sha384();
41            input.deterministic_hash(&mut hasher);
42            hasher.finish_base64()
43        }
44        HashAlgorithm::Sha512Base64 => {
45            let mut hasher = ShaHasher::new_sha512();
46            input.deterministic_hash(&mut hasher);
47            hasher.finish_base64()
48        }
49    }
50}
51
52pub use crate::{
53    deterministic_hash::{DeterministicHash, DeterministicHasher},
54    hex::encode_hex,
55    sha::ShaHasher,
56    xxh3_hash64::{Xxh3Hash64Hasher, hash_xxh3_hash64},
57};