diff --git a/Cargo.toml b/Cargo.toml index 53886778bab..9250f1e33bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -338,10 +338,11 @@ inefficient_to_string = "warn" redundant_clone = "warn" debug_assert_with_mut_call = "warn" unused_peekable = "warn" -manual_is_variant_and = "warn" or_fun_call = "warn" unnested_or_patterns = "warn" # pedantic lints to enforce gradually cloned_instead_of_copied = "warn" +manual_is_variant_and = "warn" +map_unwrap_or = "warn" must_use_candidate = "warn" diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index 3f53fe10e15..61473687366 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -5412,6 +5412,7 @@ impl Compiler { self.prepare_decorators(decorator_list)?; let is_generic = type_params.is_some(); + #[expect(clippy::map_unwrap_or, reason = "Changing this will not compile")] let firstlineno = decorator_list .first() .map(|decorator| { @@ -6882,19 +6883,13 @@ impl Compiler { return Err(self.error(CodegenErrorType::MultipleStarArgs)); } // star wildcard check - star_wildcard = pattern - .as_match_star() - .map(|m| m.name.is_none()) - .unwrap_or(false); + star_wildcard = pattern.as_match_star().is_some_and(|m| m.name.is_none()); only_wildcard &= star_wildcard; star = Some(i); continue; } // wildcard check - only_wildcard &= pattern - .as_match_as() - .map(|m| m.name.is_none()) - .unwrap_or(false); + only_wildcard &= pattern.as_match_as().is_some_and(|m| m.name.is_none()); } // Keep the subject on top during the sequence and length checks. diff --git a/crates/codegen/src/ir.rs b/crates/codegen/src/ir.rs index 17764a99206..8d77b4688b9 100644 --- a/crates/codegen/src/ir.rs +++ b/crates/codegen/src/ir.rs @@ -8907,8 +8907,7 @@ impl CodeInfo { if let DeoptKind::ReturnIter { tail_start_idx } = deopt_kind { let tail_instr_idx = real_instrs .get(tail_start_idx) - .map(|(instr_idx, _)| *instr_idx) - .unwrap_or(block_instr_len); + .map_or(block_instr_len, |(instr_idx, _)| *instr_idx); if !tail_returns_without_store( &self.blocks, &is_pre_handler, @@ -9472,8 +9471,7 @@ impl CodeInfo { block.disable_load_fast_borrow, block .start_depth - .map(|depth| depth.to_string()) - .unwrap_or_else(|| String::from("None")), + .map_or_else(|| String::from("None"), |depth| depth.to_string()), ); for info in &block.instructions { let lineno = instruction_lineno(info); @@ -10169,8 +10167,7 @@ fn mark_cold(blocks: &mut [Block]) { let has_fallthrough = block .instructions .last() - .map(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()) - .unwrap_or(true); + .is_none_or(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()); if has_fallthrough && block.next != BlockIdx::NULL { let next_idx = block.next.idx(); if !blocks[next_idx].except_handler && !warm[next_idx] { @@ -10209,11 +10206,9 @@ fn push_cold_blocks_to_end(blocks: &mut Vec) { block.cold && block.next != BlockIdx::NULL && !blocks[block.next.idx()].cold - && block - .instructions - .last() - .map(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()) - .unwrap_or(true) + && block.instructions.last().is_none_or(|ins| { + !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump() + }) }) .map(|(idx, block)| (idx, block.next)) .collect(); @@ -13343,8 +13338,7 @@ fn duplicate_end_returns(blocks: &mut Vec, metadata: &CodeUnitMetadata) { if current != last_block && !block.cold { let last_ins = block.instructions.last(); let has_fallthrough = last_ins - .map(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()) - .unwrap_or(true); + .is_none_or(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()); // Don't duplicate if block already ends with the same return pattern let already_has_return = block.instructions.len() >= 2 && { let n = block.instructions.len(); @@ -13518,8 +13512,7 @@ fn duplicate_named_except_cleanup_returns(blocks: &mut Vec, metadata: &Co let fallthroughs_into_target = blocks[layout_pred.idx()] .instructions .last() - .map(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()) - .unwrap_or(true); + .is_none_or(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()); if !fallthroughs_into_target || predecessors[target.idx()] < 2 { continue; } @@ -13765,8 +13758,7 @@ pub(crate) fn label_exception_targets(blocks: &mut [Block]) { let has_fallthrough = blocks[bi] .instructions .last() - .map(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()) - .unwrap_or(true); // Empty block falls through + .is_none_or(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()); // Empty block falls through if has_fallthrough { visited[next.idx()] = true; block_stacks[next.idx()] = Some(stack); diff --git a/crates/codegen/src/symboltable.rs b/crates/codegen/src/symboltable.rs index 448e22d256e..31da7c164e8 100644 --- a/crates/codegen/src/symboltable.rs +++ b/crates/codegen/src/symboltable.rs @@ -1085,17 +1085,13 @@ impl SymbolTableBuilder { } fn enter_scope(&mut self, name: &str, typ: CompilerScope, line_number: u32) { - let is_nested = self - .tables - .last() - .map(|table| { - table.is_nested - || matches!( - table.typ, - CompilerScope::Function | CompilerScope::AsyncFunction - ) - }) - .unwrap_or(false); + let is_nested = self.tables.last().is_some_and(|table| { + table.is_nested + || matches!( + table.typ, + CompilerScope::Function | CompilerScope::AsyncFunction + ) + }); // Inherit mangled_names from parent for non-class scopes let inherited_mangled_names = self .tables diff --git a/crates/common/src/cformat.rs b/crates/common/src/cformat.rs index 3b7ac5d76ec..cea23d1cb54 100644 --- a/crates/common/src/cformat.rs +++ b/crates/common/src/cformat.rs @@ -620,7 +620,7 @@ where let (index, c) = iter.next().ok_or_else(|| { ( CFormatErrorType::IncompleteFormat, - iter.peek().map(|x| x.0).unwrap_or(0), + iter.peek().map_or(0, |x| x.0), ) })?; let format_type = match c.to_char_lossy() { diff --git a/crates/derive-impl/src/pyclass.rs b/crates/derive-impl/src/pyclass.rs index aa87b193932..625bbd0baf9 100644 --- a/crates/derive-impl/src/pyclass.rs +++ b/crates/derive-impl/src/pyclass.rs @@ -331,8 +331,7 @@ fn validate_base_field(item: &Item, base_path: &syn::Path) -> Result { diff --git a/crates/jit/tests/common.rs b/crates/jit/tests/common.rs index 6066ebc4307..ca761477f3c 100644 --- a/crates/jit/tests/common.rs +++ b/crates/jit/tests/common.rs @@ -116,10 +116,12 @@ fn extract_annotations_from_annotate_code(code: &CodeObject) -> HashMap value - .as_str() - .map(|s| s.to_owned()) - .unwrap_or_else(|_| value.to_string_lossy().into_owned()), + Some(ConstantData::Str { value }) => { + value.as_str().map_or_else( + |_| value.to_string_lossy().into_owned(), + |s| s.to_owned(), + ) + } Some(other) => panic!( "Unsupported annotation const for '{:?}' at idx {}: {:?}", param_name, val_idx, other diff --git a/crates/sre_engine/src/string.rs b/crates/sre_engine/src/string.rs index 9639be117a7..83b80ad81f9 100644 --- a/crates/sre_engine/src/string.rs +++ b/crates/sre_engine/src/string.rs @@ -339,29 +339,20 @@ const fn is_py_ascii_whitespace(b: u8) -> bool { #[inline] pub(crate) fn is_word(ch: u32) -> bool { - ch == '_' as u32 - || u8::try_from(ch) - .map(|x| x.is_ascii_alphanumeric()) - .unwrap_or(false) + ch == '_' as u32 || u8::try_from(ch).is_ok_and(|x| x.is_ascii_alphanumeric()) } #[inline] pub(crate) fn is_space(ch: u32) -> bool { - u8::try_from(ch) - .map(is_py_ascii_whitespace) - .unwrap_or(false) + u8::try_from(ch).is_ok_and(is_py_ascii_whitespace) } #[inline] pub(crate) fn is_digit(ch: u32) -> bool { - u8::try_from(ch) - .map(|x| x.is_ascii_digit()) - .unwrap_or(false) + u8::try_from(ch).is_ok_and(|x| x.is_ascii_digit()) } #[inline] pub(crate) fn is_loc_alnum(ch: u32) -> bool { // FIXME: Ignore the locales - u8::try_from(ch) - .map(|x| x.is_ascii_alphanumeric()) - .unwrap_or(false) + u8::try_from(ch).is_ok_and(|x| x.is_ascii_alphanumeric()) } #[inline] pub(crate) fn is_loc_word(ch: u32) -> bool { @@ -374,9 +365,7 @@ pub(crate) const fn is_linebreak(ch: u32) -> bool { #[inline] #[must_use] pub fn lower_ascii(ch: u32) -> u32 { - u8::try_from(ch) - .map(|x| x.to_ascii_lowercase() as u32) - .unwrap_or(ch) + u8::try_from(ch).map_or(ch, |x| x.to_ascii_lowercase() as u32) } #[inline] pub(crate) fn lower_locate(ch: u32) -> u32 { @@ -386,16 +375,12 @@ pub(crate) fn lower_locate(ch: u32) -> u32 { #[inline] pub(crate) fn upper_locate(ch: u32) -> u32 { // FIXME: Ignore the locales - u8::try_from(ch) - .map(|x| x.to_ascii_uppercase() as u32) - .unwrap_or(ch) + u8::try_from(ch).map_or(ch, |x| x.to_ascii_uppercase() as u32) } #[inline] pub(crate) fn is_uni_digit(ch: u32) -> bool { // TODO: check with cpython - char::try_from(ch) - .map(|x| x.is_ascii_digit()) - .unwrap_or(false) + char::try_from(ch).is_ok_and(|x| x.is_ascii_digit()) } #[inline] pub(crate) fn is_uni_space(ch: u32) -> bool { @@ -444,13 +429,11 @@ pub(crate) const fn is_uni_linebreak(ch: u32) -> bool { #[inline] pub(crate) fn is_uni_alnum(ch: u32) -> bool { // TODO: check with cpython - char::try_from(ch) - .map(|c| { - GeneralCategoryGroup::Letter - .union(GeneralCategoryGroup::Number) - .contains(GeneralCategory::for_char(c)) - }) - .unwrap_or(false) + char::try_from(ch).is_ok_and(|c| { + GeneralCategoryGroup::Letter + .union(GeneralCategoryGroup::Number) + .contains(GeneralCategory::for_char(c)) + }) } #[inline] pub(crate) fn is_uni_word(ch: u32) -> bool { @@ -460,15 +443,11 @@ pub(crate) fn is_uni_word(ch: u32) -> bool { #[must_use] pub fn lower_unicode(ch: u32) -> u32 { // TODO: check with cpython - char::try_from(ch) - .map(|x| x.to_lowercase().next().unwrap() as u32) - .unwrap_or(ch) + char::try_from(ch).map_or(ch, |x| x.to_lowercase().next().unwrap() as u32) } #[inline] #[must_use] pub fn upper_unicode(ch: u32) -> u32 { // TODO: check with cpython - char::try_from(ch) - .map(|x| x.to_uppercase().next().unwrap() as u32) - .unwrap_or(ch) + char::try_from(ch).map_or(ch, |x| x.to_uppercase().next().unwrap() as u32) } diff --git a/crates/stdlib/src/_asyncio.rs b/crates/stdlib/src/_asyncio.rs index 508947b561f..29bbe39a0f5 100644 --- a/crates/stdlib/src/_asyncio.rs +++ b/crates/stdlib/src/_asyncio.rs @@ -900,8 +900,7 @@ pub(crate) mod _asyncio { { let s = state .str(vm) - .map(|s| s.as_wtf8().to_lowercase()) - .unwrap_or_else(|_| Wtf8Buf::from("unknown")); + .map_or_else(|_| Wtf8Buf::from("unknown"), |s| s.as_wtf8().to_lowercase()); return Ok(s); } Ok(Wtf8Buf::from("state=unknown")) diff --git a/crates/stdlib/src/_opcode.rs b/crates/stdlib/src/_opcode.rs index a57a275b76d..80f422d69d2 100644 --- a/crates/stdlib/src/_opcode.rs +++ b/crates/stdlib/src/_opcode.rs @@ -34,25 +34,22 @@ mod _opcode { #[pyfunction] fn stack_effect(args: StackEffectArgs, vm: &VirtualMachine) -> PyResult { - let oparg = args - .oparg - .map(|v| { - if !v.fast_isinstance(vm.ctx.types.int_type) { - return Err(vm.new_type_error(format!( + let oparg = args.oparg.map_or(Ok(0), |v| { + if !v.fast_isinstance(vm.ctx.types.int_type) { + return Err(vm.new_type_error(format!( + "'{}' object cannot be interpreted as an integer", + v.class().name() + ))); + } + v.downcast_ref::() + .ok_or_else(|| { + vm.new_type_error(format!( "'{}' object cannot be interpreted as an integer", v.class().name() - ))); - } - v.downcast_ref::() - .ok_or_else(|| { - vm.new_type_error(format!( - "'{}' object cannot be interpreted as an integer", - v.class().name() - )) - })? - .try_to_primitive::(vm) - }) - .unwrap_or(Ok(0))?; + )) + })? + .try_to_primitive::(vm) + })?; let jump: Option = match args.jump { Some(v) => { @@ -99,49 +96,37 @@ mod _opcode { #[pyfunction] fn has_arg(opcode: i32) -> bool { - try_from_i32(opcode).map(|op| op.has_arg()).unwrap_or(false) + try_from_i32(opcode).is_ok_and(|op| op.has_arg()) } #[pyfunction] fn has_const(opcode: i32) -> bool { - try_from_i32(opcode) - .map(|op| op.has_const()) - .unwrap_or(false) + try_from_i32(opcode).is_ok_and(|op| op.has_const()) } #[pyfunction] fn has_name(opcode: i32) -> bool { - try_from_i32(opcode) - .map(|op| op.has_name()) - .unwrap_or(false) + try_from_i32(opcode).is_ok_and(|op| op.has_name()) } #[pyfunction] fn has_jump(opcode: i32) -> bool { - try_from_i32(opcode) - .map(|op| op.has_jump()) - .unwrap_or(false) + try_from_i32(opcode).is_ok_and(|op| op.has_jump()) } #[pyfunction] fn has_free(opcode: i32) -> bool { - try_from_i32(opcode) - .map(|op| op.has_free()) - .unwrap_or(false) + try_from_i32(opcode).is_ok_and(|op| op.has_free()) } #[pyfunction] fn has_local(opcode: i32) -> bool { - try_from_i32(opcode) - .map(|op| op.has_local()) - .unwrap_or(false) + try_from_i32(opcode).is_ok_and(|op| op.has_local()) } #[pyfunction] fn has_exc(opcode: i32) -> bool { - try_from_i32(opcode) - .map(|op| op.is_block_push()) - .unwrap_or(false) + try_from_i32(opcode).is_ok_and(|op| op.is_block_push()) } #[pyfunction] diff --git a/crates/stdlib/src/bisect.rs b/crates/stdlib/src/bisect.rs index 69b6e8aee46..7cb965cd5f9 100644 --- a/crates/stdlib/src/bisect.rs +++ b/crates/stdlib/src/bisect.rs @@ -44,14 +44,11 @@ mod _bisect { ) -> PyResult<(usize, usize)> { // We only deal with positives for lo, try_from can't fail. // Default is always a Some so we can safely unwrap. - let lo = handle_default(lo, vm)? - .map(|value| { - usize::try_from(value).map_err(|_| vm.new_value_error("lo must be non-negative")) - }) - .unwrap_or(Ok(0))?; - let hi = handle_default(hi, vm)? - .map(|value| usize::try_from(value).unwrap_or(0)) - .unwrap_or(seq_len); + let lo = handle_default(lo, vm)?.map_or(Ok(0), |value| { + usize::try_from(value).map_err(|_| vm.new_value_error("lo must be non-negative")) + })?; + let hi = + handle_default(hi, vm)?.map_or(seq_len, |value| usize::try_from(value).unwrap_or(0)); Ok((lo, hi)) } diff --git a/crates/stdlib/src/csv.rs b/crates/stdlib/src/csv.rs index 5c2d2662cc5..dab50799308 100644 --- a/crates/stdlib/src/csv.rs +++ b/crates/stdlib/src/csv.rs @@ -964,11 +964,7 @@ mod _csv { #[inline] fn trim_spaces(input: &[u8]) -> &[u8] { let trimmed_start = input.iter().position(|&x| x != b' ').unwrap_or(input.len()); - let trimmed_end = input - .iter() - .rposition(|&x| x != b' ') - .map(|i| i + 1) - .unwrap_or(0); + let trimmed_end = input.iter().rposition(|&x| x != b' ').map_or(0, |i| i + 1); &input[trimmed_start..trimmed_end] } let input = if *skipinitialspace { diff --git a/crates/stdlib/src/faulthandler.rs b/crates/stdlib/src/faulthandler.rs index 3c3533d9914..2b59ae85f81 100644 --- a/crates/stdlib/src/faulthandler.rs +++ b/crates/stdlib/src/faulthandler.rs @@ -218,13 +218,13 @@ mod decl { let funcname = frame.code.obj_name.as_str(); let lasti = frame.lasti(); let lineno = if lasti == 0 { - frame.code.first_line_number.map(|n| n.get()).unwrap_or(1) as u32 + frame.code.first_line_number.map_or(1, |n| n.get()) as u32 } else { let idx = (lasti as usize).saturating_sub(1); if idx < frame.code.locations.len() { frame.code.locations[idx].0.line.get() as u32 } else { - frame.code.first_line_number.map(|n| n.get()).unwrap_or(0) as u32 + frame.code.first_line_number.map_or(0, |n| n.get()) as u32 } }; @@ -292,7 +292,7 @@ mod decl { let funcname = frame.code.obj_name.as_str(); let filename = frame.code.source_path().as_str(); let lineno = if frame.lasti() == 0 { - frame.code.first_line_number.map(|n| n.get()).unwrap_or(1) as u32 + frame.code.first_line_number.map_or(1, |n| n.get()) as u32 } else { frame.current_location().line.get() as u32 }; @@ -1112,8 +1112,7 @@ mod decl { } else { // Already registered, keep previous handler user_signals::get_user_signal(signum) - .map(|u| u.previous) - .unwrap_or(unsafe { core::mem::zeroed() }) + .map_or(unsafe { core::mem::zeroed() }, |u| u.previous) }; user_signals::set_user_signal( diff --git a/crates/stdlib/src/json.rs b/crates/stdlib/src/json.rs index 8b3ef8d2e9c..a32397ad59d 100644 --- a/crates/stdlib/src/json.rs +++ b/crates/stdlib/src/json.rs @@ -616,8 +616,7 @@ mod _json { let end_byte_idx = wtf8 .code_point_indices() .nth(end_char_idx as usize) - .map(|(i, _)| i) - .unwrap_or(wtf8.len()); + .map_or(wtf8.len(), |(i, _)| i); Ok((value, end_char_idx as usize, end_byte_idx)) } Err(err) if err.fast_isinstance(vm.ctx.exceptions.stop_iteration) => { diff --git a/crates/stdlib/src/math.rs b/crates/stdlib/src/math.rs index b2ef4a42ba7..12d2eeee8cf 100644 --- a/crates/stdlib/src/math.rs +++ b/crates/stdlib/src/math.rs @@ -559,9 +559,7 @@ mod math { let mut flt_result: f64 = if let Some(ref f) = obj_float { f.to_f64() } else if start_is_float && let OptionalArg::Present(s) = &start { - s.downcast_ref::() - .map(|f| f.to_f64()) - .unwrap_or(1.0) + s.downcast_ref::().map_or(1.0, |f| f.to_f64()) } else { 1.0 }; diff --git a/crates/stdlib/src/mmap.rs b/crates/stdlib/src/mmap.rs index d360a2c2ada..2d1fd512480 100644 --- a/crates/stdlib/src/mmap.rs +++ b/crates/stdlib/src/mmap.rs @@ -959,12 +959,8 @@ mod mmap { let size = self.__len__(); let start = options .start - .map(|start| start.saturated_at(size)) - .unwrap_or_else(|| self.pos()); - let end = options - .end - .map(|end| end.saturated_at(size)) - .unwrap_or(size); + .map_or_else(|| self.pos(), |start| start.saturated_at(size)); + let end = options.end.map_or(size, |end| end.saturated_at(size)); (start, end) } @@ -1121,8 +1117,7 @@ mod mmap { let remaining = self.__len__().saturating_sub(pos); let num_bytes = num_bytes .filter(|&n| n >= 0 && (n as usize) <= remaining) - .map(|n| n as usize) - .unwrap_or(remaining); + .map_or(remaining, |n| n as usize); let end_pos = pos + num_bytes; let bytes = mmap.deref().as_ref().unwrap().as_slice()[pos..end_pos].to_vec(); diff --git a/crates/stdlib/src/overlapped.rs b/crates/stdlib/src/overlapped.rs index 2230991b643..86238ed9ea4 100644 --- a/crates/stdlib/src/overlapped.rs +++ b/crates/stdlib/src/overlapped.rs @@ -1949,10 +1949,7 @@ mod _overlapped { let name_wide: Option> = name.map(|n| n.encode_utf16().chain(core::iter::once(0)).collect()); - let name_ptr = name_wide - .as_ref() - .map(|n| n.as_ptr()) - .unwrap_or(core::ptr::null()); + let name_ptr = name_wide.as_ref().map_or(core::ptr::null(), |n| n.as_ptr()); let event = unsafe { windows_sys::Win32::System::Threading::CreateEventW( diff --git a/crates/stdlib/src/ssl.rs b/crates/stdlib/src/ssl.rs index caaf9b70f29..b523c29a65b 100644 --- a/crates/stdlib/src/ssl.rs +++ b/crates/stdlib/src/ssl.rs @@ -2558,8 +2558,7 @@ mod _ssl { .connection .lock() .as_ref() - .map(|conn| conn.is_session_resumed()) - .unwrap_or(false); + .is_some_and(|conn| conn.is_session_resumed()); *self.session_was_reused.lock() = was_resumed; @@ -2835,7 +2834,7 @@ mod _ssl { } let socket_timeout = self.get_socket_timeout(vm)?; - let is_non_blocking = socket_timeout.map(|t| t.is_zero()).unwrap_or(false); + let is_non_blocking = socket_timeout.is_some_and(|t| t.is_zero()); let mut sent_total = 0; @@ -2918,7 +2917,7 @@ mod _ssl { } let timeout = self.get_socket_timeout(vm)?; - let is_non_blocking = timeout.map(|t| t.is_zero()).unwrap_or(false); + let is_non_blocking = timeout.is_some_and(|t| t.is_zero()); let mut sent_total = 0; while sent_total < buf.len() { @@ -2976,7 +2975,7 @@ mod _ssl { pub(crate) fn blocking_flush_all_pending(&self, vm: &VirtualMachine) -> PyResult<()> { // Get socket timeout to respect during flush let timeout = self.get_socket_timeout(vm)?; - if timeout.map(|t| t.is_zero()).unwrap_or(false) { + if timeout.is_some_and(|t| t.is_zero()) { return self.flush_pending_tls_output(vm, None); } @@ -3581,7 +3580,7 @@ mod _ssl { }; let mut reader = conn.reader(); - reader.fill_buf().map(|buf| buf.len()).unwrap_or(0) + reader.fill_buf().map_or(0, |buf| buf.len()) }; if pending > 0 { let mut buf = vec![0u8; pending.min(len)]; @@ -3610,7 +3609,7 @@ mod _ssl { }; let mut reader = conn.reader(); - reader.fill_buf().map(|buf| buf.len()).unwrap_or(0) + reader.fill_buf().map_or(0, |buf| buf.len()) }; if pending > 0 { let mut buf = vec![0u8; pending.min(len)]; @@ -4776,12 +4775,7 @@ mod _ssl { // If name=False (default), only accept OID strings // If name=True, accept both names and OID strings - let entry = if txt - .chars() - .next() - .map(|c| c.is_ascii_digit()) - .unwrap_or(false) - { + let entry = if txt.chars().next().is_some_and(|c| c.is_ascii_digit()) { // Looks like an OID string (starts with digit) oid::find_by_oid_string(txt) } else if name { @@ -4848,13 +4842,9 @@ mod _ssl { let tuple = vm.ctx.new_tuple(vec![ vm.ctx.new_str("SSL_CERT_FILE").into(), // openssl_cafile_env - default_cafile - .map(|s| vm.ctx.new_str(s).into()) - .unwrap_or_else(|| vm.ctx.none()), // openssl_cafile - vm.ctx.new_str("SSL_CERT_DIR").into(), // openssl_capath_env - default_capath - .map(|s| vm.ctx.new_str(s).into()) - .unwrap_or_else(|| vm.ctx.none()), // openssl_capath + default_cafile.map_or_else(|| vm.ctx.none(), |s| vm.ctx.new_str(s).into()), // openssl_cafile + vm.ctx.new_str("SSL_CERT_DIR").into(), // openssl_capath_env + default_capath.map_or_else(|| vm.ctx.none(), |s| vm.ctx.new_str(s).into()), // openssl_capath ]); Ok(tuple.into()) } diff --git a/crates/stdlib/src/ssl/compat.rs b/crates/stdlib/src/ssl/compat.rs index 3cf7db49c5a..29e3687e9d6 100644 --- a/crates/stdlib/src/ssl/compat.rs +++ b/crates/stdlib/src/ssl/compat.rs @@ -1754,8 +1754,7 @@ pub(super) fn ssl_read( let bytes_read = data .clone() .try_into_value::(vm) - .map(|b| b.as_bytes().len()) - .unwrap_or(0); + .map_or(0, |b| b.as_bytes().len()); if bytes_read == 0 { // No more data available - check if this is clean shutdown or unexpected EOF @@ -2177,8 +2176,7 @@ fn ssl_ensure_data_available( let bytes_read = data .clone() .try_into_value::(vm) - .map(|b| b.as_bytes().len()) - .unwrap_or(0); + .map_or(0, |b| b.as_bytes().len()); // Check if BIO has EOF set (incoming BIO closed) let is_eof = if is_bio { diff --git a/crates/vm/src/builtins/float.rs b/crates/vm/src/builtins/float.rs index cfce960c18d..f36f9de79d4 100644 --- a/crates/vm/src/builtins/float.rs +++ b/crates/vm/src/builtins/float.rs @@ -247,9 +247,10 @@ fn float_from_string(val: PyObjectRef, vm: &VirtualMachine) -> PyResult { ))); }; crate::literal::float::parse_bytes(b).ok_or_else(|| { - val.repr(vm) - .map(|repr| vm.new_value_error(format!("could not convert string to float: {repr}"))) - .unwrap_or_else(|e| e) + val.repr(vm).map_or_else( + |e| e, + |repr| vm.new_value_error(format!("could not convert string to float: {repr}")), + ) }) } diff --git a/crates/vm/src/builtins/frame.rs b/crates/vm/src/builtins/frame.rs index 3c1c48b66f0..bfce1ba8291 100644 --- a/crates/vm/src/builtins/frame.rs +++ b/crates/vm/src/builtins/frame.rs @@ -474,7 +474,7 @@ impl Frame { // If lasti is 0, execution hasn't started yet - use first line number // Similar to PyCode_Addr2Line which returns co_firstlineno for addr_q < 0 if self.lasti() == 0 { - self.code.first_line_number.map(|n| n.get()).unwrap_or(1) + self.code.first_line_number.map_or(1, |n| n.get()) } else { self.current_location().line.get() } @@ -496,11 +496,7 @@ impl Frame { } }; - let first_line = self - .code - .first_line_number - .map(|n| n.get() as i32) - .unwrap_or(1); + let first_line = self.code.first_line_number.map_or(1, |n| n.get() as i32); if l_new_lineno < first_line { return Err(vm.new_value_error(format!( diff --git a/crates/vm/src/builtins/function.rs b/crates/vm/src/builtins/function.rs index 10f96fd70c9..9b34aa8bff3 100644 --- a/crates/vm/src/builtins/function.rs +++ b/crates/vm/src/builtins/function.rs @@ -192,8 +192,7 @@ impl PyFunction { code.code .constants .first() - .map(|c| c.as_object().to_owned()) - .unwrap_or_else(|| vm.ctx.none()) + .map_or_else(|| vm.ctx.none(), |c| c.as_object().to_owned()) } else { vm.ctx.none() }; diff --git a/crates/vm/src/builtins/iter.rs b/crates/vm/src/builtins/iter.rs index a5b4fe0d3cc..322eef15cd1 100644 --- a/crates/vm/src/builtins/iter.rs +++ b/crates/vm/src/builtins/iter.rs @@ -188,9 +188,10 @@ impl PySequenceIterator { let internal = self.internal.lock(); if let IterStatus::Active(obj) = &internal.status { let seq = obj.sequence_unchecked(); - seq.length(vm) - .map(|x| PyInt::from(x).into_pyobject(vm)) - .unwrap_or_else(|_| vm.ctx.not_implemented()) + seq.length(vm).map_or_else( + |_| vm.ctx.not_implemented(), + |x| PyInt::from(x).into_pyobject(vm), + ) } else { PyInt::from(0).into_pyobject(vm) } diff --git a/crates/vm/src/builtins/module.rs b/crates/vm/src/builtins/module.rs index 9ddf27e1297..f9d3df8df97 100644 --- a/crates/vm/src/builtins/module.rs +++ b/crates/vm/src/builtins/module.rs @@ -185,8 +185,7 @@ impl Py { let is_possibly_shadowing = origin .as_ref() - .map(|o| is_possibly_shadowing_path(o, vm)) - .unwrap_or(false); + .is_some_and(|o| is_possibly_shadowing_path(o, vm)); // Use the ORIGINAL __name__ object for stdlib check (may raise TypeError // if __name__ is an unhashable str subclass) let is_possibly_shadowing_stdlib = if is_possibly_shadowing { diff --git a/crates/vm/src/builtins/object.rs b/crates/vm/src/builtins/object.rs index 6670d64d588..7ee22e5cbda 100644 --- a/crates/vm/src/builtins/object.rs +++ b/crates/vm/src/builtins/object.rs @@ -756,9 +756,8 @@ fn reduce_newobj(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { // Use copyreg.__newobj_ex__ let newobj = copyreg.get_attr("__newobj_ex__", vm)?; let args_tuple: PyObjectRef = args.into(); - let kwargs_dict: PyObjectRef = kwargs - .map(|k| k.into()) - .unwrap_or_else(|| vm.ctx.new_dict().into()); + let kwargs_dict: PyObjectRef = + kwargs.map_or_else(|| vm.ctx.new_dict().into(), |k| k.into()); let newargs = vm .ctx diff --git a/crates/vm/src/builtins/singletons.rs b/crates/vm/src/builtins/singletons.rs index 31dbf1666f1..2928c523b1b 100644 --- a/crates/vm/src/builtins/singletons.rs +++ b/crates/vm/src/builtins/singletons.rs @@ -82,10 +82,10 @@ impl Comparable for PyNone { op: PyComparisonOp, _vm: &VirtualMachine, ) -> PyResult { - Ok(op - .identical_optimization(zelf, other) - .map(PyComparisonValue::Implemented) - .unwrap_or(PyComparisonValue::NotImplemented)) + Ok(op.identical_optimization(zelf, other).map_or( + PyComparisonValue::NotImplemented, + PyComparisonValue::Implemented, + )) } } diff --git a/crates/vm/src/builtins/str.rs b/crates/vm/src/builtins/str.rs index 60c588ba47c..8a36d9350ba 100644 --- a/crates/vm/src/builtins/str.rs +++ b/crates/vm/src/builtins/str.rs @@ -452,7 +452,7 @@ impl Constructor for PyStr { input.class().name() ))); } - let enc_str = encoding.as_ref().map(|e| e.as_str()).unwrap_or("utf-8"); + let enc_str = encoding.as_ref().map_or("utf-8", |e| e.as_str()); let s = vm .state .codec_registry @@ -550,8 +550,7 @@ impl PyStr { pub fn to_string_lossy(&self) -> Cow<'_, str> { self.to_str() - .map(Cow::Borrowed) - .unwrap_or_else(|| self.as_wtf8().to_string_lossy()) + .map_or_else(|| self.as_wtf8().to_string_lossy(), Cow::Borrowed) } pub const fn kind(&self) -> StrKind { diff --git a/crates/vm/src/builtins/template.rs b/crates/vm/src/builtins/template.rs index ba5e9c5eb0c..92734e13424 100644 --- a/crates/vm/src/builtins/template.rs +++ b/crates/vm/src/builtins/template.rs @@ -116,8 +116,7 @@ impl PyTemplate { .map(|interp| { interp .downcast_ref::() - .map(|i| i.value.clone()) - .unwrap_or_else(|| interp.clone()) + .map_or_else(|| interp.clone(), |i| i.value.clone()) }) .collect(); vm.ctx.new_tuple(values) diff --git a/crates/vm/src/builtins/type.rs b/crates/vm/src/builtins/type.rs index 6208bc5ebfe..a0d1cf8802b 100644 --- a/crates/vm/src/builtins/type.rs +++ b/crates/vm/src/builtins/type.rs @@ -860,21 +860,17 @@ impl PyType { if slots.flags.contains(PyTypeFlags::DISALLOW_INSTANTIATION) { slots.new.store(None) } else if slots.new.load().is_none() { - slots.new.store( - base.as_ref() - .map(|base| base.slots.new.load()) - .unwrap_or(None), - ) + slots + .new + .store(base.as_ref().and_then(|base| base.slots.new.load())) } } fn set_alloc(slots: &PyTypeSlots, base: &Option) { if slots.alloc.load().is_none() { - slots.alloc.store( - base.as_ref() - .map(|base| base.slots.alloc.load()) - .unwrap_or(None), - ); + slots + .alloc + .store(base.as_ref().and_then(|base| base.slots.alloc.load())); } } @@ -2072,7 +2068,7 @@ impl Constructor for PyType { .map(|base| base.slots.member_count) .max() .unwrap(); - let heaptype_member_count = heaptype_slots.as_ref().map(|x| x.len()).unwrap_or(0); + let heaptype_member_count = heaptype_slots.as_ref().map_or(0, |x| x.len()); let member_count: usize = base_member_count + heaptype_member_count; let mut flags = PyTypeFlags::heap_type_flags(); diff --git a/crates/vm/src/exceptions.rs b/crates/vm/src/exceptions.rs index 230ea182df6..538b60c6d49 100644 --- a/crates/vm/src/exceptions.rs +++ b/crates/vm/src/exceptions.rs @@ -2002,8 +2002,8 @@ pub(super) mod types { .as_ref() .map(|s| s.str(vm)) .transpose()? - .map(|s| s.to_string()) - .unwrap_or_else(|| "None".to_owned()); + .map_or_else(|| "None".to_owned(), |s| s.to_string()); + if let Some(ref f2) = filename2 { return Ok(vm.ctx.new_str(format!( "[WinError {}] {}: {} -> {}", @@ -2034,14 +2034,12 @@ pub(super) mod types { .as_ref() .map(|e| e.str(vm)) .transpose()? - .map(|s| s.to_string()) - .unwrap_or_else(|| "None".to_owned()); + .map_or_else(|| "None".to_owned(), |s| s.to_string()); let msg = strerror .as_ref() .map(|s| s.str(vm)) .transpose()? - .map(|s| s.to_string()) - .unwrap_or_else(|| "None".to_owned()); + .map_or_else(|| "None".to_owned(), |s| s.to_string()); if let Some(ref f2) = filename2 { return Ok(vm.ctx.new_str(format!( "[Errno {}] {}: {} -> {}", diff --git a/crates/vm/src/frame.rs b/crates/vm/src/frame.rs index c87341de32a..ba007622187 100644 --- a/crates/vm/src/frame.rs +++ b/crates/vm/src/frame.rs @@ -1504,8 +1504,7 @@ impl ExecutingFrame<'_> { let exc_value: PyObjectRef = exc.clone().into(); let exc_tb: PyObjectRef = exc .__traceback__() - .map(|tb| -> PyObjectRef { tb.into() }) - .unwrap_or_else(|| vm.ctx.none()); + .map_or_else(|| vm.ctx.none(), |tb| -> PyObjectRef { tb.into() }); let tuple = vm.ctx.new_tuple(vec![exc_type, exc_value, exc_tb]).into(); vm.trace_event(crate::protocol::TraceEvent::Exception, Some(tuple))?; } @@ -3426,8 +3425,7 @@ impl ExecutingFrame<'_> { let exc = self.pop_value(); let prev_exc = vm .current_exception() - .map(|e| e.into()) - .unwrap_or_else(|| vm.ctx.none()); + .map_or_else(|| vm.ctx.none(), |e| e.into()); // Set exc as the current exception if let Some(exc_ref) = exc.downcast_ref::() { @@ -6089,13 +6087,10 @@ impl ExecutingFrame<'_> { // because a callback may de-instrument and clear the tables. let (real_op_byte, also_instruction) = { let data = self.code.monitoring_data.lock(); - let line_op = data.as_ref().map(|d| d.line_opcodes[idx]).unwrap_or(0); + let line_op = data.as_ref().map_or(0, |d| d.line_opcodes[idx]); if line_op == u8::from(Instruction::InstrumentedInstruction) { // LINE wraps INSTRUCTION: resolve the INSTRUCTION side-table too - let inst_op = data - .as_ref() - .map(|d| d.per_instruction_opcodes[idx]) - .unwrap_or(0); + let inst_op = data.as_ref().map_or(0, |d| d.per_instruction_opcodes[idx]); (inst_op, true) } else { (line_op, false) @@ -6143,9 +6138,7 @@ impl ExecutingFrame<'_> { // Get original opcode from side-table let original_op_byte = { let data = self.code.monitoring_data.lock(); - data.as_ref() - .map(|d| d.per_instruction_opcodes[idx]) - .unwrap_or(0) + data.as_ref().map_or(0, |d| d.per_instruction_opcodes[idx]) }; debug_assert!( original_op_byte != 0, @@ -6282,8 +6275,7 @@ impl ExecutingFrame<'_> { let is_possibly_shadowing = origin .as_ref() - .map(|o| is_possibly_shadowing_path(o, vm)) - .unwrap_or(false); + .is_some_and(|o| is_possibly_shadowing_path(o, vm)); let is_possibly_shadowing_stdlib = if is_possibly_shadowing { if let Some(ref mod_name) = mod_name_obj { is_stdlib_module_name(mod_name, vm)? @@ -9618,9 +9610,7 @@ impl ExecutingFrame<'_> { let stack_len = self.localsplus.stack_len(); if count > stack_len { let instr = self.code.instructions.get(self.lasti() as usize); - let op_name = instr - .map(|i| format!("{:?}", i.op)) - .unwrap_or_else(|| "None".to_string()); + let op_name = instr.map_or_else(|| "None".to_string(), |i| format!("{:?}", i.op)); panic!( "Stack underflow in pop_multiple: trying to pop {} elements from stack with {} elements. lasti={}, code={}, op={}, source_path={}", count, diff --git a/crates/vm/src/getpath.rs b/crates/vm/src/getpath.rs index 0ed62136088..66c39613bfa 100644 --- a/crates/vm/src/getpath.rs +++ b/crates/vm/src/getpath.rs @@ -145,10 +145,10 @@ pub fn init_path_config(settings: &Settings) -> Paths { // Step 5: Set prefix and base_prefix if venv_prefix.is_some() { // In venv: prefix = venv directory, base_prefix = original Python's prefix - paths.prefix = venv_prefix - .as_ref() - .map(|p| p.to_string_lossy().into_owned()) - .unwrap_or_else(|| calculated_prefix.clone()); + paths.prefix = venv_prefix.as_ref().map_or_else( + || calculated_prefix.clone(), + |p| p.to_string_lossy().into_owned(), + ); paths.base_prefix = calculated_prefix; } else { // Not in venv: prefix == base_prefix diff --git a/crates/vm/src/object/ext.rs b/crates/vm/src/object/ext.rs index dc4a7bd4fd4..f3170db98fa 100644 --- a/crates/vm/src/object/ext.rs +++ b/crates/vm/src/object/ext.rs @@ -346,9 +346,7 @@ impl PyAtomicRef { impl From>> for PyAtomicRef> { fn from(opt_ref: Option>) -> Self { - let val = opt_ref - .map(|x| PyRef::leak(x) as *const Py as *mut _) - .unwrap_or(null_mut()); + let val = opt_ref.map_or(null_mut(), |x| PyRef::leak(x) as *const Py as *mut _); Self { inner: Radium::new(val), _phantom: Default::default(), @@ -378,9 +376,7 @@ impl PyAtomicRef> { /// until no more reference can be used via PyAtomicRef::deref() #[must_use] pub unsafe fn swap(&self, opt_ref: Option>) -> Option> { - let val = opt_ref - .map(|x| PyRef::leak(x) as *const Py as *mut _) - .unwrap_or(null_mut()); + let val = opt_ref.map_or(null_mut(), |x| PyRef::leak(x) as *const Py as *mut _); let old = Radium::swap(&self.inner, val, Ordering::AcqRel); unsafe { old.cast::>().as_ref().map(|x| PyRef::from_raw(x)) } } @@ -440,9 +436,7 @@ impl PyAtomicRef { impl From> for PyAtomicRef> { fn from(obj: Option) -> Self { - let val = obj - .map(|x| x.into_raw().as_ptr().cast()) - .unwrap_or(null_mut()); + let val = obj.map_or(null_mut(), |x| x.into_raw().as_ptr().cast()); Self { inner: Radium::new(val), _phantom: Default::default(), @@ -472,9 +466,7 @@ impl PyAtomicRef> { /// until no more reference can be used via PyAtomicRef::deref() #[must_use] pub unsafe fn swap(&self, obj: Option) -> Option { - let val = obj - .map(|x| x.into_raw().as_ptr().cast()) - .unwrap_or(null_mut()); + let val = obj.map_or(null_mut(), |x| x.into_raw().as_ptr().cast()); let old = Radium::swap(&self.inner, val, Ordering::AcqRel); unsafe { NonNull::new(old.cast::()).map(|x| PyObjectRef::from_raw(x)) } } diff --git a/crates/vm/src/stdlib/_ast/statement.rs b/crates/vm/src/stdlib/_ast/statement.rs index 386f4d8cc93..32ee5273dcb 100644 --- a/crates/vm/src/stdlib/_ast/statement.rs +++ b/crates/vm/src/stdlib/_ast/statement.rs @@ -191,9 +191,10 @@ impl Node for ast::StmtFunctionDef { dict.set_item("type_comment", vm.ctx.none(), vm).unwrap(); dict.set_item( "type_params", - type_params - .map(|tp| tp.ast_to_object(vm, source_file)) - .unwrap_or_else(|| vm.ctx.new_list(vec![]).into()), + type_params.map_or_else( + || vm.ctx.new_list(vec![]).into(), + |tp| tp.ast_to_object(vm, source_file), + ), vm, ) .unwrap(); @@ -273,17 +274,19 @@ impl Node for ast::StmtClassDef { .unwrap(); dict.set_item( "bases", - bases - .map(|b| b.ast_to_object(_vm, source_file)) - .unwrap_or_else(|| _vm.ctx.new_list(vec![]).into()), + bases.map_or_else( + || _vm.ctx.new_list(vec![]).into(), + |b| b.ast_to_object(_vm, source_file), + ), _vm, ) .unwrap(); dict.set_item( "keywords", - keywords - .map(|k| k.ast_to_object(_vm, source_file)) - .unwrap_or_else(|| _vm.ctx.new_list(vec![]).into()), + keywords.map_or_else( + || _vm.ctx.new_list(vec![]).into(), + |k| k.ast_to_object(_vm, source_file), + ), _vm, ) .unwrap(); @@ -297,9 +300,10 @@ impl Node for ast::StmtClassDef { .unwrap(); dict.set_item( "type_params", - type_params - .map(|tp| tp.ast_to_object(_vm, source_file)) - .unwrap_or_else(|| _vm.ctx.new_list(vec![]).into()), + type_params.map_or_else( + || _vm.ctx.new_list(vec![]).into(), + |tp| tp.ast_to_object(_vm, source_file), + ), _vm, ) .unwrap(); @@ -480,9 +484,10 @@ impl Node for ast::StmtTypeAlias { .unwrap(); dict.set_item( "type_params", - type_params - .map(|tp| tp.ast_to_object(_vm, source_file)) - .unwrap_or_else(|| _vm.ctx.new_list(Vec::new()).into()), + type_params.map_or_else( + || _vm.ctx.new_list(Vec::new()).into(), + |tp| tp.ast_to_object(_vm, source_file), + ), _vm, ) .unwrap(); diff --git a/crates/vm/src/stdlib/_codecs.rs b/crates/vm/src/stdlib/_codecs.rs index b2c0a220003..adab1915095 100644 --- a/crates/vm/src/stdlib/_codecs.rs +++ b/crates/vm/src/stdlib/_codecs.rs @@ -62,8 +62,7 @@ mod _codecs { let encoding = self .encoding .as_deref() - .map(|s| s.as_str()) - .unwrap_or(codecs::DEFAULT_ENCODING); + .map_or(codecs::DEFAULT_ENCODING, |s| s.as_str()); f( &vm.state.codec_registry, self.obj, @@ -392,7 +391,7 @@ mod _codecs_windows { CP_ACP, WC_NO_BEST_FIT_CHARS, WideCharToMultiByte, }; - let errors = args.errors.as_ref().map(|s| s.as_str()).unwrap_or("strict"); + let errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); let s = match args.s.to_str() { Some(s) => s, None => { @@ -482,7 +481,7 @@ mod _codecs_windows { CP_ACP, MB_ERR_INVALID_CHARS, MultiByteToWideChar, }; - let _errors = args.errors.as_ref().map(|s| s.as_str()).unwrap_or("strict"); + let _errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); let data = args.data.borrow_buf(); let len = data.len(); @@ -578,7 +577,7 @@ mod _codecs_windows { CP_OEMCP, WC_NO_BEST_FIT_CHARS, WideCharToMultiByte, }; - let errors = args.errors.as_ref().map(|s| s.as_str()).unwrap_or("strict"); + let errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); let s = match args.s.to_str() { Some(s) => s, None => { @@ -668,7 +667,7 @@ mod _codecs_windows { CP_OEMCP, MB_ERR_INVALID_CHARS, MultiByteToWideChar, }; - let _errors = args.errors.as_ref().map(|s| s.as_str()).unwrap_or("strict"); + let _errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); let data = args.data.borrow_buf(); let len = data.len(); @@ -1054,7 +1053,8 @@ mod _codecs_windows { if args.code_page < 0 { return Err(vm.new_value_error("invalid code page number")); } - let errors = args.errors.as_ref().map(|s| s.as_str()).unwrap_or("strict"); + + let errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); let code_page = args.code_page as u32; let char_len = args.s.char_len(); @@ -1367,7 +1367,8 @@ mod _codecs_windows { if args.code_page < 0 { return Err(vm.new_value_error("invalid code page number")); } - let errors = args.errors.as_ref().map(|s| s.as_str()).unwrap_or("strict"); + + let errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); let code_page = args.code_page as u32; let data = args.data.borrow_buf(); let is_final = args.r#final; diff --git a/crates/vm/src/stdlib/_collections.rs b/crates/vm/src/stdlib/_collections.rs index 8eacc69f039..03438f28c08 100644 --- a/crates/vm/src/stdlib/_collections.rs +++ b/crates/vm/src/stdlib/_collections.rs @@ -181,8 +181,7 @@ mod _collections { Err(vm.new_value_error( needle .repr(vm) - .map(|repr| format!("{repr} is not in deque")) - .unwrap_or_else(|_| String::new()), + .map_or_else(|_| String::new(), |repr| format!("{repr} is not in deque")), )) } } @@ -569,8 +568,7 @@ mod _collections { let class_name = class.name(); let closing_part = zelf .maxlen - .map(|maxlen| format!("], maxlen={maxlen}")) - .unwrap_or_else(|| "]".to_owned()); + .map_or_else(|| "]".to_owned(), |maxlen| format!("], maxlen={maxlen}")); if zelf.__len__() == 0 { return Ok(vm.ctx.new_str(format!("{class_name}([{closing_part})"))); diff --git a/crates/vm/src/stdlib/_ctypes/array.rs b/crates/vm/src/stdlib/_ctypes/array.rs index c04e342547a..657f0a2146f 100644 --- a/crates/vm/src/stdlib/_ctypes/array.rs +++ b/crates/vm/src/stdlib/_ctypes/array.rs @@ -26,8 +26,7 @@ fn get_size_from_format(fmt: &str) -> usize { .chars() .next() .map(|c| c.to_string()); - code.map(|c| type_info(&c).map(|t| t.size).unwrap_or(1)) - .unwrap_or(1) + code.map_or(1, |c| type_info(&c).map_or(1, |t| t.size)) } /// Creates array type for (element_type, length) @@ -770,12 +769,7 @@ impl PyCArray { } Some("u") => { if let Some(s) = value.downcast_ref::() { - let code = s - .as_wtf8() - .code_points() - .next() - .map(|c| c.to_u32()) - .unwrap_or(0); + let code = s.as_wtf8().code_points().next().map_or(0, |c| c.to_u32()); if offset + WCHAR_SIZE <= buffer.len() { wchar_to_bytes(code, &mut buffer[offset..]); } diff --git a/crates/vm/src/stdlib/_ctypes/base.rs b/crates/vm/src/stdlib/_ctypes/base.rs index 7d611c27b0f..9eda289b548 100644 --- a/crates/vm/src/stdlib/_ctypes/base.rs +++ b/crates/vm/src/stdlib/_ctypes/base.rs @@ -2098,7 +2098,7 @@ impl FfiArgValue { pub(super) fn buffer_to_ffi_value(type_code: &str, buffer: &[u8]) -> FfiArgValue { match type_code { "c" | "b" => { - let v = buffer.first().map(|&b| b as i8).unwrap_or(0); + let v = buffer.first().map_or(0, |&b| b as i8); FfiArgValue::I8(v) } "B" => { @@ -2157,7 +2157,7 @@ pub(super) fn buffer_to_ffi_value(type_code: &str, buffer: &[u8]) -> FfiArgValue } "z" | "Z" | "P" | "O" => FfiArgValue::Pointer(read_ptr_from_buffer(buffer)), "?" => { - let v = buffer.first().map(|&b| b != 0).unwrap_or(false); + let v = buffer.first().is_some_and(|&b| b != 0); FfiArgValue::U8(if v { 1 } else { 0 }) } "u" => { diff --git a/crates/vm/src/stdlib/_ctypes/function.rs b/crates/vm/src/stdlib/_ctypes/function.rs index 0577bdc83bd..00bbe2ad523 100644 --- a/crates/vm/src/stdlib/_ctypes/function.rs +++ b/crates/vm/src/stdlib/_ctypes/function.rs @@ -1760,7 +1760,7 @@ fn build_result( // Handle OUT parameter return values if out_buffers.is_empty() { - return result.map(Ok).unwrap_or_else(|| Ok(vm.ctx.none())); + return result.map_or_else(|| Ok(vm.ctx.none()), Ok); } let out_values = extract_out_values(out_buffers, vm); @@ -1851,8 +1851,7 @@ impl AsBuffer for PyCFuncPtr { stg_info .format .clone() - .map(Cow::Owned) - .unwrap_or(Cow::Borrowed("X{}")), + .map_or(Cow::Borrowed("X{}"), Cow::Owned), stg_info.size, ) } else { @@ -1946,8 +1945,7 @@ impl PyCFuncPtr { // Fallback to StgInfo for native types zelf.class() .stg_info_opt() - .map(|stg| stg.flags.bits()) - .unwrap_or(StgInfoFlags::empty().bits()) + .map_or(StgInfoFlags::empty().bits(), |stg| stg.flags.bits()) } } @@ -2184,8 +2182,7 @@ unsafe extern "C" fn thunk_callback( let repr = userdata .callable .repr(vm) - .map(|s| s.to_string()) - .unwrap_or_else(|_| "".to_string()); + .map_or_else(|_| "".to_string(), |s| s.to_string()); let msg = format!( "Exception ignored while calling ctypes callback function {}", repr diff --git a/crates/vm/src/stdlib/_ctypes/pointer.rs b/crates/vm/src/stdlib/_ctypes/pointer.rs index 1e704a1e4ad..57535c175ca 100644 --- a/crates/vm/src/stdlib/_ctypes/pointer.rs +++ b/crates/vm/src/stdlib/_ctypes/pointer.rs @@ -845,8 +845,7 @@ impl AsBuffer for PyCPointer { let format = stg_info .format .clone() - .map(Cow::Owned) - .unwrap_or(Cow::Borrowed("&B")); + .map_or(Cow::Borrowed("&B"), Cow::Owned); let itemsize = stg_info.size; // Pointer types are scalars with ndim=0, shape=() let desc = BufferDescriptor { diff --git a/crates/vm/src/stdlib/_ctypes/simple.rs b/crates/vm/src/stdlib/_ctypes/simple.rs index 1dd2001335f..bb00d4830ce 100644 --- a/crates/vm/src/stdlib/_ctypes/simple.rs +++ b/crates/vm/src/stdlib/_ctypes/simple.rs @@ -1424,8 +1424,7 @@ impl AsBuffer for PyCSimple { let format = stg_info .format .clone() - .map(Cow::Owned) - .unwrap_or(Cow::Borrowed("B")); + .map_or(Cow::Borrowed("B"), Cow::Owned); let itemsize = stg_info.size; // Simple types are scalars with ndim=0, shape=() let desc = BufferDescriptor { diff --git a/crates/vm/src/stdlib/_functools.rs b/crates/vm/src/stdlib/_functools.rs index 7e648bae259..b36fbbcddbb 100644 --- a/crates/vm/src/stdlib/_functools.rs +++ b/crates/vm/src/stdlib/_functools.rs @@ -164,8 +164,7 @@ mod _functools { fn __dict__(zelf: &Py, vm: &VirtualMachine) -> PyDictRef { zelf.as_object() .instance_dict() - .map(|d| d.get_or_insert(vm)) - .unwrap_or_else(|| vm.ctx.new_dict()) + .map_or_else(|| vm.ctx.new_dict(), |d| d.get_or_insert(vm)) } #[pygetset(setter)] @@ -492,8 +491,10 @@ mod _functools { let qualname = zelf.class().__qualname__(vm); let qualname_wtf8 = qualname .downcast_ref::() - .map(|s| s.as_wtf8().to_owned()) - .unwrap_or_else(|| Wtf8Buf::from(zelf.class().name().to_owned())); + .map_or_else( + || Wtf8Buf::from(zelf.class().name().to_owned()), + |s| s.as_wtf8().to_owned(), + ); let module = zelf.class().__module__(vm); let mut result = Wtf8Buf::new(); diff --git a/crates/vm/src/stdlib/_io.rs b/crates/vm/src/stdlib/_io.rs index 5295dba5012..640bd80fd11 100644 --- a/crates/vm/src/stdlib/_io.rs +++ b/crates/vm/src/stdlib/_io.rs @@ -1856,7 +1856,7 @@ mod _io { fn read(&self, size: OptionalSize, vm: &VirtualMachine) -> PyResult> { let mut data = self.reader().lock(vm)?; let raw = data.check_init(vm)?; - let n = size.size.map(|s| *s).unwrap_or(-1); + let n = size.size.map_or(-1, |s| *s); if n < -1 { return Err(vm.new_value_error("read length must be non-negative or -1")); } @@ -5968,8 +5968,7 @@ mod fileio { if zelf.fd.load() >= 0 && zelf.closefd.load() { let repr = source .repr(vm) - .map(|s| s.as_wtf8().to_owned()) - .unwrap_or_else(|_| Wtf8Buf::from("")); + .map_or_else(|_| Wtf8Buf::from(""), |s| s.as_wtf8().to_owned()); if let Err(e) = crate::stdlib::_warnings::warn( vm.ctx.exceptions.resource_warning, format!("unclosed file {repr}"), @@ -6230,8 +6229,7 @@ mod winconsoleio { let mode_str: &str = args .mode .as_ref() - .map(|s: &PyUtf8StrRef| s.as_str()) - .unwrap_or("r"); + .map_or("r", |s: &PyUtf8StrRef| s.as_str()); let mut rwa = false; let mut readable = false; @@ -6521,8 +6519,8 @@ mod winconsoleio { if zelf.fd.load() >= 0 && zelf.closefd.load() { let repr = source .repr(vm) - .map(|s| s.as_wtf8().to_owned()) - .unwrap_or_else(|_| Wtf8Buf::from("")); + .map_or_else(|_| Wtf8Buf::from(""), |s| s.as_wtf8().to_owned()); + if let Err(e) = crate::stdlib::_warnings::warn( vm.ctx.exceptions.resource_warning, format!("unclosed file {repr}"), diff --git a/crates/vm/src/stdlib/_sre.rs b/crates/vm/src/stdlib/_sre.rs index becf2453e7a..1f62b48b137 100644 --- a/crates/vm/src/stdlib/_sre.rs +++ b/crates/vm/src/stdlib/_sre.rs @@ -723,8 +723,7 @@ mod _sre { .ok_or_else(|| vm.new_index_error("no such group")) .map(|index| { self.get_slice(index, str_drive, vm) - .map(|x| x.to_pyobject(vm)) - .unwrap_or_else(|| vm.ctx.none()) + .map_or_else(|| vm.ctx.none(), |x| x.to_pyobject(vm)) }) }) .try_collect()?; @@ -761,8 +760,7 @@ mod _sre { let v: Vec = (1..self.regs.len()) .map(|i| { self.get_slice(i, str_drive, vm) - .map(|s| s.to_pyobject(vm)) - .unwrap_or_else(|| default.clone()) + .map_or_else(|| default.clone(), |s| s.to_pyobject(vm)) }) .collect(); Ok(PyTuple::new_ref(v, &vm.ctx)) @@ -784,8 +782,7 @@ mod _sre { let value = self .get_index(index, vm) .and_then(|x| self.get_slice(x, str_drive, vm)) - .map(|x| x.to_pyobject(vm)) - .unwrap_or_else(|| default.clone()); + .map_or_else(|| default.clone(), |x| x.to_pyobject(vm)); dict.set_item(&*key, value, vm)?; } Ok(dict) diff --git a/crates/vm/src/stdlib/_typing.rs b/crates/vm/src/stdlib/_typing.rs index 70554037d46..3eff99f6c45 100644 --- a/crates/vm/src/stdlib/_typing.rs +++ b/crates/vm/src/stdlib/_typing.rs @@ -327,8 +327,7 @@ pub(crate) mod decl { "Expected a type param, got {}", param .repr(vm) - .map(|s| s.to_string()) - .unwrap_or_else(|_| "?".to_owned()) + .map_or_else(|_| "?".to_owned(), |s| s.to_string()) )) })?; let is_no_default = dflt.is(no_default); diff --git a/crates/vm/src/stdlib/builtins.rs b/crates/vm/src/stdlib/builtins.rs index 1c83bac3ec6..bf047ade300 100644 --- a/crates/vm/src/stdlib/builtins.rs +++ b/crates/vm/src/stdlib/builtins.rs @@ -1225,21 +1225,21 @@ mod builtins { }; // Use downcast_exact to keep ref to old object on error. - let metaclass = kwargs - .pop_kwarg("metaclass") - .map(|metaclass| { - metaclass - .downcast_exact::(vm) - .map(|m| m.into_pyref()) - }) - .unwrap_or_else(|| { + let metaclass = kwargs.pop_kwarg("metaclass").map_or_else( + || { // if there are no bases, use type; else get the type of the first base Ok(if bases.is_empty() { vm.ctx.types.type_type.to_owned() } else { bases.first().unwrap().class().to_owned() }) - }); + }, + |metaclass| { + metaclass + .downcast_exact::(vm) + .map(|m| m.into_pyref()) + }, + ); let (metaclass, meta_name) = match metaclass { Ok(mut metaclass) => { diff --git a/crates/vm/src/stdlib/posix.rs b/crates/vm/src/stdlib/posix.rs index 95abf264fbf..1d114071aad 100644 --- a/crates/vm/src/stdlib/posix.rs +++ b/crates/vm/src/stdlib/posix.rs @@ -2590,8 +2590,7 @@ pub mod module { let headers = _extract_vec_bytes(args.headers, vm)?; let count = headers .as_ref() - .map(|v| v.iter().map(|s| s.len()).sum()) - .unwrap_or(0) as i64 + .map_or(0, |v| v.iter().map(|s| s.len()).sum()) as i64 + args.count; let headers = headers diff --git a/crates/vm/src/types/slot.rs b/crates/vm/src/types/slot.rs index bfcd7a8798d..3d64d121b6a 100644 --- a/crates/vm/src/types/slot.rs +++ b/crates/vm/src/types/slot.rs @@ -499,8 +499,7 @@ fn hash_wrapper(zelf: &PyObject, vm: &VirtualMachine) -> PyResult { let big_int = py_int.as_bigint(); let hash = big_int .to_i64() - .map(fix_sentinel) - .unwrap_or_else(|| hash_bigint(big_int)); + .map_or_else(|| hash_bigint(big_int), fix_sentinel); Ok(hash) } diff --git a/crates/vm/src/warn.rs b/crates/vm/src/warn.rs index 5dbf3fce780..cde821cfaa3 100644 --- a/crates/vm/src/warn.rs +++ b/crates/vm/src/warn.rs @@ -196,8 +196,7 @@ fn already_warned( let version_matches = version_obj.as_ref().is_some_and(|v| { v.try_int(vm) - .map(|i| i.as_u32_mask() as usize == current_version) - .unwrap_or(false) + .is_ok_and(|i| i.as_u32_mask() as usize == current_version) }); if version_matches { diff --git a/crates/vm/src/windows.rs b/crates/vm/src/windows.rs index 30686412612..bb65ce29aa5 100644 --- a/crates/vm/src/windows.rs +++ b/crates/vm/src/windows.rs @@ -153,9 +153,7 @@ fn attribute_data_to_stat( let mut st_mode = attributes_to_mode(info.dwFileAttributes); let st_size = ((info.nFileSizeHigh as u64) << 32) | (info.nFileSizeLow as u64); - let st_dev = id_info - .map(|id| id.VolumeSerialNumber as u32) - .unwrap_or(info.dwVolumeSerialNumber); + let st_dev = id_info.map_or(info.dwVolumeSerialNumber, |id| id.VolumeSerialNumber as u32); let st_nlink = info.nNumberOfLinks as i32; // Convert FILETIME/LARGE_INTEGER to (time_t, nsec)