CStr: derive PartialEq, Eq; add test for Ord · model-checking/verify-rust-std@b889a1d (original) (raw)

4 files changed

lines changed

Original file line number Diff line number Diff line change
@@ -94,7 +94,7 @@ use crate::str;
94 94 /// ```
95 95 ///
96 96 /// [str]: prim@str "str"
97 -#[derive(Hash)]
97 +#[derive(PartialEq, Eq, Hash)]
98 98 #[stable(feature = "core_c_str", since = "1.64.0")]
99 99 #[rustc_has_incoherent_inherent_impls]
100 100 #[lang = "CStr"]
@@ -104,7 +104,6 @@ use crate::str;
104 104 // want `repr(transparent)` but we don't want it to show up in rustdoc, so we hide it under
105 105 // `cfg(doc)`. This is an ad-hoc implementation of attribute privacy.
106 106 #[repr(transparent)]
107 -#[allow(clippy::derived_hash_with_manual_eq)]
108 107 pub struct CStr {
109 108 // FIXME: this should not be represented with a DST slice but rather with
110 109 // just a raw `c_char` along with some form of marker to make
@@ -678,15 +677,9 @@ impl CStr {
678 677 }
679 678 }
680 679
681 -#[stable(feature = "rust1", since = "1.0.0")]
682 -impl PartialEq for CStr {
683 -#[inline]
684 -fn eq(&self, other: &CStr) -> bool {
685 -self.to_bytes().eq(other.to_bytes())
686 -}
687 -}
688 -#[stable(feature = "rust1", since = "1.0.0")]
689 -impl Eq for CStr {}
680 +// `.to_bytes()` representations are compared instead of the inner `[c_char]`s,
681 +// because `c_char` is `i8` (not `u8`) on some platforms.
682 +// That is why this is implemented manually and not derived.
690 683 #[stable(feature = "rust1", since = "1.0.0")]
691 684 impl PartialOrd for CStr {
692 685 #[inline]
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1 +mod cstr;
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
1 +use core::ffi::CStr;
2 +
3 +#[test]
4 +fn compares_as_u8s() {
5 +let a: &CStr = c"Hello!"; // Starts with ascii
6 +let a_bytes: &[u8] = a.to_bytes();
7 +assert!((..0b1000_0000).contains(&a_bytes[0]));
8 +
9 +let b: &CStr = c"こんにちは!"; // Starts with non ascii
10 +let b_bytes: &[u8] = b.to_bytes();
11 +assert!((0b1000_0000..).contains(&b_bytes[0]));
12 +
13 +assert_eq!(Ord::cmp(a, b), Ord::cmp(a_bytes, b_bytes));
14 +assert_eq!(PartialOrd::partial_cmp(a, b), PartialOrd::partial_cmp(a_bytes, b_bytes));
15 +}
Original file line number Diff line number Diff line change
@@ -132,6 +132,7 @@ mod clone;
132 132 mod cmp;
133 133 mod const_ptr;
134 134 mod convert;
135 +mod ffi;
135 136 mod fmt;
136 137 mod future;
137 138 mod hash;