bitcoin_spv/
utils.rs

1extern crate hex;
2extern crate std;
3
4use std::{
5    format,
6    string::String,
7    vec::Vec, // The struct
8};
9
10/// Changes the endianness of a byte array.
11/// Returns a new, backwards, byte array.
12///
13/// # Arguments
14///
15/// * `b` - The bytes to reverse
16pub fn reverse_endianness(b: &[u8]) -> Vec<u8> {
17    b.iter().rev().copied().collect()
18}
19
20/// Strips the '0x' prefix off of hex string so it can be deserialized.
21///
22/// # Arguments
23///
24/// * `s` - The hex str
25pub fn strip_0x_prefix(s: &str) -> &str {
26    if &s[..2] == "0x" {
27        &s[2..]
28    } else {
29        s
30    }
31}
32
33/// Deserializes a hex string into a u8 array.
34///
35/// # Arguments
36///
37/// * `s` - The hex string
38pub fn deserialize_hex(s: &str) -> Result<Vec<u8>, hex::FromHexError> {
39    hex::decode(&strip_0x_prefix(s))
40}
41
42/// Serializes a u8 array into a hex string.
43///
44/// # Arguments
45///
46/// * `buf` - The value as a u8 array
47pub fn serialize_hex(buf: &[u8]) -> String {
48    format!("0x{}", hex::encode(buf))
49}
50
51/// Deserialize a hex string into bytes.
52/// Panics if the string is malformatted.
53///
54/// # Arguments
55///
56/// * `s` - The hex string
57///
58/// # Panics
59///
60/// When the string is not validly formatted hex.
61pub fn force_deserialize_hex(s: &str) -> Vec<u8> {
62    deserialize_hex(s).unwrap()
63}