| 1 |
//! RFC 9839 functions. |
| 2 |
|
| 3 |
/// Determines if a character is problematic according to RFC9839. |
| 4 |
fn is_problematic(c: char) -> bool { |
| 5 |
let cp = c as u32; |
| 6 |
|
| 7 |
// 1. Surrogates: U+D800 to U+DFFF |
| 8 |
// (Note: Rust's 'char' type technically shouldn't contain these, |
| 9 |
// but they can appear in unchecked byte sequences or UTF-16) |
| 10 |
if (0xD800..=0xDFFF).contains(&cp) { |
| 11 |
return true; |
| 12 |
} |
| 13 |
|
| 14 |
// 2. Noncharacters: U+FDD0..U+FDEF and those ending in FFFE/FFFF |
| 15 |
if (0xFDD0..=0xFDEF).contains(&cp) || (cp & 0xFFFE) == 0xFFFE { |
| 16 |
return true; |
| 17 |
} |
| 18 |
|
| 19 |
// 3. Control Characters: C0 (00-1F, 7F) and C1 (80-9F) |
| 20 |
// Excludes JSON whitespace: tab (0x09), LF (0x0A), CR (0x0D) per RFC 8259 |
| 21 |
if cp == 0x7F || (0x80..=0x9F).contains(&cp) { |
| 22 |
return true; |
| 23 |
} |
| 24 |
if (0x00..=0x1F).contains(&cp) && cp != 0x09 && cp != 0x0A && cp != 0x0D { |
| 25 |
return true; |
| 26 |
} |
| 27 |
|
| 28 |
false |
| 29 |
} |
| 30 |
|
| 31 |
/// Sanitizes problematic code points. |
| 32 |
pub fn sanitize_rfc9839(input: &str) -> String { |
| 33 |
input |
| 34 |
.chars() |
| 35 |
.map(|c| { |
| 36 |
if is_problematic(c) { |
| 37 |
'\u{FFFD}' // Unicode Replacement Character |
| 38 |
} else { |
| 39 |
c |
| 40 |
} |
| 41 |
}) |
| 42 |
.collect() |
| 43 |
} |