Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 37 additions & 23 deletions crates/stdlib/src/_zoneinfo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub(crate) use _zoneinfo::module_def;
#[pymodule]
mod _zoneinfo {
use alloc::collections::VecDeque;
use rustpython_common::wtf8::{Wtf8Buf, wtf8_concat};
use rustpython_common::wtf8::{Wtf8, Wtf8Buf, wtf8_concat};
use std::collections::HashMap;

use crate::_datetime::{PyTzInfo, datetime_type, timedelta_from_seconds};
Expand All @@ -22,7 +22,7 @@ mod _zoneinfo {
PyBaseExceptionRef, PyBytes, PyModule, PyStr, PyStrRef, PyTuple, PyType, PyTypeRef,
},
class::StaticType,
function::{FuncArgs, IntoFuncArgs, KwArgs},
function::{ArgIndex, FuncArgs, IntoFuncArgs, KwArgs},
object::{Traverse, TraverseFn},
protocol::{PyIter, PyIterReturn},
types::{Constructor, Representable},
Expand Down Expand Up @@ -265,12 +265,15 @@ mod _zoneinfo {
if !is_base(cls) {
return Ok(());
}
with_cache(vm, |cache| {
let evicted = with_cache(vm, |cache| {
cache.strong.push_front((key, zone));
while cache.strong.len() > STRONG_CACHE_MAX {
cache.strong.pop_back();
}
})
cache
.strong
.split_off(STRONG_CACHE_MAX.min(cache.strong.len()))
})?;
// Dropping a zone or its key can reenter the cache through Python.
drop(evicted);
Ok(())
}

fn strong_cache_eject(cls: &Py<PyType>, key: &PyObject, vm: &VirtualMachine) -> PyResult<()> {
Expand All @@ -279,12 +282,14 @@ mod _zoneinfo {
}
for (cached_key, zone) in strong_entries(vm)? {
if vm.bool_eq(key, &cached_key)? {
with_cache(vm, |cache| {
if let Some(pos) = cache.strong.iter().position(|(_, cached)| cached.is(&zone))
{
cache.strong.remove(pos);
}
let removed = with_cache(vm, |cache| {
cache
.strong
.iter()
.position(|(_, cached)| cached.is(&zone))
.and_then(|pos| cache.strong.remove(pos))
})?;
drop(removed);
return Ok(());
}
}
Expand All @@ -295,7 +300,9 @@ mod _zoneinfo {
if !is_base(cls) {
return Ok(());
}
with_cache(vm, |cache| cache.strong.clear())
let removed = with_cache(vm, |cache| core::mem::take(&mut cache.strong))?;
drop(removed);
Ok(())
}

fn cached_delta(seconds: i64, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
Expand Down Expand Up @@ -334,7 +341,7 @@ mod _zoneinfo {
return existing.clone();
}
cache.weak = Some(weak.clone());
weak
weak.clone()
})
}

Expand Down Expand Up @@ -1201,8 +1208,7 @@ mod _zoneinfo {
base: PyTzInfo,
#[pymember(type = "object_ex")]
key: PyObjectRef,
#[pytraverse(skip)]
file_repr: Option<String>,
file_repr: Option<PyStrRef>,
#[pytraverse(skip)]
source: u8,
data: ZoneDataBox,
Expand All @@ -1225,7 +1231,10 @@ mod _zoneinfo {
fn repr_wtf8(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<Wtf8Buf> {
let name = zelf.class().fully_qualified_name(vm)?;
if vm.is_none(&zelf.key) {
let file = zelf.file_repr.as_deref().unwrap_or("");
let file = zelf
.file_repr
.as_ref()
.map_or_else(|| Wtf8::new(""), |file| file.as_wtf8());
return Ok(wtf8_concat!(name, ".from_file(", file, ")"));
}
let key = zelf.key.repr(vm)?.as_wtf8().to_owned();
Expand Down Expand Up @@ -1276,7 +1285,7 @@ mod _zoneinfo {
args: FromFileArgs,
vm: &VirtualMachine,
) -> PyResult<PyRef<Self>> {
let file_repr = args.file_obj.repr(vm)?.to_string_lossy().into_owned();
let file_repr = args.file_obj.repr(vm)?;
let key = args.key.unwrap_or_else(|| vm.ctx.none());
let data = load_data(&args.file_obj, vm)?;
Self {
Expand Down Expand Up @@ -1377,7 +1386,7 @@ mod _zoneinfo {
Ok(vm
.new_tuple((
constructor,
vm.new_tuple((zelf.key.clone(), vm.ctx.new_bool(from_cache))),
vm.new_tuple((zelf.key.clone(), vm.ctx.new_int(u8::from(from_cache)))),
))
.into())
}
Expand All @@ -1389,12 +1398,17 @@ mod _zoneinfo {
from_cache: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult {
let from_cache = (from_cache.try_index(vm)?.as_u64_mask() as u8) != 0;
if from_cache {
cls.as_object().call((key,), vm)
let use_cache = {
let index = ArgIndex::try_from_object(vm, from_cache.clone())?;
index.as_unsigned_bitfield::<8>(vm)? != 0
};
let result = if use_cache {
cached_new(cls, key, vm)
} else {
Ok(new_instance(cls, key, SOURCE_NOCACHE, vm)?.into())
}
};
drop(from_cache);
result
}

#[pyclassmethod]
Expand Down
25 changes: 8 additions & 17 deletions crates/stdlib/src/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -491,23 +491,14 @@ mod decl {
}

fn epoll_eventmask(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<u32> {
use num_traits::ToPrimitive;

let value = obj.try_index(vm)?;
// Clinic's unsigned-int bitfield conversion accepts signed values too.
if !value
.as_bigint()
.to_i64()
.is_some_and(|value| (i64::from(i32::MIN)..=i64::from(u32::MAX)).contains(&value))
{
crate::vm::stdlib::_warnings::warn(
vm.ctx.exceptions.deprecation_warning,
"integer value out of range".to_owned(),
1,
vm,
)?;
}
Ok(value.as_u32_mask())
use crate::vm::function::ArgIndex;

let result = (|| {
let value = ArgIndex::try_from_object(vm, obj.clone())?;
Ok(value.as_unsigned_bitfield::<32>(vm)? as u32)
})();
drop(obj);
result
}

#[derive(FromArgs)]
Expand Down
16 changes: 1 addition & 15 deletions crates/stdlib/src/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2805,21 +2805,7 @@ mod _socket {
) = args.bind(vm)?;
let optlen = match optlen {
OptionalArg::Present(index) => {
let index = index.as_ref();
// CPython's unsigned-int bitfield conversion masks the value,
// warning only when it fits neither a signed nor unsigned int.
if !index.as_bigint().to_i64().is_some_and(|value| {
(i64::from(i32::MIN)..=i64::from(u32::MAX)).contains(&value)
}) {
crate::vm::warn::warn(
vm.ctx.new_str("integer value out of range").into(),
Some(vm.ctx.exceptions.deprecation_warning.to_owned()),
1,
None,
vm,
)?;
}
OptionalArg::Present(index.as_u32_mask())
OptionalArg::Present(index.as_unsigned_bitfield::<32>(vm)? as u32)
}
OptionalArg::Missing => OptionalArg::Missing,
};
Expand Down
25 changes: 24 additions & 1 deletion crates/vm/src/function/number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::{
use core::ops::Deref;
use malachite_bigint::BigInt;
use num_complex::Complex64;
use num_traits::PrimInt;
use num_traits::{PrimInt, ToPrimitive};

/// A Python complex-like object.
///
Expand Down Expand Up @@ -155,6 +155,29 @@ impl ArgIndex {
pub fn into_int_ref(self) -> PyIntRef {
self.value
}

/// Mask a Clinic unsigned bitfield, warning if neither signed nor unsigned
/// storage of the requested width can represent the original integer.
pub fn as_unsigned_bitfield<const BITS: u32>(&self, vm: &VirtualMachine) -> PyResult<u64> {
const { assert!(BITS > 0 && BITS <= 64) };
let minimum = -(1_i128 << (BITS - 1));
let maximum = (1_i128 << BITS) - 1;
let fits = self
.value
.as_bigint()
.to_i128()
.is_some_and(|value| (minimum..=maximum).contains(&value));
if !fits {
crate::warn::warn(
vm.ctx.new_str("integer value out of range").into(),
Some(vm.ctx.exceptions.deprecation_warning.to_owned()),
1,
None,
vm,
)?;
}
Ok(self.value.as_u64_mask() & (u64::MAX >> (64 - BITS)))
}
}

impl AsRef<Py<PyInt>> for ArgIndex {
Expand Down
Loading