rust: replace Node::encode_hex with std::fmt::LowerHex
This avoids allocating intermediate strings.
Differential Revision: https://phab.mercurial-scm.org/D9860
--- a/rust/hg-core/examples/nodemap/main.rs Fri Jan 29 13:46:19 2021 +0100
+++ b/rust/hg-core/examples/nodemap/main.rs Mon Jan 25 12:00:23 2021 +0100
@@ -66,7 +66,7 @@
.collect();
if queries < 10 {
let nodes_hex: Vec<String> =
- nodes.iter().map(|n| n.encode_hex()).collect();
+ nodes.iter().map(|n| format!("{:x}", n)).collect();
println!("Nodes: {:?}", nodes_hex);
}
let mut last: Option<Revision> = None;
@@ -76,11 +76,11 @@
}
let elapsed = start.elapsed();
println!(
- "Did {} queries in {:?} (mean {:?}), last was {:?} with result {:?}",
+ "Did {} queries in {:?} (mean {:?}), last was {:x} with result {:?}",
queries,
elapsed,
elapsed / (queries as u32),
- nodes.last().unwrap().encode_hex(),
+ nodes.last().unwrap(),
last
);
}
--- a/rust/hg-core/src/revlog/node.rs Fri Jan 29 13:46:19 2021 +0100
+++ b/rust/hg-core/src/revlog/node.rs Mon Jan 25 12:00:23 2021 +0100
@@ -11,6 +11,7 @@
use bytes_cast::BytesCast;
use hex::{self, FromHex, FromHexError};
use std::convert::TryFrom;
+use std::fmt;
/// The length in bytes of a `Node`
///
@@ -80,6 +81,15 @@
}
}
+impl fmt::LowerHex for Node {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ for &byte in &self.data {
+ write!(f, "{:02x}", byte)?
+ }
+ Ok(())
+ }
+}
+
#[derive(Debug, PartialEq)]
pub enum NodeError {
ExactLengthRequired(usize, String),
@@ -124,14 +134,6 @@
.into())
}
- /// Convert to hexadecimal string representation
- ///
- /// To be used in FFI and I/O only, in order to facilitate future
- /// changes of hash format.
- pub fn encode_hex(&self) -> String {
- hex::encode(self.data)
- }
-
/// Provide access to binary data
///
/// This is needed by FFI layers, for instance to return expected
@@ -349,7 +351,7 @@
#[test]
fn test_node_encode_hex() {
- assert_eq!(sample_node().encode_hex(), sample_node_hex());
+ assert_eq!(format!("{:x}", sample_node()), sample_node_hex());
}
#[test]
@@ -391,7 +393,7 @@
"testgr".to_string()
))
);
- let mut long = NULL_NODE.encode_hex();
+ let mut long = format!("{:x}", NULL_NODE);
long.push('c');
match NodePrefix::from_hex(&long)
.expect_err("should be refused as too long")