MCPcopy Create free account
hub / github.com/dgrunwald/rust-cpython / compare

Method compare

src/objectprotocol.rs:100–146  ·  view source on GitHub ↗

Compares two Python objects. On Python 2, this is equivalent to the Python expression 'cmp(self, other)'. On Python 3, this is equivalent to: ```ignore if self == other: return Equal elif a < b: return Less elif a > b: return Greater else: raise TypeError("ObjectProtocol::compare(): All comparisons returned false") ```

(&self, py: Python, other: O)

Source from the content-addressed store, hash-verified

98 /// raise TypeError("ObjectProtocol::compare(): All comparisons returned false")
99 /// ```
100 fn compare<O>(&self, py: Python, other: O) -> PyResult<Ordering>
101 where
102 O: ToPyObject,
103 {
104 #[cfg(feature = "python27-sys")]
105 unsafe fn do_compare(
106 py: Python,
107 a: *mut ffi::PyObject,
108 b: *mut ffi::PyObject,
109 ) -> PyResult<Ordering> {
110 let mut result = -1;
111 err::error_on_minusone(py, ffi::PyObject_Cmp(a, b, &mut result))?;
112 Ok(result.cmp(&0))
113 }
114
115 #[cfg(feature = "python3-sys")]
116 unsafe fn do_compare(
117 py: Python,
118 a: *mut ffi::PyObject,
119 b: *mut ffi::PyObject,
120 ) -> PyResult<Ordering> {
121 let result = ffi::PyObject_RichCompareBool(a, b, ffi::Py_EQ);
122 if result == 1 {
123 return Ok(Ordering::Equal);
124 } else if result < 0 {
125 return Err(PyErr::fetch(py));
126 }
127 let result = ffi::PyObject_RichCompareBool(a, b, ffi::Py_LT);
128 if result == 1 {
129 return Ok(Ordering::Less);
130 } else if result < 0 {
131 return Err(PyErr::fetch(py));
132 }
133 let result = ffi::PyObject_RichCompareBool(a, b, ffi::Py_GT);
134 if result == 1 {
135 return Ok(Ordering::Greater);
136 } else if result < 0 {
137 return Err(PyErr::fetch(py));
138 }
139 Err(PyErr::new::<crate::exc::TypeError, _>(
140 py,
141 "ObjectProtocol::compare(): All comparisons returned false",
142 ))
143 }
144
145 other.with_borrowed_ptr(py, |other| unsafe { do_compare(py, self.as_ptr(), other) })
146 }
147
148 /// Compares two Python objects.
149 ///

Callers

nothing calls this directly

Implementers 1

objectprotocol.rssrc/objectprotocol.rs

Calls 2

with_borrowed_ptrMethod · 0.45
as_ptrMethod · 0.45

Tested by

no test coverage detected