Skip to content

Commit 156e6e1

Browse files
authored
Merge pull request RustPython#1654 from youknowone/clone-value
objstr::get_value -> objstr::clone_value
2 parents 73e6539 + 13914e0 commit 156e6e1

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
@@ -211,7 +211,7 @@ impl PyString {
211211
#[pymethod(name = "__add__")]
212212
fn add(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult<String> {
213213
if objtype::isinstance(&rhs, &vm.ctx.str_type()) {
214-
Ok(format!("{}{}", self.value, get_value(&rhs)))
214+
Ok(format!("{}{}", self.value, borrow_value(&rhs)))
215215
} else {
216216
Err(vm.new_type_error(format!("Cannot add {} and {}", self, rhs)))
217217
}
@@ -225,7 +225,7 @@ impl PyString {
225225
#[pymethod(name = "__eq__")]
226226
fn eq(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
227227
if objtype::isinstance(&rhs, &vm.ctx.str_type()) {
228-
vm.new_bool(self.value == get_value(&rhs))
228+
vm.new_bool(self.value == borrow_value(&rhs))
229229
} else {
230230
vm.ctx.not_implemented()
231231
}
@@ -234,7 +234,7 @@ impl PyString {
234234
#[pymethod(name = "__ne__")]
235235
fn ne(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
236236
if objtype::isinstance(&rhs, &vm.ctx.str_type()) {
237-
vm.new_bool(self.value != get_value(&rhs))
237+
vm.new_bool(self.value != borrow_value(&rhs))
238238
} else {
239239
vm.ctx.not_implemented()
240240
}
@@ -611,8 +611,8 @@ impl PyString {
611611
actual_type
612612
)));
613613
}
614-
let format_string_text = get_value(zelf);
615-
match FormatString::from_str(format_string_text.as_str()) {
614+
let format_string_text = borrow_value(zelf);
615+
match FormatString::from_str(format_string_text) {
616616
Ok(format_string) => perform_format(vm, &format_string, &args),
617617
Err(err) => match err {
618618
FormatParseError::UnmatchedBracket => {
@@ -637,8 +637,8 @@ impl PyString {
637637
}
638638

639639
let zelf = &args.args[0];
640-
let format_string_text = get_value(zelf);
641-
match FormatString::from_str(format_string_text.as_str()) {
640+
let format_string_text = borrow_value(zelf);
641+
match FormatString::from_str(format_string_text) {
642642
Ok(format_string) => perform_format_map(vm, &format_string, &args.args[1]),
643643
Err(err) => match err {
644644
FormatParseError::UnmatchedBracket => {
@@ -1271,7 +1271,7 @@ pub fn init(ctx: &PyContext) {
12711271
PyStringReverseIterator::extend_class(ctx, &ctx.types.strreverseiterator_type);
12721272
}
12731273

1274-
pub fn get_value(obj: &PyObjectRef) -> String {
1274+
pub fn clone_value(obj: &PyObjectRef) -> String {
12751275
obj.payload::<PyString>().unwrap().value.clone()
12761276
}
12771277

@@ -1324,7 +1324,7 @@ fn do_cformat_specifier(
13241324
CFormatPreconversor::Ascii => vm.call_method(&obj.clone(), "__repr__", vec![])?,
13251325
CFormatPreconversor::Bytes => vm.call_method(&obj.clone(), "decode", vec![])?,
13261326
};
1327-
Ok(format_spec.format_string(get_value(&result)))
1327+
Ok(format_spec.format_string(clone_value(&result)))
13281328
}
13291329
CFormatType::Number(_) => {
13301330
if !objtype::isinstance(&obj, &vm.ctx.int_type()) {
@@ -1367,7 +1367,7 @@ fn do_cformat_specifier(
13671367
}
13681368
}
13691369
} else if objtype::isinstance(&obj, &vm.ctx.str_type()) {
1370-
let s: String = get_value(&obj);
1370+
let s = borrow_value(&obj);
13711371
let num_chars = s.chars().count();
13721372
if num_chars != 1 {
13731373
Err(vm.new_type_error("%c requires int or char".to_string()))
@@ -1554,7 +1554,7 @@ fn perform_format(
15541554
}
15551555
};
15561556
auto_argument_index += 1;
1557-
get_value(&result)
1557+
clone_value(&result)
15581558
}
15591559
FormatPart::IndexSpec(index, format_spec) => {
15601560
let result = match arguments.args.get(*index + 1) {
@@ -1563,7 +1563,7 @@ fn perform_format(
15631563
return Err(vm.new_index_error("tuple index out of range".to_string()));
15641564
}
15651565
};
1566-
get_value(&result)
1566+
clone_value(&result)
15671567
}
15681568
FormatPart::KeywordSpec(keyword, format_spec) => {
15691569
let result = match arguments.get_optional_kwarg(&keyword) {
@@ -1572,7 +1572,7 @@ fn perform_format(
15721572
return Err(vm.new_key_error(vm.new_str(keyword.to_string())));
15731573
}
15741574
};
1575-
get_value(&result)
1575+
clone_value(&result)
15761576
}
15771577
FormatPart::Literal(literal) => literal.clone(),
15781578
};
@@ -1597,7 +1597,7 @@ fn perform_format_map(
15971597
FormatPart::KeywordSpec(keyword, format_spec) => {
15981598
let argument = dict.get_item(keyword, &vm)?;
15991599
let result = call_object_format(vm, argument.clone(), &format_spec)?;
1600-
get_value(&result)
1600+
clone_value(&result)
16011601
}
16021602
FormatPart::Literal(literal) => literal.clone(),
16031603
};

vm/src/py_serde.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ impl<'s> serde::Serialize for PyObjectSerializer<'s> {
7070
seq.end()
7171
};
7272
if objtype::isinstance(self.pyobject, &self.vm.ctx.str_type()) {
73-
serializer.serialize_str(&objstr::get_value(&self.pyobject))
73+
serializer.serialize_str(objstr::borrow_value(&self.pyobject))
7474
} else if objtype::isinstance(self.pyobject, &self.vm.ctx.float_type()) {
7575
serializer.serialize_f64(objfloat::get_value(self.pyobject))
7676
} 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::B(command_list) => command_list
110110
.borrow_elements()
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
@@ -1529,7 +1529,7 @@ mod tests {
15291529
let a = vm.ctx.new_str(String::from("Hello "));
15301530
let b = vm.ctx.new_int(4_i32);
15311531
let res = vm._mul(a, b).unwrap();
1532-
let value = objstr::get_value(&res);
1532+
let value = objstr::borrow_value(&res);
15331533
assert_eq!(value, String::from("Hello Hello Hello Hello "))
15341534
}
15351535
}

0 commit comments

Comments
 (0)