Skip to content

Commit 13914e0

Browse files
committed
objstr::get_value -> objstr::clone_value
because the previous naming gives unclear performance estimation to users especially comparing to objstr::borrow_value
1 parent 31d3fc6 commit 13914e0

File tree

11 files changed

+50
-56
lines changed

11 files changed

+50
-56
lines changed

vm/src/frame.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,7 @@ impl Frame {
301301
let s = self
302302
.pop_multiple(*size)
303303
.into_iter()
304-
.map(|pyobj| objstr::get_value(&pyobj))
304+
.map(|pyobj| objstr::clone_value(&pyobj))
305305
.collect::<String>();
306306
let str_obj = vm.ctx.new_str(s);
307307
self.push_value(str_obj);
@@ -929,7 +929,7 @@ impl Frame {
929929
let kwarg_names = vm
930930
.extract_elements(&kwarg_names)?
931931
.iter()
932-
.map(|pyobj| objstr::get_value(pyobj))
932+
.map(|pyobj| objstr::clone_value(pyobj))
933933
.collect();
934934
PyFuncArgs::new(args, kwarg_names)
935935
}
@@ -939,7 +939,7 @@ impl Frame {
939939
self.pop_value().downcast().expect("Kwargs must be a dict.");
940940
kw_dict
941941
.into_iter()
942-
.map(|elem| (objstr::get_value(&elem.0), elem.1))
942+
.map(|elem| (objstr::clone_value(&elem.0), elem.1))
943943
.collect()
944944
} else {
945945
IndexMap::new()

vm/src/obj/objdict.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -332,7 +332,7 @@ impl PyDictRef {
332332
pub fn to_attributes(self) -> PyAttributes {
333333
let mut attrs = PyAttributes::new();
334334
for (key, value) in self {
335-
let key = objstr::get_value(&key);
335+
let key = objstr::clone_value(&key);
336336
attrs.insert(key, value);
337337
}
338338
attrs

vm/src/obj/objstr.rs

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,7 @@ impl PyString {
214214
#[pymethod(name = "__add__")]
215215
fn add(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult<String> {
216216
if objtype::isinstance(&rhs, &vm.ctx.str_type()) {
217-
Ok(format!("{}{}", self.value, get_value(&rhs)))
217+
Ok(format!("{}{}", self.value, borrow_value(&rhs)))
218218
} else {
219219
Err(vm.new_type_error(format!("Cannot add {} and {}", self, rhs)))
220220
}
@@ -228,7 +228,7 @@ impl PyString {
228228
#[pymethod(name = "__eq__")]
229229
fn eq(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
230230
if objtype::isinstance(&rhs, &vm.ctx.str_type()) {
231-
vm.new_bool(self.value == get_value(&rhs))
231+
vm.new_bool(self.value == borrow_value(&rhs))
232232
} else {
233233
vm.ctx.not_implemented()
234234
}
@@ -237,7 +237,7 @@ impl PyString {
237237
#[pymethod(name = "__ne__")]
238238
fn ne(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
239239
if objtype::isinstance(&rhs, &vm.ctx.str_type()) {
240-
vm.new_bool(self.value != get_value(&rhs))
240+
vm.new_bool(self.value != borrow_value(&rhs))
241241
} else {
242242
vm.ctx.not_implemented()
243243
}
@@ -623,8 +623,8 @@ impl PyString {
623623
actual_type
624624
)));
625625
}
626-
let format_string_text = get_value(zelf);
627-
match FormatString::from_str(format_string_text.as_str()) {
626+
let format_string_text = borrow_value(zelf);
627+
match FormatString::from_str(format_string_text) {
628628
Ok(format_string) => perform_format(vm, &format_string, &args),
629629
Err(err) => match err {
630630
FormatParseError::UnmatchedBracket => {
@@ -649,8 +649,8 @@ impl PyString {
649649
}
650650

651651
let zelf = &args.args[0];
652-
let format_string_text = get_value(zelf);
653-
match FormatString::from_str(format_string_text.as_str()) {
652+
let format_string_text = borrow_value(zelf);
653+
match FormatString::from_str(format_string_text) {
654654
Ok(format_string) => perform_format_map(vm, &format_string, &args.args[1]),
655655
Err(err) => match err {
656656
FormatParseError::UnmatchedBracket => {
@@ -1288,7 +1288,7 @@ pub fn init(ctx: &PyContext) {
12881288
PyStringReverseIterator::extend_class(ctx, &ctx.types.strreverseiterator_type);
12891289
}
12901290

1291-
pub fn get_value(obj: &PyObjectRef) -> String {
1291+
pub fn clone_value(obj: &PyObjectRef) -> String {
12921292
obj.payload::<PyString>().unwrap().value.clone()
12931293
}
12941294

@@ -1341,7 +1341,7 @@ fn do_cformat_specifier(
13411341
CFormatPreconversor::Ascii => vm.call_method(&obj.clone(), "__repr__", vec![])?,
13421342
CFormatPreconversor::Bytes => vm.call_method(&obj.clone(), "decode", vec![])?,
13431343
};
1344-
Ok(format_spec.format_string(get_value(&result)))
1344+
Ok(format_spec.format_string(clone_value(&result)))
13451345
}
13461346
CFormatType::Number(_) => {
13471347
if !objtype::isinstance(&obj, &vm.ctx.int_type()) {
@@ -1384,7 +1384,7 @@ fn do_cformat_specifier(
13841384
}
13851385
}
13861386
} else if objtype::isinstance(&obj, &vm.ctx.str_type()) {
1387-
let s: String = get_value(&obj);
1387+
let s = borrow_value(&obj);
13881388
let num_chars = s.chars().count();
13891389
if num_chars != 1 {
13901390
Err(vm.new_type_error("%c requires int or char".to_string()))
@@ -1573,7 +1573,7 @@ fn perform_format(
15731573
}
15741574
};
15751575
auto_argument_index += 1;
1576-
get_value(&result)
1576+
clone_value(&result)
15771577
}
15781578
FormatPart::IndexSpec(index, format_spec) => {
15791579
let result = match arguments.args.get(*index + 1) {
@@ -1582,7 +1582,7 @@ fn perform_format(
15821582
return Err(vm.new_index_error("tuple index out of range".to_string()));
15831583
}
15841584
};
1585-
get_value(&result)
1585+
clone_value(&result)
15861586
}
15871587
FormatPart::KeywordSpec(keyword, format_spec) => {
15881588
let result = match arguments.get_optional_kwarg(&keyword) {
@@ -1591,7 +1591,7 @@ fn perform_format(
15911591
return Err(vm.new_key_error(vm.new_str(keyword.to_string())));
15921592
}
15931593
};
1594-
get_value(&result)
1594+
clone_value(&result)
15951595
}
15961596
FormatPart::Literal(literal) => literal.clone(),
15971597
};
@@ -1616,7 +1616,7 @@ fn perform_format_map(
16161616
FormatPart::KeywordSpec(keyword, format_spec) => {
16171617
let argument = dict.get_item(keyword, &vm)?;
16181618
let result = call_object_format(vm, argument.clone(), &format_spec)?;
1619-
get_value(&result)
1619+
clone_value(&result)
16201620
}
16211621
FormatPart::Literal(literal) => literal.clone(),
16221622
};

vm/src/py_serde.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ impl<'s> serde::Serialize for PyObjectSerializer<'s> {
6767
seq.end()
6868
};
6969
if objtype::isinstance(self.pyobject, &self.vm.ctx.str_type()) {
70-
serializer.serialize_str(&objstr::get_value(&self.pyobject))
70+
serializer.serialize_str(objstr::borrow_value(&self.pyobject))
7171
} else if objtype::isinstance(self.pyobject, &self.vm.ctx.float_type()) {
7272
serializer.serialize_f64(objfloat::get_value(self.pyobject))
7373
} else if objtype::isinstance(self.pyobject, &self.vm.ctx.bool_type()) {

vm/src/stdlib/csv.rs

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -29,34 +29,30 @@ struct ReaderOption {
2929

3030
impl ReaderOption {
3131
fn new(args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<Self> {
32-
let delimiter = {
33-
let bytes = args
34-
.get_optional_kwarg("delimiter")
35-
.map_or(",".to_string(), |pyobj| objstr::get_value(&pyobj))
36-
.into_bytes();
37-
32+
let delimiter = if let Some(delimiter) = args.get_optional_kwarg("delimiter") {
33+
let bytes = objstr::borrow_value(&delimiter).as_bytes();
3834
match bytes.len() {
3935
1 => bytes[0],
4036
_ => {
4137
let msg = r#""delimiter" must be a 1-character string"#;
4238
return Err(vm.new_type_error(msg.to_string()));
4339
}
4440
}
41+
} else {
42+
b','
4543
};
4644

47-
let quotechar = {
48-
let bytes = args
49-
.get_optional_kwarg("quotechar")
50-
.map_or("\"".to_string(), |pyobj| objstr::get_value(&pyobj))
51-
.into_bytes();
52-
45+
let quotechar = if let Some(quotechar) = args.get_optional_kwarg("quotechar") {
46+
let bytes = objstr::borrow_value(&quotechar).as_bytes();
5347
match bytes.len() {
5448
1 => bytes[0],
5549
_ => {
5650
let msg = r#""quotechar" must be a 1-character string"#;
5751
return Err(vm.new_type_error(msg.to_string()));
5852
}
5953
}
54+
} else {
55+
b'"'
6056
};
6157

6258
Ok(ReaderOption {

vm/src/stdlib/imp.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ fn imp_is_frozen(name: PyStringRef, vm: &VirtualMachine) -> bool {
3535

3636
fn imp_create_builtin(spec: PyObjectRef, vm: &VirtualMachine) -> PyResult {
3737
let sys_modules = vm.get_attribute(vm.sys_module.clone(), "modules").unwrap();
38-
39-
let name = &objstr::get_value(&vm.get_attribute(spec.clone(), "name")?);
38+
let spec = vm.get_attribute(spec.clone(), "name")?;
39+
let name = objstr::borrow_value(&spec);
4040

4141
if let Ok(module) = sys_modules.get_item(name, vm) {
4242
Ok(module)

vm/src/stdlib/io.rs

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -209,13 +209,11 @@ fn string_io_new(
209209
_args: StringIOArgs,
210210
vm: &VirtualMachine,
211211
) -> PyResult<PyStringIORef> {
212-
let raw_string = match object {
213-
OptionalArg::Present(Some(ref input)) => objstr::get_value(input),
214-
_ => String::new(),
215-
};
212+
let flatten = object.flat_option();
213+
let input = flatten.map_or_else(Vec::new, |v| objstr::borrow_value(&v).as_bytes().to_vec());
216214

217215
PyStringIO {
218-
buffer: RefCell::new(Some(BufferedIO::new(Cursor::new(raw_string.into_bytes())))),
216+
buffer: RefCell::new(Some(BufferedIO::new(Cursor::new(input)))),
219217
}
220218
.into_ref_with_type(vm, cls)
221219
}
@@ -816,7 +814,7 @@ fn text_io_wrapper_readline(
816814
Ok(rust_string)
817815
}
818816

819-
fn split_mode_string(mode_string: String) -> Result<(String, String), String> {
817+
fn split_mode_string(mode_string: &str) -> Result<(String, String), String> {
820818
let mut mode: char = '\0';
821819
let mut typ: char = '\0';
822820
let mut plus_is_set = false;
@@ -882,7 +880,7 @@ pub fn io_open(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
882880
);
883881

884882
// mode is optional: 'rt' is the default mode (open from reading text)
885-
let mode_string = mode.map_or("rt".to_string(), objstr::get_value);
883+
let mode_string = mode.map_or("rt", objstr::borrow_value);
886884

887885
let (mode, typ) = match split_mode_string(mode_string) {
888886
Ok((mode, typ)) => (mode, typ),
@@ -1066,7 +1064,7 @@ mod tests {
10661064
use super::*;
10671065

10681066
fn assert_mode_split_into(mode_string: &str, expected_mode: &str, expected_typ: &str) {
1069-
let (mode, typ) = split_mode_string(mode_string.to_string()).unwrap();
1067+
let (mode, typ) = split_mode_string(mode_string).unwrap();
10701068
assert_eq!(mode, expected_mode);
10711069
assert_eq!(typ, expected_typ);
10721070
}
@@ -1085,37 +1083,37 @@ mod tests {
10851083
#[test]
10861084
fn test_invalid_mode() {
10871085
assert_eq!(
1088-
split_mode_string("rbsss".to_string()),
1086+
split_mode_string("rbsss"),
10891087
Err("invalid mode: 'rbsss'".to_string())
10901088
);
10911089
assert_eq!(
1092-
split_mode_string("rrb".to_string()),
1090+
split_mode_string("rrb"),
10931091
Err("invalid mode: 'rrb'".to_string())
10941092
);
10951093
assert_eq!(
1096-
split_mode_string("rbb".to_string()),
1094+
split_mode_string("rbb"),
10971095
Err("invalid mode: 'rbb'".to_string())
10981096
);
10991097
}
11001098

11011099
#[test]
11021100
fn test_mode_not_specified() {
11031101
assert_eq!(
1104-
split_mode_string("".to_string()),
1102+
split_mode_string(""),
11051103
Err(
11061104
"Must have exactly one of create/read/write/append mode and at most one plus"
11071105
.to_string()
11081106
)
11091107
);
11101108
assert_eq!(
1111-
split_mode_string("b".to_string()),
1109+
split_mode_string("b"),
11121110
Err(
11131111
"Must have exactly one of create/read/write/append mode and at most one plus"
11141112
.to_string()
11151113
)
11161114
);
11171115
assert_eq!(
1118-
split_mode_string("t".to_string()),
1116+
split_mode_string("t"),
11191117
Err(
11201118
"Must have exactly one of create/read/write/append mode and at most one plus"
11211119
.to_string()
@@ -1126,23 +1124,23 @@ mod tests {
11261124
#[test]
11271125
fn test_text_and_binary_at_once() {
11281126
assert_eq!(
1129-
split_mode_string("rbt".to_string()),
1127+
split_mode_string("rbt"),
11301128
Err("can't have text and binary mode at once".to_string())
11311129
);
11321130
}
11331131

11341132
#[test]
11351133
fn test_exactly_one_mode() {
11361134
assert_eq!(
1137-
split_mode_string("rwb".to_string()),
1135+
split_mode_string("rwb"),
11381136
Err("must have exactly one of create/read/write/append mode".to_string())
11391137
);
11401138
}
11411139

11421140
#[test]
11431141
fn test_at_most_one_plus() {
11441142
assert_eq!(
1145-
split_mode_string("a++".to_string()),
1143+
split_mode_string("a++"),
11461144
Err("invalid mode: 'a++'".to_string())
11471145
);
11481146
}

vm/src/stdlib/pystruct.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ fn struct_pack(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
213213
} else {
214214
let fmt_arg = args.args[0].clone();
215215
if objtype::isinstance(&fmt_arg, &vm.ctx.str_type()) {
216-
let fmt_str = objstr::get_value(&fmt_arg);
216+
let fmt_str = objstr::clone_value(&fmt_arg);
217217

218218
let format_spec = parse_format_string(fmt_str).map_err(|e| vm.new_value_error(e))?;
219219

@@ -364,7 +364,7 @@ fn struct_unpack(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
364364
]
365365
);
366366

367-
let fmt_str = objstr::get_value(&fmt);
367+
let fmt_str = objstr::clone_value(&fmt);
368368

369369
let format_spec = parse_format_string(fmt_str).map_err(|e| vm.new_value_error(e))?;
370370
let data = objbytes::get_value(buffer).to_vec();

vm/src/stdlib/subprocess.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ impl PopenRef {
109109
Either::A(command) => vec![command.as_str().to_string()],
110110
Either::B(command_list) => objsequence::get_elements_list(command_list.as_object())
111111
.iter()
112-
.map(|x| objstr::get_value(x))
112+
.map(|x| objstr::clone_value(x))
113113
.collect(),
114114
};
115115
let cwd = args.cwd.map(|x| OsString::from(x.as_str()));

vm/src/stdlib/tokenize.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@ use crate::vm::VirtualMachine;
1313

1414
fn tokenize_tokenize(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
1515
arg_check!(vm, args, required = [(readline, Some(vm.ctx.str_type()))]);
16-
let source = objstr::get_value(readline);
16+
let source = objstr::borrow_value(readline);
1717

1818
// TODO: implement generator when the time has come.
19-
let lexer1 = lexer::make_tokenizer(&source);
19+
let lexer1 = lexer::make_tokenizer(source);
2020

2121
let tokens = lexer1.map(|st| vm.ctx.new_str(format!("{:?}", st.unwrap().1)));
2222
let tokens = Vec::from_iter(tokens);

vm/src/vm.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1523,7 +1523,7 @@ mod tests {
15231523
let a = vm.ctx.new_str(String::from("Hello "));
15241524
let b = vm.ctx.new_int(4_i32);
15251525
let res = vm._mul(a, b).unwrap();
1526-
let value = objstr::get_value(&res);
1526+
let value = objstr::borrow_value(&res);
15271527
assert_eq!(value, String::from("Hello Hello Hello Hello "))
15281528
}
15291529
}

0 commit comments

Comments
 (0)