diff rust/hg-cpython/src/cindex.rs @ 44512:166349510398

revlog: using two new functions in C capsule from Rust code We expose `index_length` and `index_node` in the C capsule, so that the Rust representation of the C index can implement the `RevlogIndex` trait. Because our `Node` is actually a one-field struct, we have to decorate it for direct FFI exchange with the C `char*` It would be a good thing to get a length from the C layer, but doing so right now would probably interfere with the upcoming changes that will happen there for the hash length. Differential Revision: https://phab.mercurial-scm.org/D8152
author Georges Racinet <georges.racinet@octobus.net>
date Mon, 13 Jan 2020 19:31:33 +0100
parents f5d2720f3bea
children cefd130c98be
line wrap: on
line diff
--- a/rust/hg-cpython/src/cindex.rs	Tue Feb 18 19:11:14 2020 +0100
+++ b/rust/hg-cpython/src/cindex.rs	Mon Jan 13 19:31:33 2020 +0100
@@ -11,14 +11,21 @@
 //! but this will take some time to get there.
 
 use cpython::{exc::ImportError, PyClone, PyErr, PyObject, PyResult, Python};
+use hg::revlog::{Node, RevlogIndex};
 use hg::{Graph, GraphError, Revision, WORKING_DIRECTORY_REVISION};
 use libc::c_int;
 
-const REVLOG_CABI_VERSION: c_int = 1;
+const REVLOG_CABI_VERSION: c_int = 2;
 
 #[repr(C)]
 pub struct Revlog_CAPI {
     abi_version: c_int,
+    index_length:
+        unsafe extern "C" fn(index: *mut revlog_capi::RawPyObject) -> c_int,
+    index_node: unsafe extern "C" fn(
+        index: *mut revlog_capi::RawPyObject,
+        rev: c_int,
+    ) -> *const Node,
     index_parents: unsafe extern "C" fn(
         index: *mut revlog_capi::RawPyObject,
         rev: c_int,
@@ -131,3 +138,30 @@
         }
     }
 }
+
+impl RevlogIndex for Index {
+    /// Note C return type is Py_ssize_t (hence signed), but we shall
+    /// force it to unsigned, because it's a length
+    fn len(&self) -> usize {
+        unsafe { (self.capi.index_length)(self.index.as_ptr()) as usize }
+    }
+
+    fn node<'a>(&'a self, rev: Revision) -> Option<&'a Node> {
+        let raw = unsafe {
+            (self.capi.index_node)(self.index.as_ptr(), rev as c_int)
+        };
+        if raw.is_null() {
+            None
+        } else {
+            // TODO it would be much better for the C layer to give us
+            // a length, since the hash length will change in the near
+            // future, but that's probably out of scope for the nodemap
+            // patch series.
+            //
+            // The root of that unsafety relies in the signature of
+            // `capi.index_node()` itself: returning a `Node` pointer
+            // whereas it's a `char *` in the C counterpart.
+            Some(unsafe { &*raw })
+        }
+    }
+}