Merge pull request #3367 from DimitrisJim/length_hint_opt

vm.length_hint into vm.length_hint_opt
This commit is contained in:
Jeong YunWon
2021-10-24 23:36:49 +09:00
committed by GitHub
5 changed files with 8 additions and 12 deletions

View File

@@ -37,7 +37,7 @@ impl PyMap {
#[pymethod(magic)]
fn length_hint(&self, vm: &VirtualMachine) -> PyResult<usize> {
self.iterators.iter().try_fold(0, |prev, cur| {
let cur = vm.length_hint(cur.as_ref().to_owned())?.unwrap_or(0);
let cur = cur.as_ref().to_owned().length_hint(0, vm)?;
let max = std::cmp::max(prev, cur);
Ok(max)
})

View File

@@ -50,7 +50,7 @@ where
&'b self,
vm: &'a VirtualMachine,
) -> PyResult<PyIterIter<'a, U, &'b PyObject>> {
let length_hint = vm.length_hint(self.as_ref().to_owned())?;
let length_hint = vm.length_hint_opt(self.as_ref().to_owned())?;
Ok(PyIterIter::new(vm, self.0.borrow(), length_hint))
}
@@ -65,7 +65,7 @@ where
impl PyIter<PyObjectRef> {
/// Returns an iterator over this sequence of objects.
pub fn into_iter<U>(self, vm: &VirtualMachine) -> PyResult<PyIterIter<U, PyObjectRef>> {
let length_hint = vm.length_hint(self.as_object().to_owned())?;
let length_hint = vm.length_hint_opt(self.as_object().to_owned())?;
Ok(PyIterIter::new(vm, self.0, length_hint))
}
}

View File

@@ -73,12 +73,8 @@ impl PyObjectRef {
self.is_true(vm).map(|x| !x)
}
pub fn length_hint(
self,
defaultvalue: Option<usize>,
vm: &VirtualMachine,
) -> PyResult<Option<usize>> {
Ok(vm.length_hint(self)?.or(defaultvalue))
pub fn length_hint(self, defaultvalue: usize, vm: &VirtualMachine) -> PyResult<usize> {
Ok(vm.length_hint_opt(self)?.unwrap_or(defaultvalue))
}
// item protocol

View File

@@ -282,7 +282,7 @@ mod _operator {
v.payload::<PyInt>().unwrap().try_to_primitive(vm)
})
.unwrap_or(Ok(0))?;
vm.length_hint(obj).map(|v| v.unwrap_or(default))
obj.length_hint(default, vm)
}
// Inplace Operators

View File

@@ -1201,7 +1201,7 @@ impl VirtualMachine {
F: FnMut(PyObjectRef) -> PyResult<R>,
{
let iter = value.to_owned().get_iter(self)?;
let cap = match self.length_hint(value.to_owned()) {
let cap = match self.length_hint_opt(value.to_owned()) {
Err(e) if e.class().is(&self.ctx.exceptions.runtime_error) => return Err(e),
Ok(Some(value)) => Some(value),
// Use a power of 2 as a default capacity.
@@ -1681,7 +1681,7 @@ impl VirtualMachine {
})
}
pub fn length_hint(&self, iter: PyObjectRef) -> PyResult<Option<usize>> {
pub fn length_hint_opt(&self, iter: PyObjectRef) -> PyResult<Option<usize>> {
if let Some(len) = self.obj_len_opt(&iter) {
match len {
Ok(len) => return Ok(Some(len)),