ACP: Allow comparisons between CString and CStr. · Issue #517 · rust-lang/libs-team (original) (raw)

Proposal

Problem statement

alloc::ffi::CString is very similar to alloc:🧵:String, and the same goes for core::ffi::CStr when compared to str. But the FFI types do differ a bit with regard to the relationship between the owned and borrowed types.

Currently, str, String, and alloc::borrow::Cow<'a, str> all implement PartialEq in the following variants:

CString and CStr, on the other hand, only implement the default PartialEq<Self>.

Motivating examples or use cases

Comparing a CString with a CStr currently requires converting either of the objects to the other's type:

let s0: CString = todo!(); let s1: &CStr = todo!();

assert_eq!(s0, s1.to_owned()); assert_eq!(s0.as_ref(), s1); // Etc.

Implementing this proposal would eliminate the need for the ToOwned::to_owned or AsRef::as_ref call, as well as increase the overall parity with String / str.

Solution sketch

Add the following implementations to the standard library:

// core::ffi

impl PartialEq<&Self> for CStr;

impl PartialEq for CStr;

impl PartialEq<Cow<'_, Self>> for CStr;

// alloc::ffi

impl PartialEq for CString;

impl PartialEq<&CStr> for CString;

impl PartialEq<Cow<'_, Self>> for CString;

// alloc::borrow

impl PartialEq for Cow<'_, CStr>;

impl<'a, 'b> PartialEq<&'b CStr> for Cow<'a, CStr>;

impl PartialEq for Cow<'_, CStr>;