Debian Codegraph @

rust/hg-pyo3/src/node.rs

raw
1 use std::convert::Infallible;
2
3 use hg::revlog::index::Index;
4 use hg::revlog::node::NODE_BYTES_LENGTH;
5 use hg::revlog::RevlogIndex;
6 use hg::Node;
7 use hg::NodePrefix;
8 use hg::Revision;
9 use pyo3::exceptions::PyValueError;
10 use pyo3::prelude::*;
11 use pyo3::types::PyBytes;
12
13 #[derive(Debug, Copy, Clone, PartialEq, derive_more::From)]
14 pub struct PyNode(pub Node);
15
16 impl<'py> IntoPyObject<'py> for PyNode {
17 type Target = PyBytes;
18 type Output = Bound<'py, Self::Target>;
19 type Error = Infallible;
20
21 fn into_pyobject(
22 self,
23 py: Python<'py>,
24 ) -> Result<Self::Output, Self::Error> {
25 Ok(PyBytes::new(py, self.0.as_bytes()))
26 }
27 }
28
29 /// Copy incoming Python binary Node ID into [`Node`]
30 ///
31 /// # Python exceptions
32 /// Raises `ValueError` if length is not as expected
33 pub fn node_from_py_bytes(bytes: &Bound<'_, PyBytes>) -> PyResult<Node> {
34 Node::try_from(bytes.as_bytes()).map_err(|_| {
35 PyValueError::new_err(format!(
36 "{}-byte hash required",
37 NODE_BYTES_LENGTH
38 ))
39 })
40 }
41
42 /// Convert Python hexadecimal Node ID node or prefix given as `bytes` into
43 /// [`NodePrefix`].
44 ///
45 /// # Python exceptions
46 /// Raises `ValueError` if the incoming `bytes` is invalid.
47 pub fn node_prefix_from_py_bytes(
48 bytes: &Bound<'_, PyBytes>,
49 ) -> PyResult<NodePrefix> {
50 let as_bytes = bytes.as_bytes();
51 NodePrefix::from_hex(as_bytes).map_err(|_| {
52 PyValueError::new_err(format!(
53 "Invalid node or prefix '{}'",
54 String::from_utf8_lossy(as_bytes)
55 ))
56 })
57 }
58
59 /// Return the binary node from a checked revision
60 ///
61 /// This is meant to be used on revisions already checked to exist,
62 /// typically obtained from a NodeTree lookup.
63 ///
64 /// # Panics
65 /// Panics if the revision does not exist
66 pub fn py_node_for_rev<'py>(
67 py: Python<'py>,
68 idx: &Index,
69 rev: Revision,
70 ) -> Bound<'py, PyBytes> {
71 PyBytes::new(py, idx.node(rev).as_bytes())
72 }