pyo3::types::bytes

Struct PyBytes

Source
#[repr(transparent)]
pub struct PyBytes(PyAny);
Expand description

Represents a Python bytes object.

This type is immutable.

Values of this type are accessed via PyO3’s smart pointers, e.g. as Py<PyBytes> or Bound<'py, PyBytes>.

For APIs available on bytes objects, see the PyBytesMethods trait which is implemented for Bound<'py, PyBytes>.

§Equality

For convenience, Bound<'py, PyBytes> implements PartialEq<[u8]> to allow comparing the data in the Python bytes to a Rust [u8] byte slice.

This is not always the most appropriate way to compare Python bytes, as Python bytes subclasses may have different equality semantics. In situations where subclasses overriding equality might be relevant, use PyAnyMethods::eq, at cost of the additional overhead of a Python method call.

use pyo3::types::PyBytes;

let py_bytes = PyBytes::new(py, b"foo".as_slice());
// via PartialEq<[u8]>
assert_eq!(py_bytes, b"foo".as_slice());

// via Python equality
let other = PyBytes::new(py, b"foo".as_slice());
assert!(py_bytes.as_any().eq(other).unwrap());

// Note that `eq` will convert its argument to Python using `IntoPyObject`.
// Byte collections are specialized, so that the following slice will indeed
// convert into a `bytes` object and not a `list`:
assert!(py_bytes.as_any().eq(b"foo".as_slice()).unwrap());

Tuple Fields§

§0: PyAny

Implementations§

Source§

impl PyBytes

Source

#[doc(hidden)] pub const _PYO3_DEF: AddTypeToModule<Self> = _

Source§

impl PyBytes

Source

pub fn new<'p>(py: Python<'p>, s: &[u8]) -> Bound<'p, PyBytes>

Creates a new Python bytestring object. The bytestring is initialized by copying the data from the &[u8].

Panics if out of memory.

Source

pub fn new_bound<'p>(py: Python<'p>, s: &[u8]) -> Bound<'p, PyBytes>

👎Deprecated since 0.23.0: renamed to PyBytes::new

Deprecated name for PyBytes::new.

Source

pub fn new_with<F>( py: Python<'_>, len: usize, init: F, ) -> PyResult<Bound<'_, PyBytes>>
where F: FnOnce(&mut [u8]) -> PyResult<()>,

Creates a new Python bytes object with an init closure to write its contents. Before calling init the bytes’ contents are zero-initialised.

  • If Python raises a MemoryError on the allocation, new_with will return it inside Err.
  • If init returns Err(e), new_with will return Err(e).
  • If init returns Ok(()), new_with will return Ok(&PyBytes).
§Examples
use pyo3::{prelude::*, types::PyBytes};

Python::with_gil(|py| -> PyResult<()> {
    let py_bytes = PyBytes::new_with(py, 10, |bytes: &mut [u8]| {
        bytes.copy_from_slice(b"Hello Rust");
        Ok(())
    })?;
    let bytes: &[u8] = py_bytes.extract()?;
    assert_eq!(bytes, b"Hello Rust");
    Ok(())
})
Source

pub fn new_bound_with<F>( py: Python<'_>, len: usize, init: F, ) -> PyResult<Bound<'_, PyBytes>>
where F: FnOnce(&mut [u8]) -> PyResult<()>,

👎Deprecated since 0.23.0: renamed to PyBytes::new_with

Deprecated name for PyBytes::new_with.

Source

pub unsafe fn from_ptr( py: Python<'_>, ptr: *const u8, len: usize, ) -> Bound<'_, PyBytes>

Creates a new Python byte string object from a raw pointer and length.

Panics if out of memory.

§Safety

This function dereferences the raw pointer ptr as the leading pointer of a slice of length len. As with std::slice::from_raw_parts, this is unsafe.

Source

pub unsafe fn bound_from_ptr( py: Python<'_>, ptr: *const u8, len: usize, ) -> Bound<'_, PyBytes>

👎Deprecated since 0.23.0: renamed to PyBytes::from_ptr

Deprecated name for PyBytes::from_ptr.

§Safety

This function dereferences the raw pointer ptr as the leading pointer of a slice of length len. As with std::slice::from_raw_parts, this is unsafe.

Methods from Deref<Target = PyAny>§

Source

#[doc(hidden)] pub const _PYO3_DEF: AddTypeToModule<Self> = _

Trait Implementations§

Source§

impl AsRef<PyAny> for PyBytes

Source§

fn as_ref(&self) -> &PyAny

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Deref for PyBytes

Source§

type Target = PyAny

The resulting type after dereferencing.
Source§

fn deref(&self) -> &PyAny

Dereferences the value.
Source§

impl PyTypeInfo for PyBytes

Source§

const NAME: &'static str = "PyBytes"

Class name.
Source§

const MODULE: Option<&'static str> = _

Module name, if any.
Source§

fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject

Returns the PyTypeObject instance for this type.
Source§

fn is_type_of_bound(obj: &Bound<'_, PyAny>) -> bool

👎Deprecated since 0.23.0: renamed to PyTypeInfo::is_type_of
Deprecated name for PyTypeInfo::is_type_of.
Source§

fn type_object(py: Python<'_>) -> Bound<'_, PyType>

Returns the safe abstraction over the type object.
Source§

fn type_object_bound(py: Python<'_>) -> Bound<'_, PyType>

👎Deprecated since 0.23.0: renamed to PyTypeInfo::type_object
Deprecated name for PyTypeInfo::type_object.
Source§

fn is_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type or a subclass of this type.
Source§

fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type.
Source§

fn is_exact_type_of_bound(object: &Bound<'_, PyAny>) -> bool

👎Deprecated since 0.23.0: renamed to PyTypeInfo::is_exact_type_of
Deprecated name for PyTypeInfo::is_exact_type_of.
Source§

impl DerefToPyAny for PyBytes

Auto Trait Implementations§

§

impl !Freeze for PyBytes

§

impl !RefUnwindSafe for PyBytes

§

impl !Send for PyBytes

§

impl !Sync for PyBytes

§

impl Unpin for PyBytes

§

impl UnwindSafe for PyBytes

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> AssertNotZeroSized for T

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PyTypeCheck for T
where T: PyTypeInfo,

Source§

const NAME: &'static str = const NAME: &'static str = <T as PyTypeInfo>::NAME;

Name of self. This is used in error messages, for example.
Source§

fn type_check(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of Self, which may include a subtype. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> SizedTypeProperties for T

Source§

#[doc(hidden)] const IS_ZST: bool = _

🔬This is a nightly-only experimental API. (sized_type_properties)
true if this type requires no storage. false if its size is greater than zero. Read more
Source§

#[doc(hidden)] const LAYOUT: Layout = _

🔬This is a nightly-only experimental API. (sized_type_properties)
Source§

impl<T> SomeWrap<T> for T

Source§

fn wrap(self) -> Option<T>

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
⚠️ Internal Docs ⚠️ Not Public API 👉 Official Docs Here