Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

rust: str: add `CStr` unit tests

Add unit tests for `CStr::from_bytes_with_nul()` and
`CStr::from_bytes_with_nul_unchecked()`.

These serve as an example of the first unit tests for Rust code
(i.e. different from documentation tests).

Signed-off-by: Milan Landaverde <milan@mdaverde.com>
[Reworded, adapted for upstream and applied latest changes]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>

authored by

Milan Landaverde and committed by
Miguel Ojeda
985f1f09 c07e67bd

+29
+29
rust/kernel/str.rs
··· 321 321 } 322 322 } 323 323 324 + #[cfg(test)] 325 + mod tests { 326 + use super::*; 327 + 328 + #[test] 329 + fn test_cstr_to_str() { 330 + let good_bytes = b"\xf0\x9f\xa6\x80\0"; 331 + let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap(); 332 + let checked_str = checked_cstr.to_str().unwrap(); 333 + assert_eq!(checked_str, "🦀"); 334 + } 335 + 336 + #[test] 337 + #[should_panic] 338 + fn test_cstr_to_str_panic() { 339 + let bad_bytes = b"\xc3\x28\0"; 340 + let checked_cstr = CStr::from_bytes_with_nul(bad_bytes).unwrap(); 341 + checked_cstr.to_str().unwrap(); 342 + } 343 + 344 + #[test] 345 + fn test_cstr_as_str_unchecked() { 346 + let good_bytes = b"\xf0\x9f\x90\xA7\0"; 347 + let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap(); 348 + let unchecked_str = unsafe { checked_cstr.as_str_unchecked() }; 349 + assert_eq!(unchecked_str, "🐧"); 350 + } 351 + } 352 + 324 353 /// Allows formatting of [`fmt::Arguments`] into a raw buffer. 325 354 /// 326 355 /// It does not fail if callers write past the end of the buffer so that they can calculate the