Merge pull request #357 from chr1sj0nes/master

Add `PyList.sort()`.
This commit is contained in:
Yuji Kanagawa 2019-02-17 09:20:01 +09:00 committed by GitHub
commit 9ceb453822
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -111,6 +111,11 @@ impl PyList {
index: 0,
}
}
/// Sorts the list in-place. Equivalent to python `l.sort()`
pub fn sort(&self) -> PyResult<()> {
unsafe { err::error_on_minusone(self.py(), ffi::PyList_Sort(self.as_ptr())) }
}
}
/// Used by `PyList::iter()`.
@ -372,4 +377,21 @@ mod test {
let v2 = list.as_ref().extract::<Vec<i32>>().unwrap();
assert_eq!(v, v2);
}
#[test]
fn test_sort() {
let gil = Python::acquire_gil();
let py = gil.python();
let v = vec![7, 3, 2, 5];
let list = PyList::new(py, &v);
assert_eq!(7, list.get_item(0).extract::<i32>().unwrap());
assert_eq!(3, list.get_item(1).extract::<i32>().unwrap());
assert_eq!(2, list.get_item(2).extract::<i32>().unwrap());
assert_eq!(5, list.get_item(3).extract::<i32>().unwrap());
list.sort().unwrap();
assert_eq!(2, list.get_item(0).extract::<i32>().unwrap());
assert_eq!(3, list.get_item(1).extract::<i32>().unwrap());
assert_eq!(5, list.get_item(2).extract::<i32>().unwrap());
assert_eq!(7, list.get_item(3).extract::<i32>().unwrap());
}
}