Skip to content

Commit 7a8045f

Browse files
committed
BorrowValue for PyInt and PyList
1 parent 7d75c4e commit 7a8045f

26 files changed

Lines changed: 185 additions & 172 deletions

src/main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use rustpython_vm::{
1010
exceptions::print_exception,
1111
match_class,
1212
obj::{objint::PyInt, objtype},
13-
pyobject::{ItemProtocol, PyResult},
13+
pyobject::{BorrowValue, ItemProtocol, PyResult},
1414
scope::Scope,
1515
util, InitParameter, PySettings, VirtualMachine,
1616
};
@@ -57,7 +57,7 @@ fn main() {
5757
1 => match_class!(match args.as_slice()[0].clone() {
5858
i @ PyInt => {
5959
use num_traits::cast::ToPrimitive;
60-
process::exit(i.as_bigint().to_i32().unwrap_or(0));
60+
process::exit(i.borrow_value().to_i32().unwrap_or(0));
6161
}
6262
arg => {
6363
if vm.is_none(&arg) {

vm/src/builtins.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ mod decl {
2828
use crate::obj::objstr::{PyString, PyStringRef};
2929
use crate::obj::objtype::{self, PyClassRef};
3030
use crate::pyobject::{
31-
Either, IdProtocol, ItemProtocol, PyCallable, PyIterable, PyObjectRef, PyResult, PyValue,
32-
TryFromObject, TypeProtocol,
31+
BorrowValue, Either, IdProtocol, ItemProtocol, PyCallable, PyIterable, PyObjectRef,
32+
PyResult, PyValue, TryFromObject, TypeProtocol,
3333
};
3434
use crate::readline::{Readline, ReadlineResult};
3535
use crate::scope::Scope;
@@ -76,7 +76,7 @@ mod decl {
7676

7777
#[pyfunction]
7878
fn bin(x: PyIntRef) -> String {
79-
let x = x.as_bigint();
79+
let x = x.borrow_value();
8080
if x.is_negative() {
8181
format!("-0b{:b}", x.abs())
8282
} else {
@@ -338,7 +338,7 @@ mod decl {
338338

339339
#[pyfunction]
340340
fn hex(number: PyIntRef, vm: &VirtualMachine) -> PyResult {
341-
let n = number.as_bigint();
341+
let n = number.borrow_value();
342342
let s = if n.is_negative() {
343343
format!("-0x{:x}", -n)
344344
} else {
@@ -544,7 +544,7 @@ mod decl {
544544

545545
#[pyfunction]
546546
fn oct(number: PyIntRef, vm: &VirtualMachine) -> PyResult {
547-
let n = number.as_bigint();
547+
let n = number.borrow_value();
548548
let s = if n.is_negative() {
549549
format!("-0o{:o}", n.abs())
550550
} else {
@@ -616,7 +616,7 @@ mod decl {
616616
.to_owned(),
617617
));
618618
}
619-
let m = m.as_bigint();
619+
let m = m.borrow_value();
620620
if m.is_zero() {
621621
return Err(vm.new_value_error("pow() 3rd argument cannot be 0".to_owned()));
622622
}

vm/src/bytesinner.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ use crate::obj::objsequence::{PySliceableSequence, SequenceIndex};
1515
use crate::obj::objslice::PySliceRef;
1616
use crate::obj::objstr::{self, PyString, PyStringRef};
1717
use crate::pyobject::{
18-
Either, PyComparisonValue, PyIterable, PyObjectRef, PyResult, TryFromObject, TypeProtocol,
18+
BorrowValue, Either, PyComparisonValue, PyIterable, PyObjectRef, PyResult, TryFromObject,
19+
TypeProtocol,
1920
};
2021
use crate::pystr::{self, PyCommonString, PyCommonStringContainer, PyCommonStringWrapper};
2122
use crate::vm::VirtualMachine;
@@ -165,7 +166,7 @@ impl ByteInnerFindOptions {
165166
) -> PyResult<(Vec<u8>, std::ops::Range<usize>)> {
166167
let sub = match self.sub {
167168
Either::A(v) => v.elements.to_vec(),
168-
Either::B(int) => vec![int.as_bigint().byte_or(vm)?],
169+
Either::B(int) => vec![int.borrow_value().byte_or(vm)?],
169170
};
170171
let range = pystr::adjust_indices(self.start, self.end, len);
171172
Ok((sub, range))
@@ -304,7 +305,7 @@ impl PyBytesInner {
304305
) -> PyResult<bool> {
305306
Ok(match needle {
306307
Either::A(byte) => self.elements.contains_str(byte.elements.as_slice()),
307-
Either::B(int) => self.elements.contains(&int.as_bigint().byte_or(vm)?),
308+
Either::B(int) => self.elements.contains(&int.borrow_value().byte_or(vm)?),
308309
})
309310
}
310311

@@ -327,7 +328,7 @@ impl PyBytesInner {
327328
if let Some(idx) = self.elements.get_pos(int) {
328329
let result = match_class!(match object {
329330
i @ PyInt => {
330-
if let Some(value) = i.as_bigint().to_u8() {
331+
if let Some(value) = i.borrow_value().to_u8() {
331332
Ok(value)
332333
} else {
333334
Err(vm.new_value_error("byte must be in range(0, 256)".to_owned()))

vm/src/macros.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,13 +116,13 @@ macro_rules! py_namespace {
116116
/// use rustpython_vm::match_class;
117117
/// use rustpython_vm::obj::objfloat::PyFloat;
118118
/// use rustpython_vm::obj::objint::PyInt;
119-
/// use rustpython_vm::pyobject::PyValue;
119+
/// use rustpython_vm::pyobject::{PyValue, BorrowValue};
120120
///
121121
/// let vm: VirtualMachine = Default::default();
122122
/// let obj = PyInt::from(0).into_ref(&vm).into_object();
123123
///
124124
/// let int_value = match_class!(match obj {
125-
/// i @ PyInt => i.as_bigint().clone(),
125+
/// i @ PyInt => i.borrow_value().clone(),
126126
/// f @ PyFloat => f.to_f64().to_bigint().unwrap(),
127127
/// obj => panic!("non-numeric object {}", obj),
128128
/// });

vm/src/obj/objbool.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ use num_traits::Zero;
33

44
use crate::function::{OptionalArg, PyFuncArgs};
55
use crate::pyobject::{
6-
IdProtocol, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyResult, TryFromObject,
7-
TypeProtocol,
6+
BorrowValue, IdProtocol, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyResult,
7+
TryFromObject, TypeProtocol,
88
};
99
use crate::vm::VirtualMachine;
1010

@@ -59,7 +59,7 @@ pub fn boolval(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<bool> {
5959
let bool_obj = vm.invoke(&method, PyFuncArgs::default())?;
6060
match bool_obj.payload::<PyInt>() {
6161
Some(int_obj) => {
62-
let len_val = int_obj.as_bigint();
62+
let len_val = int_obj.borrow_value();
6363
if len_val.sign() == Sign::Minus {
6464
return Err(
6565
vm.new_value_error("__len__() should return >= 0".to_owned())
@@ -185,7 +185,7 @@ pub fn not(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<bool> {
185185

186186
// Retrieve inner int value:
187187
pub fn get_value(obj: &PyObjectRef) -> bool {
188-
!obj.payload::<PyInt>().unwrap().as_bigint().is_zero()
188+
!obj.payload::<PyInt>().unwrap().borrow_value().is_zero()
189189
}
190190

191191
pub fn get_py_int(obj: &PyObjectRef) -> &PyInt {

vm/src/obj/objbytearray.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ use crate::bytesinner::{
1616
use crate::common::cell::{PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard};
1717
use crate::function::{OptionalArg, OptionalOption};
1818
use crate::pyobject::{
19-
Either, PyClassImpl, PyComparisonValue, PyContext, PyIterable, PyObjectRef, PyRef, PyResult,
20-
PyValue, TryFromObject, TypeProtocol,
19+
BorrowValue, Either, PyClassImpl, PyComparisonValue, PyContext, PyIterable, PyObjectRef, PyRef,
20+
PyResult, PyValue, TryFromObject, TypeProtocol,
2121
};
2222
use crate::pystr::{self, PyCommonString};
2323
use crate::vm::VirtualMachine;
@@ -338,7 +338,7 @@ impl PyByteArray {
338338

339339
#[pymethod(name = "remove")]
340340
fn remove(&self, x: PyIntRef, vm: &VirtualMachine) -> PyResult<()> {
341-
let x = x.as_bigint().byte_or(vm)?;
341+
let x = x.borrow_value().byte_or(vm)?;
342342

343343
let bytes = &mut self.borrow_value_mut().elements;
344344
let pos = bytes
@@ -480,7 +480,7 @@ impl PyByteArray {
480480
fn append(&self, x: PyIntRef, vm: &VirtualMachine) -> PyResult<()> {
481481
self.borrow_value_mut()
482482
.elements
483-
.push(x.as_bigint().byte_or(vm)?);
483+
.push(x.borrow_value().byte_or(vm)?);
484484
Ok(())
485485
}
486486

@@ -489,7 +489,7 @@ impl PyByteArray {
489489
for x in iterable_of_ints.iter(vm)? {
490490
let x = x?;
491491
let x = PyIntRef::try_from_object(vm, x)?;
492-
let x = x.as_bigint().byte_or(vm)?;
492+
let x = x.borrow_value().byte_or(vm)?;
493493
self.borrow_value_mut().elements.push(x);
494494
}
495495

@@ -504,7 +504,7 @@ impl PyByteArray {
504504
.to_isize()
505505
.ok_or_else(|| vm.new_overflow_error("bytearray too big".to_owned()))?;
506506

507-
let x = x.as_bigint().byte_or(vm)?;
507+
let x = x.borrow_value().byte_or(vm)?;
508508

509509
if index >= len {
510510
bytes.push(x);

vm/src/obj/objcomplex.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ use super::objstr::PyString;
99
use super::objtype::PyClassRef;
1010
use crate::function::OptionalArg;
1111
use crate::pyobject::{
12-
IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol,
12+
BorrowValue, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue,
13+
TypeProtocol,
1314
};
1415
use crate::vm::VirtualMachine;
1516
use rustpython_common::hash;
@@ -233,7 +234,7 @@ impl PyComplex {
233234
OptionalArg::Missing => 0.0,
234235
OptionalArg::Present(obj) => match_class!(match obj {
235236
i @ PyInt => {
236-
objint::try_float(i.as_bigint(), vm)?
237+
objint::try_float(i.borrow_value(), vm)?
237238
}
238239
f @ PyFloat => {
239240
f.to_f64()

vm/src/obj/objenumerate.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use super::objint::PyIntRef;
88
use super::objiter;
99
use super::objtype::PyClassRef;
1010
use crate::function::OptionalArg;
11-
use crate::pyobject::{PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
11+
use crate::pyobject::{BorrowValue, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
1212
use crate::vm::VirtualMachine;
1313

1414
#[pyclass]
@@ -35,7 +35,7 @@ impl PyEnumerate {
3535
vm: &VirtualMachine,
3636
) -> PyResult<PyEnumerateRef> {
3737
let counter = match start {
38-
OptionalArg::Present(start) => start.as_bigint().clone(),
38+
OptionalArg::Present(start) => start.borrow_value().clone(),
3939
OptionalArg::Missing => BigInt::zero(),
4040
};
4141

vm/src/obj/objfloat.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ use super::objtype::PyClassRef;
1010
use crate::format::FormatSpec;
1111
use crate::function::{OptionalArg, OptionalOption};
1212
use crate::pyobject::{
13-
IntoPyObject, IntoPyResult, PyArithmaticValue::*, PyClassImpl, PyComparisonValue, PyContext,
14-
PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol,
13+
BorrowValue, IntoPyObject, IntoPyResult, PyArithmaticValue::*, PyClassImpl, PyComparisonValue,
14+
PyContext, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol,
1515
};
1616
use crate::vm::VirtualMachine;
1717
use rustpython_common::{float_ops, hash};
@@ -56,7 +56,7 @@ pub fn try_float(obj: &PyObjectRef, vm: &VirtualMachine) -> PyResult<Option<f64>
5656
let v = if let Some(float) = obj.payload_if_subclass::<PyFloat>(vm) {
5757
Some(float.value)
5858
} else if let Some(int) = obj.payload_if_subclass::<PyInt>(vm) {
59-
Some(objint::try_float(int.as_bigint(), vm)?)
59+
Some(objint::try_float(int.borrow_value(), vm)?)
6060
} else {
6161
None
6262
};
@@ -179,7 +179,7 @@ impl PyFloat {
179179
if let Some(other) = other.payload_if_subclass::<PyFloat>(vm) {
180180
Implemented(float_op(self.value, other.value))
181181
} else if let Some(other) = other.payload_if_subclass::<PyInt>(vm) {
182-
Implemented(int_op(self.value, other.as_bigint()))
182+
Implemented(int_op(self.value, other.borrow_value()))
183183
} else {
184184
NotImplemented
185185
}
@@ -399,7 +399,7 @@ impl PyFloat {
399399
fn round(&self, ndigits: OptionalOption<PyIntRef>, vm: &VirtualMachine) -> PyResult {
400400
let ndigits = ndigits.flatten();
401401
if let Some(ndigits) = ndigits {
402-
let ndigits = ndigits.as_bigint();
402+
let ndigits = ndigits.borrow_value();
403403
if ndigits.is_zero() {
404404
let fract = self.value.fract();
405405
let value = if (fract.abs() - 0.5).abs() < std::f64::EPSILON {
@@ -523,7 +523,7 @@ fn to_float(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<f64> {
523523
let value = if let Some(float) = obj.payload_if_subclass::<PyFloat>(vm) {
524524
float.value
525525
} else if let Some(int) = obj.payload_if_subclass::<PyInt>(vm) {
526-
objint::try_float(int.as_bigint(), vm)?
526+
objint::try_float(int.borrow_value(), vm)?
527527
} else if let Some(s) = obj.payload_if_subclass::<PyString>(vm) {
528528
float_ops::parse_str(s.as_str().trim()).ok_or_else(|| {
529529
vm.new_value_error(format!("could not convert string to float: '{}'", s))

vm/src/obj/objint.rs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use crate::format::FormatSpec;
1919
use crate::function::{OptionalArg, PyFuncArgs};
2020
use crate::pyobject::{
2121
IdProtocol, IntoPyObject, IntoPyResult, PyArithmaticValue, PyClassImpl, PyComparisonValue,
22-
PyContext, PyObject, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol,
22+
PyContext, PyObject, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol, BorrowValue
2323
};
2424
use crate::stdlib::array::PyArray;
2525
use crate::vm::VirtualMachine;
@@ -53,8 +53,10 @@ impl fmt::Display for PyInt {
5353

5454
pub type PyIntRef = PyRef<PyInt>;
5555

56-
impl PyInt {
57-
pub fn as_bigint(&self) -> &BigInt {
56+
impl<'a> BorrowValue<'a> for PyInt {
57+
type Borrowed = &'a BigInt;
58+
59+
fn borrow_value(&'a self) -> Self::Borrowed {
5860
&self.value
5961
}
6062
}
@@ -261,7 +263,7 @@ impl PyInt {
261263
base.lease_class().name
262264
)))
263265
})?
264-
.as_bigint()
266+
.borrow_value()
265267
.to_u32()
266268
.filter(|&v| v == 0 || (2..=36).contains(&v))
267269
.ok_or_else(|| {
@@ -635,12 +637,12 @@ impl PyInt {
635637
false
636638
};
637639

638-
let value = self.as_bigint();
640+
let value = self.borrow_value();
639641
if value.sign() == Sign::Minus && !signed {
640642
return Err(vm.new_overflow_error("can't convert negative int to unsigned".to_owned()));
641643
}
642644

643-
let byte_len = if let Some(byte_len) = args.length.as_bigint().to_usize() {
645+
let byte_len = if let Some(byte_len) = args.length.borrow_value().to_usize() {
644646
byte_len
645647
} else {
646648
return Err(
@@ -785,7 +787,7 @@ pub(crate) fn to_int(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<BigInt>
785787
})?;
786788
let result = vm.invoke(&method, PyFuncArgs::default())?;
787789
return match result.payload::<PyInt>() {
788-
Some(int_obj) => Ok(int_obj.as_bigint().clone()),
790+
Some(int_obj) => Ok(int_obj.borrow_value().clone()),
789791
None => Err(vm.new_type_error(format!(
790792
"TypeError: __int__ returned non-int (type '{}')",
791793
result.class().name

0 commit comments

Comments
 (0)