Skip to main content

rustpython_vm/
utils.rs

1use rustpython_common::wtf8::{Wtf8, Wtf8Buf};
2
3use crate::{
4    PyObject, PyObjectRef, PyResult, VirtualMachine,
5    builtins::{PyStr, PyUtf8Str},
6    convert::{ToPyException, ToPyObject},
7};
8
9pub fn hash_iter<'a, I: IntoIterator<Item = &'a PyObject>>(
10    iter: I,
11    vm: &VirtualMachine,
12) -> PyResult<rustpython_common::hash::PyHash> {
13    crate::vm::hash_secret().hash_iter(iter, |obj| obj.hash(vm))
14}
15
16impl ToPyObject for core::convert::Infallible {
17    fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef {
18        match self {}
19    }
20}
21
22pub trait ToCString: AsRef<Wtf8> {
23    fn to_cstring(&self, vm: &VirtualMachine) -> PyResult<alloc::ffi::CString> {
24        alloc::ffi::CString::new(self.as_ref().as_bytes()).map_err(|err| err.to_pyexception(vm))
25    }
26}
27
28impl ToCString for &str {}
29impl ToCString for PyStr {}
30impl ToCString for PyUtf8Str {}
31
32pub(crate) fn collection_repr<'a, I>(
33    class_name: Option<&str>,
34    prefix: &str,
35    suffix: &str,
36    empty: &str,
37    iter: I,
38    vm: &VirtualMachine,
39) -> PyResult<Wtf8Buf>
40where
41    I: core::iter::Iterator<Item = &'a PyObject>,
42{
43    let mut repr = Wtf8Buf::new();
44    if let Some(name) = class_name {
45        repr.push_str(name);
46        repr.push_char('(');
47    }
48    repr.push_str(prefix);
49    {
50        let mut parts_iter = iter.map(|o| o.repr(vm));
51        let Some(first) = parts_iter.next().transpose()? else {
52            return Ok(Wtf8Buf::from(empty));
53        };
54        repr.push_wtf8(first.as_wtf8());
55        for part in parts_iter {
56            repr.push_str(", ");
57            repr.push_wtf8(part?.as_wtf8());
58        }
59    }
60    repr.push_str(suffix);
61    if class_name.is_some() {
62        repr.push_char(')');
63    }
64
65    Ok(repr)
66}