From 4f1bbe9b11040fbcc4d091d2a44165831f27d4dc Mon Sep 17 00:00:00 2001 From: Yota Toyama Date: Mon, 7 Apr 2025 19:03:09 -0700 Subject: [PATCH] Implement equality with `CStr` --- src/c_string.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/c_string.rs b/src/c_string.rs index 7c737032..f766421b 100644 --- a/src/c_string.rs +++ b/src/c_string.rs @@ -298,6 +298,30 @@ impl PartialEq> for CString { } } +impl PartialEq for CString { + fn eq(&self, rhs: &CStr) -> bool { + self.as_c_str() == rhs + } +} + +impl PartialEq<&CStr> for CString { + fn eq(&self, rhs: &&CStr) -> bool { + self.as_c_str() == *rhs + } +} + +impl PartialEq> for CStr { + fn eq(&self, rhs: &CString) -> bool { + self == rhs.as_c_str() + } +} + +impl PartialEq> for &CStr { + fn eq(&self, rhs: &CString) -> bool { + *self == rhs.as_c_str() + } +} + impl Eq for CString {} /// An error to extend [`CString`] with bytes. @@ -474,4 +498,19 @@ mod tests { != CString::<4>::from_bytes_with_nul(b"abc\0").unwrap() ); } + + #[test] + fn equal_with_c_str() { + // Empty strings + assert!(CString::<1>::new() == c""); + assert!(c"" == CString::<1>::new()); + + // Single character + assert!(CString::<2>::from_bytes_with_nul(b"a\0").unwrap() == c"a"); + assert!(c"a" == CString::<2>::from_bytes_with_nul(b"a\0").unwrap()); + + // Multiple characters + assert!(CString::<4>::from_bytes_with_nul(b"abc\0").unwrap() == c"abc"); + assert!(c"abc" == CString::<4>::from_bytes_with_nul(b"abc\0").unwrap()); + } }