changeset 52856:e2d2961b8383

rust-pyo3: implementing IntoPyObject for Node It will be simpler to go through the `PyNode` new-type, than to call `PyBytes::new(py, node.as_bytes())`. This also opens up many implicit usages, e.g, by `PyList::new` and the various "protocol" methods `PyAnyMethods::set_item`. Also we made the inner `Node` public because we feel `PyNode(n)` to be nicer than `n.into::<PyNode>()` as typically a bare `n.into()` will not be enough for `into_pyobject()` to know what to do.
author Georges Racinet <georges.racinet@cloudcrane.io>
date Thu, 06 Feb 2025 11:40:38 +0100
parents 138e4ce24680
children e7b825893e1b
files rust/hg-pyo3/src/node.rs
diffstat 1 files changed, 16 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/rust/hg-pyo3/src/node.rs	Wed Jan 29 15:56:44 2025 +0100
+++ b/rust/hg-pyo3/src/node.rs	Thu Feb 06 11:40:38 2025 +0100
@@ -2,6 +2,8 @@
 use pyo3::prelude::*;
 use pyo3::types::PyBytes;
 
+use std::convert::Infallible;
+
 use hg::revlog::RevlogIndex;
 use hg::{
     revlog::index::Index, revlog::node::NODE_BYTES_LENGTH, Node, NodePrefix,
@@ -9,7 +11,20 @@
 };
 
 #[derive(Debug, Copy, Clone, PartialEq, derive_more::From)]
-pub struct PyNode(Node);
+pub struct PyNode(pub Node);
+
+impl<'py> IntoPyObject<'py> for PyNode {
+    type Target = PyBytes;
+    type Output = Bound<'py, Self::Target>;
+    type Error = Infallible;
+
+    fn into_pyobject(
+        self,
+        py: Python<'py>,
+    ) -> Result<Self::Output, Self::Error> {
+        Ok(PyBytes::new(py, self.0.as_bytes()))
+    }
+}
 
 /// Copy incoming Python binary Node ID into [`Node`]
 ///