Skip to content

Commit ab37e45

Browse files
committed
BorrowValue for PyString
1 parent a77e78d commit ab37e45

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+392
-347
lines changed

src/shell.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use rustpython_vm::readline::{Readline, ReadlineResult};
66
use rustpython_vm::{
77
exceptions::{print_exception, PyBaseExceptionRef},
88
obj::objtype,
9-
pyobject::PyResult,
9+
pyobject::{BorrowValue, PyResult},
1010
scope::Scope,
1111
VirtualMachine,
1212
};
@@ -61,7 +61,7 @@ pub fn run_shell(vm: &VirtualMachine, scope: Scope) -> PyResult<()> {
6161
.get_attribute(vm.sys_module.clone(), prompt_name)
6262
.and_then(|prompt| vm.to_str(&prompt));
6363
let prompt = match prompt {
64-
Ok(ref s) => s.as_str(),
64+
Ok(ref s) => s.borrow_value(),
6565
Err(_) => "",
6666
};
6767
let result = match repl.readline(prompt) {

src/shell/helper.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use rustpython_vm::obj::objstr::PyStringRef;
2-
use rustpython_vm::pyobject::{PyIterable, PyResult, TryFromObject};
2+
use rustpython_vm::pyobject::{BorrowValue, PyIterable, PyResult, TryFromObject};
33
use rustpython_vm::scope::{NameProtocol, Scope};
44
use rustpython_vm::VirtualMachine;
55

@@ -104,7 +104,7 @@ impl<'vm> ShellHelper<'vm> {
104104
.filter(|res| {
105105
res.as_ref()
106106
.ok()
107-
.map_or(true, |s| s.as_str().starts_with(word_start))
107+
.map_or(true, |s| s.borrow_value().starts_with(word_start))
108108
})
109109
.collect::<Result<Vec<_>, _>>()
110110
.ok()?;
@@ -117,7 +117,7 @@ impl<'vm> ShellHelper<'vm> {
117117
let no_underscore = all_completions
118118
.iter()
119119
.cloned()
120-
.filter(|s| !s.as_str().starts_with('_'))
120+
.filter(|s| !s.borrow_value().starts_with('_'))
121121
.collect::<Vec<_>>();
122122

123123
// if there are only completions that start with a '_', give them all of the
@@ -130,13 +130,13 @@ impl<'vm> ShellHelper<'vm> {
130130
};
131131

132132
// sort the completions alphabetically
133-
completions.sort_by(|a, b| std::cmp::Ord::cmp(a.as_str(), b.as_str()));
133+
completions.sort_by(|a, b| std::cmp::Ord::cmp(a.borrow_value(), b.borrow_value()));
134134

135135
Some((
136136
startpos,
137137
completions
138138
.into_iter()
139-
.map(|s| s.as_str().to_owned())
139+
.map(|s| s.borrow_value().to_owned())
140140
.collect(),
141141
))
142142
}

vm/src/builtins.rs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ mod decl {
7070
#[pyfunction]
7171
fn ascii(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<String> {
7272
let repr = vm.to_repr(&obj)?;
73-
let ascii = to_ascii(repr.as_str());
73+
let ascii = to_ascii(repr.borrow_value());
7474
Ok(ascii)
7575
}
7676

@@ -121,11 +121,11 @@ mod decl {
121121
fn compile(args: CompileArgs, vm: &VirtualMachine) -> PyResult {
122122
// TODO: compile::compile should probably get bytes
123123
let source = match &args.source {
124-
Either::A(string) => string.as_str(),
124+
Either::A(string) => string.borrow_value(),
125125
Either::B(bytes) => std::str::from_utf8(bytes).unwrap(),
126126
};
127127

128-
let mode_str = args.mode.as_str();
128+
let mode_str = args.mode.borrow_value();
129129

130130
let flags = args
131131
.flags
@@ -138,7 +138,7 @@ mod decl {
138138
.parse::<compile::Mode>()
139139
.map_err(|err| vm.new_value_error(err.to_string()))?;
140140

141-
vm.compile(&source, mode, args.filename.as_str().to_owned())
141+
vm.compile(&source, mode, args.filename.borrow_value().to_owned())
142142
.map(|o| o.into_object())
143143
.map_err(|err| vm.new_syntax_error(&err))
144144
} else {
@@ -230,7 +230,7 @@ mod decl {
230230
// Determine code object:
231231
let code_obj = match source {
232232
Either::A(string) => vm
233-
.compile(string.as_str(), mode, "<string>".to_owned())
233+
.compile(string.borrow_value(), mode, "<string>".to_owned())
234234
.map_err(|err| vm.new_syntax_error(&err))?,
235235
Either::B(code_obj) => code_obj,
236236
};
@@ -355,7 +355,7 @@ mod decl {
355355

356356
#[pyfunction]
357357
fn input(prompt: OptionalArg<PyStringRef>, vm: &VirtualMachine) -> PyResult<String> {
358-
let prompt = prompt.as_ref().map_or("", |s| s.as_str());
358+
let prompt = prompt.as_ref().map_or("", |s| s.borrow_value());
359359
let mut readline = Readline::new(());
360360
match readline.readline(prompt) {
361361
ReadlineResult::Line(s) => Ok(s),
@@ -568,7 +568,7 @@ mod decl {
568568
Ok(u32::from(bytes[0]))
569569
}),
570570
Either::B(string) => {
571-
let string = string.as_str();
571+
let string = string.borrow_value();
572572
let string_len = string.chars().count();
573573
if string_len != 1 {
574574
return Err(vm.new_type_error(format!(
@@ -779,7 +779,11 @@ mod decl {
779779
mut kwargs: KwArgs,
780780
vm: &VirtualMachine,
781781
) -> PyResult {
782-
let name = qualified_name.as_str().split('.').next_back().unwrap();
782+
let name = qualified_name
783+
.borrow_value()
784+
.split('.')
785+
.next_back()
786+
.unwrap();
783787
let name_obj = vm.new_str(name.to_owned());
784788

785789
let mut metaclass = if let Some(metaclass) = kwargs.pop_kwarg("metaclass") {

vm/src/cformat.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
/// [https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting]
33
use crate::format::get_num_digits;
44
use crate::obj::{objfloat, objint, objstr, objtuple, objtype};
5-
use crate::pyobject::{ItemProtocol, PyObjectRef, PyResult, TryFromObject, TypeProtocol};
5+
use crate::pyobject::{
6+
BorrowValue, ItemProtocol, PyObjectRef, PyResult, TryFromObject, TypeProtocol,
7+
};
68
use crate::vm::VirtualMachine;
79
use num_bigint::{BigInt, Sign};
810
use num_traits::cast::ToPrimitive;
@@ -295,7 +297,7 @@ impl CFormatSpec {
295297
vm.call_method(&obj.clone(), "decode", vec![])?,
296298
)?,
297299
};
298-
Ok(self.format_string(result.as_str().to_owned()))
300+
Ok(self.format_string(result.borrow_value().to_owned()))
299301
}
300302
CFormatType::Number(number_type) => {
301303
if !objtype::isinstance(&obj, &vm.ctx.types.int_type) {

vm/src/dictdatatype.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
/// And: http://code.activestate.com/recipes/578375/
55
use crate::common::cell::{PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard};
66
use crate::obj::objstr::{PyString, PyStringRef};
7-
use crate::pyobject::{IdProtocol, IntoPyObject, PyObjectRef, PyResult};
7+
use crate::pyobject::{BorrowValue, IdProtocol, IntoPyObject, PyObjectRef, PyResult};
88
use crate::vm::VirtualMachine;
99
use rustpython_common::hash;
1010
use std::collections::HashMap;
@@ -447,7 +447,7 @@ impl DictKey for PyStringRef {
447447
if self.is(other_key) {
448448
Ok(true)
449449
} else if let Some(py_str_value) = other_key.payload::<PyString>() {
450-
Ok(py_str_value.as_str() == self.as_str())
450+
Ok(py_str_value.borrow_value() == self.borrow_value())
451451
} else {
452452
vm.bool_eq(self.clone().into_object(), other_key.clone())
453453
}
@@ -472,7 +472,7 @@ impl DictKey for &str {
472472

473473
fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObjectRef) -> PyResult<bool> {
474474
if let Some(py_str_value) = other_key.payload::<PyString>() {
475-
Ok(py_str_value.as_str() == *self)
475+
Ok(py_str_value.borrow_value() == *self)
476476
} else {
477477
// Fall back to PyObjectRef implementation.
478478
let s = vm.ctx.new_str(*self);

vm/src/frame.rs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ use crate::obj::objtraceback::PyTraceback;
2424
use crate::obj::objtuple::PyTuple;
2525
use crate::obj::objtype::{self, PyClassRef};
2626
use crate::pyobject::{
27-
IdProtocol, ItemProtocol, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol,
27+
BorrowValue, IdProtocol, ItemProtocol, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject,
28+
TypeProtocol,
2829
};
2930
use crate::scope::{NameProtocol, Scope};
3031
use crate::vm::VirtualMachine;
@@ -795,7 +796,7 @@ impl ExecutingFrame<'_> {
795796
if let Some(dict) = module.dict() {
796797
for (k, v) in &dict {
797798
let k = vm.to_str(&k)?;
798-
let k = k.as_str();
799+
let k = k.borrow_value();
799800
if !k.starts_with('_') {
800801
self.scope.store_name(&vm, k, v);
801802
}
@@ -991,7 +992,7 @@ impl ExecutingFrame<'_> {
991992
let key_repr = vm.to_repr(&key)?;
992993
let msg = format!(
993994
"got multiple values for keyword argument {}",
994-
key_repr.as_str()
995+
key_repr.borrow_value()
995996
);
996997
return Err(vm.new_type_error(msg));
997998
}
@@ -1066,7 +1067,7 @@ impl ExecutingFrame<'_> {
10661067
let mut kwargs = IndexMap::new();
10671068
for (key, value) in kw_dict.into_iter() {
10681069
if let Some(key) = key.payload_if_subclass::<objstr::PyString>(vm) {
1069-
kwargs.insert(key.as_str().to_owned(), value);
1070+
kwargs.insert(key.borrow_value().to_owned(), value);
10701071
} else {
10711072
return Err(vm.new_type_error("keywords must be strings".to_owned()));
10721073
}
@@ -1285,7 +1286,11 @@ impl ExecutingFrame<'_> {
12851286
.ctx
12861287
.new_pyfunction(code_obj, scope, defaults, kw_only_defaults);
12871288

1288-
let name = qualified_name.as_str().split('.').next_back().unwrap();
1289+
let name = qualified_name
1290+
.borrow_value()
1291+
.split('.')
1292+
.next_back()
1293+
.unwrap();
12891294
vm.set_attr(&func_obj, "__name__", vm.new_str(name.to_owned()))?;
12901295
vm.set_attr(&func_obj, "__qualname__", qualified_name)?;
12911296
let module = self

vm/src/obj/objbool.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ impl PyBool {
103103
format_spec: PyStringRef,
104104
vm: &VirtualMachine,
105105
) -> PyResult<PyStringRef> {
106-
if format_spec.as_str().is_empty() {
106+
if format_spec.borrow_value().is_empty() {
107107
vm.to_str(&obj)
108108
} else {
109109
Err(vm.new_type_error("unsupported format string passed to bool.__format__".to_owned()))

vm/src/obj/objbytearray.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ impl PyByteArray {
256256

257257
#[pymethod]
258258
fn fromhex(string: PyStringRef, vm: &VirtualMachine) -> PyResult<PyByteArray> {
259-
Ok(PyBytesInner::fromhex(string.as_str(), vm)?.into())
259+
Ok(PyBytesInner::fromhex(string.borrow_value(), vm)?.into())
260260
}
261261

262262
#[pymethod(name = "center")]
@@ -590,7 +590,7 @@ impl PyByteArray {
590590
vm.new_type_error(format!(
591591
"'{}' decoder returned '{}' instead of 'str'; use codecs.encode() to \
592592
encode arbitrary types",
593-
encoding.as_ref().map_or("utf-8", |s| s.as_str()),
593+
encoding.as_ref().map_or("utf-8", |s| s.borrow_value()),
594594
obj.lease_class().name,
595595
))
596596
})

vm/src/obj/objbytes.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ impl PyBytes {
238238

239239
#[pymethod]
240240
fn fromhex(string: PyStringRef, vm: &VirtualMachine) -> PyResult<PyBytes> {
241-
Ok(PyBytesInner::fromhex(string.as_str(), vm)?.into())
241+
Ok(PyBytesInner::fromhex(string.borrow_value(), vm)?.into())
242242
}
243243

244244
#[pymethod(name = "center")]
@@ -481,7 +481,7 @@ impl PyBytes {
481481
vm.new_type_error(format!(
482482
"'{}' decoder returned '{}' instead of 'str'; use codecs.encode() to \
483483
encode arbitrary types",
484-
encoding.as_ref().map_or("utf-8", |s| s.as_str()),
484+
encoding.as_ref().map_or("utf-8", |s| s.borrow_value()),
485485
obj.lease_class().name,
486486
))
487487
})

vm/src/obj/objcomplex.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ impl PyComplex {
245245
"complex() can't take second arg if first is a string".to_owned(),
246246
));
247247
}
248-
let value = Complex64::from_str(s.as_str())
248+
let value = Complex64::from_str(s.borrow_value())
249249
.map_err(|err| vm.new_value_error(err.to_string()))?;
250250
return PyComplex { value }.into_ref_with_type(vm, cls);
251251
}

0 commit comments

Comments
 (0)