Unverified Commit ee5c6eb7 authored by Joshua Hannaford's avatar Joshua Hannaford Committed by GitHub

fix(turbopack): Fix a panic when the generated hash is too short when radix…

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
parent 3bad7cc7
...@@ -276,7 +276,12 @@ fn format_radix(mut x: u32, radix: u32) -> String { ...@@ -276,7 +276,12 @@ fn format_radix(mut x: u32, radix: u32) -> String {
} }
result.reverse(); result.reverse();
result[..6].iter().collect()
// We only need the first 6 characters of the hash but sometimes the hash is too short.
// In JavaScript, we use `toString(36).slice(0, 6)` to get the first 6 characters of the hash,
// but it will automatically take the minimum of the length of the hash and 6. Rust will panic.
let len = result.len().min(6);
result[..len].iter().collect()
} }
/// If there's special convention like (...) or @ in the page path, /// 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> { ...@@ -360,7 +365,7 @@ pub fn normalize_metadata_route(mut page: AppPage) -> Result<AppPage> {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::normalize_metadata_route; use super::{djb2_hash, format_radix, normalize_metadata_route};
use crate::next_app::AppPage; use crate::next_app::AppPage;
#[test] #[test]
...@@ -385,4 +390,10 @@ mod test { ...@@ -385,4 +390,10 @@ mod test {
assert_eq!(&normalized.to_string(), expected); assert_eq!(&normalized.to_string(), expected);
} }
} }
#[test]
fn test_format_radix_doesnt_panic_with_result_less_than_6_characters() {
let hash = format_radix(djb2_hash("/lookup/[domain]/(dns)"), 36);
assert!(hash.len() < 6);
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment