diff --git a/rtc-stun/src/error_code.rs b/rtc-stun/src/error_code.rs index 21ba7269..947c8083 100644 --- a/rtc-stun/src/error_code.rs +++ b/rtc-stun/src/error_code.rs @@ -1,3 +1,6 @@ +#[cfg(test)] +mod error_code_test; + use crate::attributes::*; use crate::checks::*; use crate::message::*; @@ -17,12 +20,7 @@ pub struct ErrorCodeAttribute { impl fmt::Display for ErrorCodeAttribute { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let reason = match String::from_utf8(self.reason.clone()) { - Ok(reason) => reason, - Err(_) => return Err(fmt::Error {}), - }; - - write!(f, "{}: {}", self.code.0, reason) + write!(f, "{}: {}", self.code.0, String::from_utf8_lossy(&self.reason)) } } diff --git a/rtc-stun/src/error_code/error_code_test.rs b/rtc-stun/src/error_code/error_code_test.rs new file mode 100644 index 00000000..4053b0f8 --- /dev/null +++ b/rtc-stun/src/error_code/error_code_test.rs @@ -0,0 +1,21 @@ +use super::*; + +#[test] +fn test_display_valid_utf8() { + let code = ErrorCodeAttribute { + code: ErrorCode(401), + reason: b"Unauthorized".to_vec(), + }; + assert_eq!(format!("{}", code), "401: Unauthorized"); +} + +#[test] +fn test_display_invalid_utf8_does_not_panic() { + let code = ErrorCodeAttribute { + code: ErrorCode(401), + reason: vec![0xc0, 0xaf], + }; + let result = format!("{}", code); + assert!(result.starts_with("401: ")); + assert!(result.contains('\u{FFFD}')); +}