Skip to content

Commit a42d547

Browse files
committed
new_{utf8_str, ascii_literal} -> new_str again
1 parent 273729d commit a42d547

Some content is hidden

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

51 files changed

+346
-342
lines changed

benches/microbenchmarks.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -132,11 +132,7 @@ fn bench_rustpy_code(group: &mut BenchmarkGroup<WallTime>, bench: &MicroBenchmar
132132
if let Some(idx) = iterations {
133133
scope
134134
.locals
135-
.set_item(
136-
vm.ctx.new_ascii_literal(ascii!("ITERATIONS")),
137-
vm.new_pyobj(idx),
138-
vm,
139-
)
135+
.set_item(vm.new_pyobj(ascii!("ITERATIONS")), vm.new_pyobj(idx), vm)
140136
.expect("Error adding ITERATIONS local variable");
141137
}
142138
let setup_result = vm.run_code_obj(setup_code.clone(), scope.clone());

common/src/str.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use ascii::AsciiString;
12
use std::ops::{Bound, RangeBounds};
23

34
#[cfg(not(target_arch = "wasm32"))]
@@ -62,11 +63,11 @@ pub fn zfill(bytes: &[u8], width: usize) -> Vec<u8> {
6263

6364
/// Convert a string to ascii compatible, escaping unicodes into escape
6465
/// sequences.
65-
pub fn to_ascii(value: &str) -> String {
66-
let mut ascii = String::new();
66+
pub fn to_ascii(value: &str) -> AsciiString {
67+
let mut ascii = Vec::new();
6768
for c in value.chars() {
6869
if c.is_ascii() {
69-
ascii.push(c)
70+
ascii.push(c as u8);
7071
} else {
7172
let c = c as i64;
7273
let hex = if c < 0x100 {
@@ -76,10 +77,10 @@ pub fn to_ascii(value: &str) -> String {
7677
} else {
7778
format!("\\U{:08x}", c)
7879
};
79-
ascii.push_str(&hex)
80+
ascii.append(&mut hex.into_bytes());
8081
}
8182
}
82-
ascii
83+
unsafe { AsciiString::from_ascii_unchecked(ascii) }
8384
}
8485

8586
#[doc(hidden)]

derive/src/pymodule.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,7 @@ impl ModuleItem for FunctionItem {
289289
vm.ctx.make_funcdef(#py_name, #ident)
290290
#doc
291291
.into_function()
292-
.with_module(vm.ctx.new_utf8_str(#module.to_owned()))
292+
.with_module(vm.new_pyobj(#module.to_owned()))
293293
.into_ref(&vm.ctx)
294294
);
295295
quote! {
@@ -350,7 +350,7 @@ impl ModuleItem for ClassItem {
350350
);
351351
let item = quote! {
352352
let new_class = #new_class;
353-
new_class.set_str_attr("__module__", vm.ctx.new_utf8_str(#module_name));
353+
new_class.set_str_attr("__module__", vm.new_pyobj(#module_name));
354354
vm.__module_set_attr(&module, #py_name, new_class).unwrap();
355355
};
356356

src/lib.rs

+6-9
Original file line numberDiff line numberDiff line change
@@ -613,7 +613,7 @@ fn _run_string(vm: &VirtualMachine, scope: Scope, source: &str, source_path: Str
613613
// trace!("Code object: {:?}", code_obj.borrow());
614614
scope
615615
.globals
616-
.set_item("__file__", vm.ctx.new_utf8_str(source_path), vm)?;
616+
.set_item("__file__", vm.new_pyobj(source_path), vm)?;
617617
vm.run_code_obj(code_obj, scope)
618618
}
619619

@@ -637,7 +637,7 @@ fn get_importer(path: &str, vm: &VirtualMachine) -> PyResult<Option<PyObjectRef>
637637
if let Some(importer) = path_importer_cache.get_item_option(path, vm)? {
638638
return Ok(Some(importer));
639639
}
640-
let path = vm.ctx.new_utf8_str(path);
640+
let path = vm.ctx.new_str(path);
641641
let path_hooks = vm.get_attribute(vm.sys_module.clone(), "path_hooks")?;
642642
let mut importer = None;
643643
let path_hooks: Vec<PyObjectRef> = vm.extract_elements(&path_hooks)?;
@@ -652,7 +652,7 @@ fn get_importer(path: &str, vm: &VirtualMachine) -> PyResult<Option<PyObjectRef>
652652
}
653653
}
654654
Ok(if let Some(imp) = importer {
655-
let imp = path_importer_cache.get_or_insert(vm, path, || imp.clone())?;
655+
let imp = path_importer_cache.get_or_insert(vm, path.into(), || imp.clone())?;
656656
Some(imp)
657657
} else {
658658
None
@@ -668,17 +668,14 @@ fn insert_sys_path(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<()> {
668668
fn run_script(vm: &VirtualMachine, scope: Scope, script_file: &str) -> PyResult<()> {
669669
debug!("Running file {}", script_file);
670670
if get_importer(script_file, vm)?.is_some() {
671-
insert_sys_path(vm, vm.ctx.new_utf8_str(script_file))?;
671+
insert_sys_path(vm, vm.ctx.new_str(script_file).into())?;
672672
let runpy = vm.import("runpy", None, 0)?;
673673
let run_module_as_main = vm.get_attribute(runpy, "_run_module_as_main")?;
674-
vm.invoke(
675-
&run_module_as_main,
676-
(vm.ctx.new_utf8_str("__main__"), false),
677-
)?;
674+
vm.invoke(&run_module_as_main, (vm.ctx.new_str("__main__"), false))?;
678675
return Ok(());
679676
}
680677
let dir = Path::new(script_file).parent().unwrap().to_str().unwrap();
681-
insert_sys_path(vm, vm.ctx.new_utf8_str(dir))?;
678+
insert_sys_path(vm, vm.ctx.new_str(dir).into())?;
682679

683680
match std::fs::read_to_string(script_file) {
684681
Ok(source) => {

stdlib/src/array.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ mod array {
2828
AsBuffer, AsMapping, Comparable, Iterable, IteratorIterable, PyComparisonOp,
2929
SlotConstructor, SlotIterator,
3030
},
31-
IdProtocol, PyComparisonValue, PyObjectRef, PyObjectWrap, PyRef, PyResult, PyValue,
32-
TryFromObject, TypeProtocol, VirtualMachine,
31+
IdProtocol, PyComparisonValue, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject,
32+
TypeProtocol, VirtualMachine,
3333
};
3434
use crossbeam_utils::atomic::AtomicCell;
3535
use itertools::Itertools;
@@ -1122,8 +1122,8 @@ mod array {
11221122
return Self::reduce(zelf, vm);
11231123
}
11241124
let array = zelf.read();
1125-
let cls = zelf.as_object().clone_class().into_object();
1126-
let typecode = vm.ctx.new_utf8_str(array.typecode_str());
1125+
let cls = zelf.as_object().clone_class();
1126+
let typecode = vm.ctx.new_str(array.typecode_str());
11271127
let bytes = vm.ctx.new_bytes(array.get_bytes().to_vec());
11281128
let code = MachineFormatCode::from_typecode(array.typecode()).unwrap();
11291129
let code = PyInt::from(u8::from(code)).into_object(vm);
@@ -1142,8 +1142,8 @@ mod array {
11421142
vm: &VirtualMachine,
11431143
) -> PyResult<(PyObjectRef, PyTupleRef, Option<PyDictRef>)> {
11441144
let array = zelf.read();
1145-
let cls = zelf.as_object().clone_class().into_object();
1146-
let typecode = vm.ctx.new_utf8_str(array.typecode_str());
1145+
let cls = zelf.as_object().clone_class();
1146+
let typecode = vm.ctx.new_str(array.typecode_str());
11471147
let values = if array.typecode() == 'u' {
11481148
let s = Self::_wchar_bytes_to_string(array.get_bytes(), array.itemsize(), vm)?;
11491149
s.chars().map(|x| x.into_pyobject(vm)).collect()
@@ -1152,7 +1152,7 @@ mod array {
11521152
};
11531153
let values = vm.ctx.new_list(values);
11541154
Ok((
1155-
cls,
1155+
cls.into(),
11561156
vm.new_tuple((typecode, values)),
11571157
zelf.as_object().dict(),
11581158
))

stdlib/src/csv.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -157,10 +157,10 @@ impl SlotIterator for Reader {
157157
.map(|&end| {
158158
let range = prev_end..end;
159159
prev_end = end;
160-
std::str::from_utf8(&buffer[range])
161-
.map(|s| vm.ctx.new_utf8_str(s.to_owned()))
160+
let s = std::str::from_utf8(&buffer[range])
162161
// not sure if this is possible - the input was all strings
163-
.map_err(|_e| vm.new_unicode_decode_error("csv not utf8".to_owned()))
162+
.map_err(|_e| vm.new_unicode_decode_error("csv not utf8".to_owned()))?;
163+
Ok(vm.ctx.new_str(s).into())
164164
})
165165
.collect::<Result<_, _>>()?;
166166
Ok(PyIterReturn::Return(vm.ctx.new_list(out)))

stdlib/src/dis.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ mod decl {
3333
fn compiler_flag_names(vm: &VirtualMachine) -> PyDictRef {
3434
let dict = vm.ctx.new_dict();
3535
for (name, flag) in CodeFlags::NAME_MAPPING {
36-
dict.set_item(vm.new_pyobj(flag.bits()), vm.ctx.new_utf8_str(name), vm)
36+
dict.set_item(vm.new_pyobj(flag.bits()), vm.ctx.new_str(*name).into(), vm)
3737
.unwrap();
3838
}
3939
dict

stdlib/src/keyword.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ mod keyword {
2222
lexer::KEYWORDS
2323
.keys()
2424
.sorted()
25-
.map(|k| vm.ctx.new_utf8_str(k))
25+
.map(|&k| vm.ctx.new_str(k).into())
2626
.collect(),
2727
)
2828
}

stdlib/src/pyexpat.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ mod _pyexpat {
131131
for attribute in attributes {
132132
dict.set_item(
133133
attribute.name.local_name.as_str(),
134-
vm.ctx.new_utf8_str(attribute.value),
134+
vm.ctx.new_str(attribute.value).into(),
135135
vm,
136136
)
137137
.unwrap();

stdlib/src/re.rs

+8-8
Original file line numberDiff line numberDiff line change
@@ -189,12 +189,12 @@ mod re {
189189
1 => {
190190
let full = captures.get(0).unwrap().as_bytes();
191191
let full = String::from_utf8_lossy(full).into_owned();
192-
vm.ctx.new_utf8_str(full)
192+
vm.ctx.new_str(full).into()
193193
}
194194
2 => {
195195
let capture = captures.get(1).unwrap().as_bytes();
196196
let capture = String::from_utf8_lossy(capture).into_owned();
197-
vm.ctx.new_utf8_str(capture)
197+
vm.ctx.new_str(capture).into()
198198
}
199199
_ => {
200200
let out = captures
@@ -204,7 +204,7 @@ mod re {
204204
let s = m
205205
.map(|m| String::from_utf8_lossy(m.as_bytes()).into_owned())
206206
.unwrap_or_default();
207-
vm.ctx.new_utf8_str(s)
207+
vm.ctx.new_str(s).into()
208208
})
209209
.collect();
210210
vm.ctx.new_tuple(out).into()
@@ -253,7 +253,7 @@ mod re {
253253
.into_iter()
254254
.map(|v| {
255255
vm.unwrap_or_none(
256-
v.map(|v| vm.ctx.new_utf8_str(String::from_utf8_lossy(v).into_owned())),
256+
v.map(|v| vm.ctx.new_str(String::from_utf8_lossy(v).into_owned()).into()),
257257
)
258258
})
259259
.collect();
@@ -330,12 +330,12 @@ mod re {
330330
}
331331

332332
#[pymethod]
333-
fn sub(&self, repl: PyStrRef, text: PyStrRef, vm: &VirtualMachine) -> PyResult {
333+
fn sub(&self, repl: PyStrRef, text: PyStrRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
334334
let replaced_text = self
335335
.regex
336336
.replace_all(text.as_str().as_bytes(), repl.as_str().as_bytes());
337337
let replaced_text = String::from_utf8_lossy(&replaced_text).into_owned();
338-
Ok(vm.ctx.new_utf8_str(replaced_text))
338+
Ok(vm.ctx.new_str(replaced_text))
339339
}
340340

341341
#[pymethod]
@@ -344,8 +344,8 @@ mod re {
344344
}
345345

346346
#[pyproperty]
347-
fn pattern(&self, vm: &VirtualMachine) -> PyResult {
348-
Ok(vm.ctx.new_utf8_str(self.pattern.clone()))
347+
fn pattern(&self, vm: &VirtualMachine) -> PyResult<PyStrRef> {
348+
Ok(vm.ctx.new_str(self.pattern.clone()))
349349
}
350350

351351
#[pymethod]

stdlib/src/scproxy.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ mod _scproxy {
108108
} else {
109109
format!("http://{}", h)
110110
};
111-
result.set_item(proto, vm.ctx.new_utf8_str(v), vm)?;
111+
result.set_item(proto, vm.new_pyobj(v), vm)?;
112112
}
113113
}
114114
Ok(())

stdlib/src/socket.rs

+7-8
Original file line numberDiff line numberDiff line change
@@ -1026,19 +1026,18 @@ fn get_addr_tuple(addr: &socket2::SockAddr, vm: &VirtualMachine) -> PyObjectRef
10261026
} else {
10271027
let len = memchr::memchr(b'\0', path_u8).unwrap_or_else(|| path_u8.len());
10281028
let path = &path_u8[..len];
1029-
vm.ctx
1030-
.new_utf8_str(String::from_utf8_lossy(path).into_owned())
1029+
vm.ctx.new_str(String::from_utf8_lossy(path)).into()
10311030
}
10321031
}
10331032
// TODO: support more address families
10341033
_ => (String::new(), 0).into_pyobject(vm),
10351034
}
10361035
}
10371036

1038-
fn _socket_gethostname(vm: &VirtualMachine) -> PyResult {
1037+
fn _socket_gethostname(vm: &VirtualMachine) -> PyResult<PyStrRef> {
10391038
gethostname()
10401039
.into_string()
1041-
.map(|hostname| vm.ctx.new_utf8_str(hostname))
1040+
.map(|hostname| vm.ctx.new_str(hostname))
10421041
.map_err(|err| vm.new_os_error(err.into_string().unwrap()))
10431042
}
10441043

@@ -1055,11 +1054,11 @@ fn _socket_inet_aton(ip_string: PyStrRef, vm: &VirtualMachine) -> PyResult<Vec<u
10551054
.map_err(|_| vm.new_os_error("illegal IP address string passed to inet_aton".to_owned()))
10561055
}
10571056

1058-
fn _socket_inet_ntoa(packed_ip: ArgBytesLike, vm: &VirtualMachine) -> PyResult {
1057+
fn _socket_inet_ntoa(packed_ip: ArgBytesLike, vm: &VirtualMachine) -> PyResult<PyStrRef> {
10591058
let packed_ip = packed_ip.borrow_buf();
10601059
let packed_ip = <&[u8; 4]>::try_from(&*packed_ip)
10611060
.map_err(|_| vm.new_os_error("packed IP wrong length for inet_ntoa".to_owned()))?;
1062-
Ok(vm.ctx.new_utf8_str(Ipv4Addr::from(*packed_ip).to_string()))
1061+
Ok(vm.ctx.new_str(Ipv4Addr::from(*packed_ip).to_string()))
10631062
}
10641063

10651064
fn cstr_opt_as_ptr(x: &OptionalArg<ffi::CString>) -> *const libc::c_char {
@@ -1290,7 +1289,7 @@ fn _socket_gethostbyaddr(
12901289
hostname,
12911290
vm.ctx.new_list(vec![]),
12921291
vm.ctx
1293-
.new_list(vec![vm.ctx.new_utf8_str(addr.ip().to_string())]),
1292+
.new_list(vec![vm.ctx.new_str(addr.ip().to_string()).into()]),
12941293
))
12951294
}
12961295

@@ -1726,7 +1725,7 @@ fn convert_socket_error(
17261725
};
17271726
vm.new_exception(
17281727
exception_cls.get().unwrap().clone(),
1729-
vec![vm.new_pyobj(err.error_num()), vm.ctx.new_utf8_str(strerr)],
1728+
vec![vm.new_pyobj(err.error_num()), vm.ctx.new_str(strerr).into()],
17301729
)
17311730
}
17321731

stdlib/src/ssl.rs

+11-11
Original file line numberDiff line numberDiff line change
@@ -187,14 +187,14 @@ fn _ssl_enum_certificates(store_name: PyStrRef, vm: &VirtualMachine) -> PyResult
187187
(*ptr).dwCertEncodingType
188188
};
189189
let enc_type = match enc_type {
190-
wincrypt::X509_ASN_ENCODING => vm.ctx.new_ascii_literal(ascii!("x509_asn")),
191-
wincrypt::PKCS_7_ASN_ENCODING => vm.ctx.new_ascii_literal(ascii!("pkcs_7_asn")),
192-
other => vm.ctx.new_int(other).into(),
190+
wincrypt::X509_ASN_ENCODING => vm.new_pyobj(ascii!("x509_asn")),
191+
wincrypt::PKCS_7_ASN_ENCODING => vm.new_pyobj(ascii!("pkcs_7_asn")),
192+
other => vm.new_pyobj(other),
193193
};
194194
let usage: PyObjectRef = match c.valid_uses()? {
195195
ValidUses::All => vm.ctx.new_bool(true).into(),
196196
ValidUses::Oids(oids) => {
197-
PyFrozenSet::from_iter(vm, oids.into_iter().map(|oid| vm.ctx.new_utf8_str(oid)))
197+
PyFrozenSet::from_iter(vm, oids.into_iter().map(|oid| vm.ctx.new_str(oid).into()))
198198
.unwrap()
199199
.into_ref(vm)
200200
.into()
@@ -991,7 +991,7 @@ fn convert_openssl_error(vm: &VirtualMachine, err: ErrorStack) -> PyBaseExceptio
991991
let reason = sys::ERR_GET_REASON(e.code());
992992
vm.new_exception(
993993
cls,
994-
vec![vm.ctx.new_int(reason).into(), vm.ctx.new_utf8_str(msg)],
994+
vec![vm.ctx.new_int(reason).into(), vm.ctx.new_str(msg).into()],
995995
)
996996
}
997997
None => vm.new_exception_empty(cls),
@@ -1073,7 +1073,7 @@ fn cert_to_py(vm: &VirtualMachine, cert: &X509Ref, binary: bool) -> PyResult {
10731073
.entries()
10741074
.map(|entry| {
10751075
let txt = obj2txt(entry.object(), false).into_pyobject(vm);
1076-
let data = vm.ctx.new_utf8_str(entry.data().as_utf8()?.to_owned());
1076+
let data = vm.ctx.new_str(entry.data().as_utf8()?.to_owned());
10771077
Ok(vm.new_tuple(((txt, data),)).into())
10781078
})
10791079
.collect::<Result<_, _>>()
@@ -1092,18 +1092,18 @@ fn cert_to_py(vm: &VirtualMachine, cert: &X509Ref, binary: bool) -> PyResult {
10921092
.map_err(|e| convert_openssl_error(vm, e))?;
10931093
dict.set_item(
10941094
"serialNumber",
1095-
vm.ctx.new_utf8_str(serial_num.to_owned()),
1095+
vm.ctx.new_str(serial_num.to_owned()).into(),
10961096
vm,
10971097
)?;
10981098

10991099
dict.set_item(
11001100
"notBefore",
1101-
vm.ctx.new_utf8_str(cert.not_before().to_string()),
1101+
vm.ctx.new_str(cert.not_before().to_string()).into(),
11021102
vm,
11031103
)?;
11041104
dict.set_item(
11051105
"notAfter",
1106-
vm.ctx.new_utf8_str(cert.not_after().to_string()),
1106+
vm.ctx.new_str(cert.not_after().to_string()).into(),
11071107
vm,
11081108
)?;
11091109

@@ -1209,11 +1209,11 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
12091209
"_test_decode_cert" => named_function!(ctx, _ssl, _test_decode_cert),
12101210

12111211
// Constants
1212-
"OPENSSL_VERSION" => ctx.new_utf8_str(openssl::version::version()),
1212+
"OPENSSL_VERSION" => ctx.new_str(openssl::version::version()),
12131213
"OPENSSL_VERSION_NUMBER" => ctx.new_int(openssl::version::number()),
12141214
"OPENSSL_VERSION_INFO" => parse_version_info(openssl::version::number()).into_pyobject(vm),
12151215
"_OPENSSL_API_VERSION" => parse_version_info(openssl_api_version).into_pyobject(vm),
1216-
"_DEFAULT_CIPHERS" => ctx.new_utf8_str(DEFAULT_CIPHER_STRING),
1216+
"_DEFAULT_CIPHERS" => ctx.new_str(DEFAULT_CIPHER_STRING),
12171217
// "PROTOCOL_SSLv2" => ctx.new_int(SslVersion::Ssl2 as u32), unsupported
12181218
// "PROTOCOL_SSLv3" => ctx.new_int(SslVersion::Ssl3 as u32),
12191219
"PROTOCOL_SSLv23" => ctx.new_int(SslVersion::Tls as u32),

stdlib/src/termios.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ mod termios {
9999
error_type(vm),
100100
vec![
101101
err.raw_os_error().into_pyobject(vm),
102-
vm.ctx.new_utf8_str(err.to_string()),
102+
vm.ctx.new_str(err.to_string()).into(),
103103
],
104104
)
105105
}

0 commit comments

Comments
 (0)