Debian Codegraph @

rust/hg-core/src/revlog/node.rs

raw
1 // Copyright 2019-2020 Georges Racinet <[email protected]>
2 //
3 // This software may be used and distributed according to the terms of the
4 // GNU General Public License version 2 or any later version.
5
6 //! Definitions and utilities for Revision nodes
7 //!
8 //! In Mercurial code base, it is customary to call "a node" the binary SHA
9 //! of a revision.
10
11 use std::fmt;
12
13 use bytes_cast::BytesCast;
14
15 use crate::errors::HgError;
16
17 /// The length in bytes of a `Node`
18 ///
19 /// This constant is meant to ease refactors of this module, and
20 /// are private so that calling code does not expect all nodes have
21 /// the same size, should we support several formats concurrently in
22 /// the future.
23 pub const NODE_BYTES_LENGTH: usize = 20;
24
25 /// The length in bytes set aside on disk for a `Node`. Revlog up to v1 only
26 /// use 20 out of those 32.
27 pub const STORED_NODE_ID_BYTES: usize = 32;
28
29 /// Id of the null node.
30 ///
31 /// Used to indicate the absence of node.
32 pub const NULL_NODE_ID: [u8; NODE_BYTES_LENGTH] = [0u8; NODE_BYTES_LENGTH];
33
34 /// Temporary node id to refer to an added (uncommitted) id
35 pub const ADDED_NODE_ID: [u8; NODE_BYTES_LENGTH] = *b"000000000000000added";
36
37 /// The length in bytes of a `Node`
38 ///
39 /// see also `NODES_BYTES_LENGTH` about it being private.
40 const NODE_NYBBLES_LENGTH: usize = 2 * NODE_BYTES_LENGTH;
41
42 /// Default for UI presentation
43 const SHORT_PREFIX_DEFAULT_NYBBLES_LENGTH: u8 = 12;
44
45 /// Private alias for readability and to ease future change
46 type NodeData = [u8; NODE_BYTES_LENGTH];
47
48 /// Binary revision SHA
49 ///
50 /// ## Future changes of hash size
51 ///
52 /// To accomodate future changes of hash size, Rust callers
53 /// should use the conversion methods at the boundaries (FFI, actual
54 /// computation of hashes and I/O) only, and only if required.
55 ///
56 /// All other callers outside of unit tests should just handle `Node` values
57 /// and never make any assumption on the actual length, using [`nybbles_len`]
58 /// if they need a loop boundary.
59 ///
60 /// All methods that create a `Node` either take a type that enforces
61 /// the size or return an error at runtime.
62 ///
63 /// [`nybbles_len`]: #method.nybbles_len
64 #[derive(Copy, Clone, PartialEq, BytesCast, derive_more::From)]
65 #[repr(transparent)]
66 pub struct Node {
67 data: NodeData,
68 }
69
70 impl fmt::Debug for Node {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 let n = format!("{:x?}", self.data);
73 // We're using debug_tuple because it makes the output a little
74 // more compact without losing data.
75 f.debug_tuple("Node").field(&n).finish()
76 }
77 }
78
79 /// The node value for NULL_REVISION
80 pub const NULL_NODE: Node = Node { data: [0; NODE_BYTES_LENGTH] };
81
82 /// Return an error if the slice has an unexpected length
83 impl<'a> TryFrom<&'a [u8]> for &'a Node {
84 type Error = ();
85
86 #[inline]
87 fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
88 match Node::from_bytes(bytes) {
89 Ok((node, [])) => Ok(node),
90 _ => Err(()),
91 }
92 }
93 }
94
95 /// Return an error if the slice has an unexpected length
96 impl TryFrom<&'_ [u8]> for Node {
97 type Error = std::array::TryFromSliceError;
98
99 #[inline]
100 fn try_from(bytes: &'_ [u8]) -> Result<Self, Self::Error> {
101 let data = bytes.try_into()?;
102 Ok(Self { data })
103 }
104 }
105
106 impl From<&'_ NodeData> for Node {
107 #[inline]
108 fn from(data: &'_ NodeData) -> Self {
109 Self { data: *data }
110 }
111 }
112
113 impl fmt::LowerHex for Node {
114 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115 for &byte in &self.data {
116 write!(f, "{:02x}", byte)?
117 }
118 Ok(())
119 }
120 }
121
122 #[derive(Debug)]
123 pub struct FromHexError;
124
125 /// Low level utility function, also for prefixes
126 fn get_nybble(s: &[u8], i: usize) -> u8 {
127 if i % 2 == 0 {
128 s[i / 2] >> 4
129 } else {
130 s[i / 2] & 0x0f
131 }
132 }
133
134 impl Node {
135 /// Retrieve the `i`th half-byte of the binary data.
136 ///
137 /// This is also the `i`th hexadecimal digit in numeric form,
138 /// also called a [nybble](https://en.wikipedia.org/wiki/Nibble).
139 pub fn get_nybble(&self, i: usize) -> u8 {
140 get_nybble(&self.data, i)
141 }
142
143 /// Length of the data, in nybbles
144 pub fn nybbles_len(&self) -> usize {
145 // public exposure as an instance method only, so that we can
146 // easily support several sizes of hashes if needed in the future.
147 NODE_NYBBLES_LENGTH
148 }
149
150 /// Convert from hexadecimal string representation
151 ///
152 /// Exact length is required.
153 ///
154 /// To be used in FFI and I/O only, in order to facilitate future
155 /// changes of hash format.
156 pub fn from_hex(hex: impl AsRef<[u8]>) -> Result<Node, FromHexError> {
157 let prefix = NodePrefix::from_hex(hex)?;
158 if prefix.nybbles_len() == NODE_NYBBLES_LENGTH {
159 Ok(Self { data: prefix.data })
160 } else {
161 Err(FromHexError)
162 }
163 }
164
165 /// `from_hex`, but for input from an internal file of the repository such
166 /// as a changelog or manifest entry.
167 ///
168 /// An error is treated as repository corruption.
169 pub fn from_hex_for_repo(hex: impl AsRef<[u8]>) -> Result<Node, HgError> {
170 Self::from_hex(hex.as_ref()).map_err(|FromHexError| {
171 HgError::corrupted(format!(
172 "Expected a full hexadecimal node ID, found {}",
173 String::from_utf8_lossy(hex.as_ref())
174 ))
175 })
176 }
177
178 /// Provide access to binary data
179 ///
180 /// This is needed by FFI layers, for instance to return expected
181 /// binary values to Python.
182 pub fn as_bytes(&self) -> &[u8] {
183 &self.data
184 }
185
186 pub fn short(&self) -> NodePrefix {
187 NodePrefix {
188 nybbles_len: SHORT_PREFIX_DEFAULT_NYBBLES_LENGTH,
189 data: self.data,
190 }
191 }
192
193 pub fn pad_to_256_bits(&self) -> [u8; 32] {
194 let mut bits = [0; 32];
195 bits[..NODE_BYTES_LENGTH].copy_from_slice(&self.data);
196 bits
197 }
198 }
199
200 /// The beginning of a binary revision SHA.
201 ///
202 /// Since it can potentially come from an hexadecimal representation with
203 /// odd length, it needs to carry around whether the last 4 bits are relevant
204 /// or not.
205 #[derive(Debug, PartialEq, Copy, Clone)]
206 pub struct NodePrefix {
207 /// In `1..=NODE_NYBBLES_LENGTH`
208 nybbles_len: u8,
209 /// The first `4 * length_in_nybbles` bits are used (considering bits
210 /// within a bytes in big-endian: most significant first), the rest
211 /// are zero.
212 data: NodeData,
213 }
214
215 impl NodePrefix {
216 /// Convert from hexadecimal string representation
217 ///
218 /// Similarly to `hex::decode`, can be used with Unicode string types
219 /// (`String`, `&str`) as well as bytes.
220 ///
221 /// To be used in FFI and I/O only, in order to facilitate future
222 /// changes of hash format.
223 pub fn from_hex(hex: impl AsRef<[u8]>) -> Result<Self, FromHexError> {
224 let hex = hex.as_ref();
225 let len = hex.len();
226 if len > NODE_NYBBLES_LENGTH || len == 0 {
227 return Err(FromHexError);
228 }
229
230 let mut data = [0; NODE_BYTES_LENGTH];
231 let mut nybbles_len = 0;
232 for &ascii_byte in hex {
233 let nybble = match char::from(ascii_byte).to_digit(16) {
234 Some(digit) => digit as u8,
235 None => return Err(FromHexError),
236 };
237 // Fill in the upper half of a byte first, then the lower half.
238 let shift = if nybbles_len % 2 == 0 { 4 } else { 0 };
239 data[nybbles_len as usize / 2] |= nybble << shift;
240 nybbles_len += 1;
241 }
242 Ok(Self { data, nybbles_len })
243 }
244
245 pub fn nybbles_len(&self) -> usize {
246 self.nybbles_len as _
247 }
248
249 pub fn is_prefix_of(&self, node: &Node) -> bool {
250 let full_bytes = self.nybbles_len() / 2;
251 if self.data[..full_bytes] != node.data[..full_bytes] {
252 return false;
253 }
254 if self.nybbles_len() % 2 == 0 {
255 return true;
256 }
257 let last = self.nybbles_len() - 1;
258 self.get_nybble(last) == node.get_nybble(last)
259 }
260
261 /// Retrieve the `i`th half-byte from the prefix.
262 ///
263 /// This is also the `i`th hexadecimal digit in numeric form,
264 /// also called a [nybble](https://en.wikipedia.org/wiki/Nibble).
265 pub fn get_nybble(&self, i: usize) -> u8 {
266 assert!(i < self.nybbles_len());
267 get_nybble(&self.data, i)
268 }
269
270 fn iter_nybbles(&self) -> impl Iterator<Item = u8> + '_ {
271 (0..self.nybbles_len()).map(move |i| get_nybble(&self.data, i))
272 }
273
274 /// Return the index first nybble that's different from `node`
275 ///
276 /// If the return value is `None` that means that `self` is
277 /// a prefix of `node`, but the current method is a bit slower
278 /// than `is_prefix_of`.
279 ///
280 /// Returned index is as in `get_nybble`, i.e., starting at 0.
281 pub fn first_different_nybble(&self, node: &Node) -> Option<usize> {
282 self.iter_nybbles()
283 .zip(NodePrefix::from(*node).iter_nybbles())
284 .position(|(a, b)| a != b)
285 }
286 }
287
288 impl fmt::LowerHex for NodePrefix {
289 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
290 let full_bytes = self.nybbles_len() / 2;
291 for &byte in &self.data[..full_bytes] {
292 write!(f, "{:02x}", byte)?
293 }
294 if self.nybbles_len() % 2 == 1 {
295 let last = self.nybbles_len() - 1;
296 write!(f, "{:x}", self.get_nybble(last))?
297 }
298 Ok(())
299 }
300 }
301
302 /// A shortcut for full `Node` references
303 impl From<&'_ Node> for NodePrefix {
304 fn from(node: &'_ Node) -> Self {
305 NodePrefix { nybbles_len: node.nybbles_len() as _, data: node.data }
306 }
307 }
308
309 /// A shortcut for full `Node` references
310 impl From<Node> for NodePrefix {
311 fn from(node: Node) -> Self {
312 NodePrefix { nybbles_len: node.nybbles_len() as _, data: node.data }
313 }
314 }
315
316 impl PartialEq<Node> for NodePrefix {
317 fn eq(&self, other: &Node) -> bool {
318 self.data == other.data && self.nybbles_len() == other.nybbles_len()
319 }
320 }
321
322 #[cfg(test)]
323 pub use tests::hex_pad_right;
324
325 #[cfg(test)]
326 mod tests {
327 use super::*;
328
329 const SAMPLE_NODE_HEX: &str = "0123456789abcdeffedcba9876543210deadbeef";
330 const SAMPLE_NODE: Node = Node {
331 data: [
332 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba,
333 0x98, 0x76, 0x54, 0x32, 0x10, 0xde, 0xad, 0xbe, 0xef,
334 ],
335 };
336
337 /// Pad an hexadecimal string to reach `NODE_NYBBLES_LENGTH`
338 /// The padding is made with zeros.
339 pub fn hex_pad_right(hex: &str) -> String {
340 let mut res = hex.to_string();
341 while res.len() < NODE_NYBBLES_LENGTH {
342 res.push('0');
343 }
344 res
345 }
346
347 #[test]
348 fn test_node_from_hex() {
349 let not_hex = "012... oops";
350 let too_short = "0123";
351 let too_long = format!("{}0", SAMPLE_NODE_HEX);
352 assert_eq!(Node::from_hex(SAMPLE_NODE_HEX).unwrap(), SAMPLE_NODE);
353 assert!(Node::from_hex(not_hex).is_err());
354 assert!(Node::from_hex(too_short).is_err());
355 assert!(Node::from_hex(too_long).is_err());
356 }
357
358 #[test]
359 fn test_node_encode_hex() {
360 assert_eq!(format!("{:x}", SAMPLE_NODE), SAMPLE_NODE_HEX);
361 }
362
363 #[test]
364 fn test_prefix_from_to_hex() -> Result<(), FromHexError> {
365 assert_eq!(format!("{:x}", NodePrefix::from_hex("0e1")?), "0e1");
366 assert_eq!(format!("{:x}", NodePrefix::from_hex("0e1a")?), "0e1a");
367 assert_eq!(
368 format!("{:x}", NodePrefix::from_hex(SAMPLE_NODE_HEX)?),
369 SAMPLE_NODE_HEX
370 );
371 Ok(())
372 }
373
374 #[test]
375 fn test_prefix_from_hex_errors() {
376 assert!(NodePrefix::from_hex("testgr").is_err());
377 let mut long = format!("{:x}", NULL_NODE);
378 long.push('c');
379 assert!(NodePrefix::from_hex(&long).is_err())
380 }
381
382 #[test]
383 fn test_is_prefix_of() -> Result<(), FromHexError> {
384 let mut node_data = [0; NODE_BYTES_LENGTH];
385 node_data[0] = 0x12;
386 node_data[1] = 0xca;
387 let node = Node::from(node_data);
388 assert!(NodePrefix::from_hex("12")?.is_prefix_of(&node));
389 assert!(!NodePrefix::from_hex("1a")?.is_prefix_of(&node));
390 assert!(NodePrefix::from_hex("12c")?.is_prefix_of(&node));
391 assert!(!NodePrefix::from_hex("12d")?.is_prefix_of(&node));
392 Ok(())
393 }
394
395 #[test]
396 fn test_get_nybble() -> Result<(), FromHexError> {
397 let prefix = NodePrefix::from_hex("dead6789cafe")?;
398 assert_eq!(prefix.get_nybble(0), 13);
399 assert_eq!(prefix.get_nybble(7), 9);
400 Ok(())
401 }
402
403 #[test]
404 fn test_first_different_nybble_even_prefix() {
405 let prefix = NodePrefix::from_hex("12ca").unwrap();
406 let mut node = Node::from([0; NODE_BYTES_LENGTH]);
407 assert_eq!(prefix.first_different_nybble(&node), Some(0));
408 node.data[0] = 0x13;
409 assert_eq!(prefix.first_different_nybble(&node), Some(1));
410 node.data[0] = 0x12;
411 assert_eq!(prefix.first_different_nybble(&node), Some(2));
412 node.data[1] = 0xca;
413 // now it is a prefix
414 assert_eq!(prefix.first_different_nybble(&node), None);
415 }
416
417 #[test]
418 fn test_first_different_nybble_odd_prefix() {
419 let prefix = NodePrefix::from_hex("12c").unwrap();
420 let mut node = Node::from([0; NODE_BYTES_LENGTH]);
421 assert_eq!(prefix.first_different_nybble(&node), Some(0));
422 node.data[0] = 0x13;
423 assert_eq!(prefix.first_different_nybble(&node), Some(1));
424 node.data[0] = 0x12;
425 assert_eq!(prefix.first_different_nybble(&node), Some(2));
426 node.data[1] = 0xca;
427 // now it is a prefix
428 assert_eq!(prefix.first_different_nybble(&node), None);
429 }
430 }