##// END OF EJS Templates
rust: replace an unsafe use of transmute with a safe use of bytes-cast...
Simon Sapin -
r47120:cfb6c10c default
parent child Browse files
Show More
@@ -8,8 +8,9 b''
8 8 //! In Mercurial code base, it is customary to call "a node" the binary SHA
9 9 //! of a revision.
10 10
11 use bytes_cast::BytesCast;
11 12 use hex::{self, FromHex, FromHexError};
12 use std::convert::{TryFrom, TryInto};
13 use std::convert::TryFrom;
13 14
14 15 /// The length in bytes of a `Node`
15 16 ///
@@ -49,7 +50,7 b' type NodeData = [u8; NODE_BYTES_LENGTH];'
49 50 ///
50 51 /// [`nybbles_len`]: #method.nybbles_len
51 52 /// [`ExactLengthRequired`]: struct.NodeError#variant.ExactLengthRequired
52 #[derive(Clone, Debug, PartialEq)]
53 #[derive(Clone, Debug, PartialEq, BytesCast)]
53 54 #[repr(transparent)]
54 55 pub struct Node {
55 56 data: NodeData,
@@ -68,14 +69,14 b' impl From<NodeData> for Node {'
68 69
69 70 /// Return an error if the slice has an unexpected length
70 71 impl<'a> TryFrom<&'a [u8]> for &'a Node {
71 type Error = std::array::TryFromSliceError;
72 type Error = ();
72 73
73 74 #[inline]
74 75 fn try_from(bytes: &'a [u8]) -> Result<&'a Node, Self::Error> {
75 let data = bytes.try_into()?;
76 // Safety: `#[repr(transparent)]` makes it ok to "wrap" the target
77 // of a reference to the type of the single field.
78 Ok(unsafe { std::mem::transmute::<&NodeData, &Node>(data) })
76 match Node::from_bytes(bytes) {
77 Ok((node, rest)) if rest.is_empty() => Ok(node),
78 _ => Err(()),
79 }
79 80 }
80 81 }
81 82
General Comments 0
You need to be logged in to leave comments. Login now