Skip to content

socket2 Part 1, some necessary but miscellaneous changes that aren't directly related to socket #1574

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 28, 2019
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
3 changes: 3 additions & 0 deletions tests/snippets/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,3 +324,6 @@ def try_mutate_str():
assert not "a".__ne__("a")
assert not "".__ne__("")
assert "".__ne__(1) == NotImplemented

assert "A_B".isupper()
assert "a_b".islower()
7 changes: 7 additions & 0 deletions vm/src/obj/objdict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ impl PyDictRef {
for (key, value) in dict_obj {
dict.borrow_mut().insert(vm, &key, value)?;
}
} else if let Some(keys) = vm.get_method(dict_obj.clone(), "keys") {
let keys = objiter::get_iter(vm, &vm.invoke(&keys?, vec![])?)?;
while let Some(key) = objiter::get_next_object(vm, &keys)? {
let val = dict_obj.get_item(&key, vm)?;
dict.borrow_mut().insert(vm, &key, val)?;
}
} else {
let iter = objiter::get_iter(vm, &dict_obj)?;
loop {
Expand All @@ -85,6 +91,7 @@ impl PyDictRef {
}
}
}

let mut dict_borrowed = dict.borrow_mut();
for (key, value) in kwargs.into_iter() {
dict_borrowed.insert(vm, &vm.new_str(key), value)?;
Expand Down
30 changes: 30 additions & 0 deletions vm/src/obj/objmappingproxy.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use super::objiter;
use super::objstr::PyStringRef;
use super::objtype::{self, PyClassRef};
use crate::function::OptionalArg;
Expand Down Expand Up @@ -78,6 +79,35 @@ impl PyMappingProxy {
MappingProxyInner::Dict(obj) => vm._membership(obj.clone(), key),
}
}

#[pymethod(name = "__iter__")]
pub fn iter(&self, vm: &VirtualMachine) -> PyResult {
match &self.mapping {
MappingProxyInner::Dict(d) => objiter::get_iter(vm, d),
MappingProxyInner::Class(_c) => Err(vm.new_type_error("Can't get iter".to_string())),
}
}
#[pymethod]
pub fn items(&self, vm: &VirtualMachine) -> PyResult {
match &self.mapping {
MappingProxyInner::Dict(d) => vm.call_method(d, "items", vec![]),
MappingProxyInner::Class(_c) => Err(vm.new_type_error("Can't get iter".to_string())),
}
}
#[pymethod]
pub fn keys(&self, vm: &VirtualMachine) -> PyResult {
match &self.mapping {
MappingProxyInner::Dict(d) => vm.call_method(d, "keys", vec![]),
MappingProxyInner::Class(_c) => Err(vm.new_type_error("Can't get iter".to_string())),
}
}
#[pymethod]
pub fn values(&self, vm: &VirtualMachine) -> PyResult {
match &self.mapping {
MappingProxyInner::Dict(d) => vm.call_method(d, "values", vec![]),
MappingProxyInner::Class(_c) => Err(vm.new_type_error("Can't get iter".to_string())),
}
}
}

pub fn init(context: &PyContext) {
Expand Down
5 changes: 3 additions & 2 deletions vm/src/obj/objstr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -727,11 +727,12 @@ impl PyString {

#[pymethod]
fn isupper(&self, _vm: &VirtualMachine) -> bool {
// TODO: assert not " ".isupper(), assert not "_".isupper()
!self.value.is_empty()
&& self
.value
.chars()
.filter(|x| !x.is_ascii_whitespace())
.filter(|x| !x.is_ascii_whitespace() && *x != '_')
.all(char::is_uppercase)
}

Expand All @@ -741,7 +742,7 @@ impl PyString {
&& self
.value
.chars()
.filter(|x| !x.is_ascii_whitespace())
.filter(|x| !x.is_ascii_whitespace() && *x != '_')
.all(char::is_lowercase)
}

Expand Down
2 changes: 1 addition & 1 deletion vm/src/obj/objsuper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ impl PySuper {
// This is a classmethod
return Ok(item);
}
return Ok(vm.ctx.new_bound_method(item, inst.clone()));
return vm.call_get_descriptor(item, inst.clone());
}
}
Err(vm.new_attribute_error(format!(
Expand Down
31 changes: 9 additions & 22 deletions vm/src/stdlib/time_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,11 @@ use crate::vm::VirtualMachine;
#[cfg(unix)]
fn time_sleep(seconds: f64, vm: &VirtualMachine) -> PyResult<()> {
// this is basically std::thread::sleep, but that catches interrupts and we don't want to
let secs = seconds.trunc() as u64;
let nsecs = (seconds.fract() * 1e9) as i64;
let dur = Duration::from_secs_f64(seconds);

let mut ts = libc::timespec {
tv_sec: std::cmp::min(libc::time_t::max_value() as u64, secs) as libc::time_t,
tv_nsec: nsecs,
tv_sec: std::cmp::min(libc::time_t::max_value() as u64, dur.as_secs()) as libc::time_t,
tv_nsec: dur.subsec_nanos().into(),
};
let res = unsafe { libc::nanosleep(&ts, &mut ts) };
let interrupted = res == -1 && nix::errno::errno() == libc::EINTR;
Expand All @@ -39,20 +38,13 @@ fn time_sleep(seconds: f64, vm: &VirtualMachine) -> PyResult<()> {

#[cfg(not(unix))]
fn time_sleep(seconds: f64, _vm: &VirtualMachine) {
let secs: u64 = seconds.trunc() as u64;
let nanos: u32 = (seconds.fract() * 1e9) as u32;
let duration = Duration::new(secs, nanos);
std::thread::sleep(duration);
}

fn duration_to_f64(d: Duration) -> f64 {
(d.as_secs() as f64) + (f64::from(d.subsec_nanos()) / 1e9)
std::thread::sleep(Duration::from_secs_f64(seconds));
}

#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
pub fn get_time() -> f64 {
match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(v) => duration_to_f64(v),
Ok(v) => v.as_secs_f64(),
Err(err) => panic!("Time error: {:?}", err),
}
}
Expand All @@ -77,22 +69,17 @@ fn time_time(_vm: &VirtualMachine) -> f64 {
fn time_monotonic(_vm: &VirtualMachine) -> f64 {
// TODO: implement proper monotonic time!
match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(v) => duration_to_f64(v),
Ok(v) => v.as_secs_f64(),
Err(err) => panic!("Time error: {:?}", err),
}
}

fn pyfloat_to_secs_and_nanos(seconds: f64) -> (i64, u32) {
let secs: i64 = seconds.trunc() as i64;
let nanos: u32 = (seconds.fract() * 1e9) as u32;
(secs, nanos)
}

fn pyobj_to_naive_date_time(value: Either<f64, i64>) -> NaiveDateTime {
match value {
Either::A(float) => {
let (seconds, nanos) = pyfloat_to_secs_and_nanos(float);
NaiveDateTime::from_timestamp(seconds, nanos)
let secs = float.trunc() as i64;
let nsecs = (float.fract() * 1e9) as u32;
NaiveDateTime::from_timestamp(secs, nsecs)
}
Either::B(int) => NaiveDateTime::from_timestamp(int, 0),
}
Expand Down