MCPcopy Create free account
hub / github.com/dgrunwald/rust-cpython / new

Method new

src/objects/string.rs:245–263  ·  view source on GitHub ↗

Creates a new Python string object. On Python 2.7, this function will create a byte string if the feature `py2-no-auto-unicode-promotion` is set, or the input input string is ASCII-only; otherwise, the input string will be converted to a unicode string. Use `PyUnicode::new()` to always create a unicode string. On Python 3.x, this function always creates unicode `str` objects. Panics if out of m

(py: Python, s: &str)

Source from the content-addressed store, hash-verified

243 ///
244 /// Panics if out of memory.
245 pub fn new(py: Python, s: &str) -> PyString {
246 #[cfg(feature = "python27-sys")]
247 fn new_impl(py: Python, s: &str) -> PyString {
248 if cfg!(feature = "py2-no-auto-unicode-promotion") || s.is_ascii() {
249 PyBytes::new(py, s.as_bytes()).into_basestring()
250 } else {
251 PyUnicode::new(py, s).into_basestring()
252 }
253 }
254 #[cfg(feature = "python3-sys")]
255 fn new_impl(py: Python, s: &str) -> PyString {
256 let ptr = s.as_ptr() as *const c_char;
257 let len = s.len() as ffi::Py_ssize_t;
258 unsafe {
259 err::cast_from_owned_ptr_or_panic(py, ffi::PyUnicode_FromStringAndSize(ptr, len))
260 }
261 }
262 new_impl(py, s)
263 }
264
265 /// Gets the python string data in its underlying representation.
266 ///

Callers

nothing calls this directly

Calls 4

as_ptrMethod · 0.45
lenMethod · 0.45

Tested by

no test coverage detected