wallet_gen/
hex_slice.rs

1/*
2 * hex_slice.rs
3 *
4 * Copyright 2018 Standard Mining
5 *
6 * Available to be used and modified under the terms of the MIT License.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
9 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
10 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
11 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
12 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
13 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14 */
15
16//! Helper struct to easily create hex bytestrings from byte slices.
17
18use std::fmt;
19use std::ops::Deref;
20
21/// A wrapper around a `&[u8]` byte slice that implements
22/// various formatting traits, such as [`Display`],
23/// [`LowerHex`], and [`UpperHex`] so it can be conveniently
24/// used to format byte strings.
25///
26/// [`Display`]: https://doc.rust-lang.org/stable/std/fmt/trait.Display.html
27/// [`UpperHex`]: https://doc.rust-lang.org/stable/std/fmt/trait.UpperHex.html
28/// [`LowerHex`]: https://doc.rust-lang.org/stable/std/fmt/trait.LowerHex.html
29#[derive(Debug, Copy, Clone, Hash)]
30pub struct HexSlice<'a>(&'a [u8]);
31
32impl<'a> HexSlice<'a> {
33    /// Creates a new [`HexSlice`].
34    ///
35    /// [`HexSlice`]: ./struct.HexSlice.html
36    pub fn new<T>(data: &'a T) -> Self
37    where T: ?Sized + AsRef<[u8]> + 'a {
38        HexSlice(data.as_ref())
39    }
40
41    /// Format the byte slice into a [`String`].
42    ///
43    /// [`String`]: https://doc.rust-lang.org/stable/std/string/struct.String.html
44    pub fn format(&self) -> String { format!("{:x}", self) }
45}
46
47impl<'a> Deref for HexSlice<'a> {
48    type Target = [u8];
49
50    fn deref(&self) -> &Self::Target { self.0 }
51}
52
53impl<'a> AsRef<[u8]> for HexSlice<'a> {
54    fn as_ref(&self) -> &[u8] { self.0 }
55}
56
57impl<'a> fmt::Display for HexSlice<'a> {
58    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:x}", self) }
59}
60
61impl<'a> fmt::LowerHex for HexSlice<'a> {
62    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63        for byte in self.0 {
64            write!(f, "{:02x}", byte)?;
65        }
66        Ok(())
67    }
68}
69
70impl<'a> fmt::UpperHex for HexSlice<'a> {
71    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
72        for byte in self.0 {
73            write!(f, "{:02X}", byte)?;
74        }
75        Ok(())
76    }
77}