Skip to content

Commit ee5c6eb

Browse files
authored
fix(turbopack): Fix a panic when the generated hash is too short when radix formatting a string. (#80966)
## Fix hash length check in metadata formatting ### What? Fixed a panic in the `format_radix` function when the generated hash is shorter than 6 characters. ### Why? The current implementation always tries to take the first 6 characters of the hash using a fixed slice `result[..6]`, which would panic if the hash is shorter than 6 characters. This doesn't match the JavaScript behavior where `toString(36).slice(0, 6)` automatically takes the minimum of the hash length and 6. ### How? Added a check to determine the minimum length between the hash length and 6, then use that value for slicing: ```rust let len = result.len().min(6); result[..len].iter().collect() ``` Fixes #PACK-4495
1 parent 3bad7cc commit ee5c6eb

File tree

1 file changed

+13
-2
lines changed
  • crates/next-core/src/next_app/metadata

1 file changed

+13
-2
lines changed

crates/next-core/src/next_app/metadata/mod.rs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,12 @@ fn format_radix(mut x: u32, radix: u32) -> String {
276276
}
277277

278278
result.reverse();
279-
result[..6].iter().collect()
279+
280+
// We only need the first 6 characters of the hash but sometimes the hash is too short.
281+
// In JavaScript, we use `toString(36).slice(0, 6)` to get the first 6 characters of the hash,
282+
// but it will automatically take the minimum of the length of the hash and 6. Rust will panic.
283+
let len = result.len().min(6);
284+
result[..len].iter().collect()
280285
}
281286

282287
/// If there's special convention like (...) or @ in the page path,
@@ -360,7 +365,7 @@ pub fn normalize_metadata_route(mut page: AppPage) -> Result<AppPage> {
360365

361366
#[cfg(test)]
362367
mod test {
363-
use super::normalize_metadata_route;
368+
use super::{djb2_hash, format_radix, normalize_metadata_route};
364369
use crate::next_app::AppPage;
365370

366371
#[test]
@@ -385,4 +390,10 @@ mod test {
385390
assert_eq!(&normalized.to_string(), expected);
386391
}
387392
}
393+
394+
#[test]
395+
fn test_format_radix_doesnt_panic_with_result_less_than_6_characters() {
396+
let hash = format_radix(djb2_hash("/lookup/[domain]/(dns)"), 36);
397+
assert!(hash.len() < 6);
398+
}
388399
}

0 commit comments

Comments
 (0)