scale_value/string_impls/custom_formatters/
hex.rs

1// Copyright (C) 2022-2024 Parity Technologies (UK) Ltd. (admin@parity.io)
2// This file is a part of the scale-value crate.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//         http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use crate::prelude::*;
17use crate::{Composite, Primitive, Value, ValueDef};
18use core::fmt::Write;
19
20/// This can be used alongside [`crate::stringify::ToWriterBuilder::add_custom_formatter()`] (which
21/// itself is constructed via [`crate::stringify::to_writer_custom()`]). It will format as a hex
22/// string any unnamed composite whose values are all primitives in the range 0-255 inclusive.
23///
24/// # Example
25///
26/// ```rust
27/// use scale_value::{value,Value};
28/// use scale_value::stringify::{to_writer_custom, custom_formatters::format_hex};
29///
30/// let val = value!({
31///     foo: (1u64,2u64,3u64,4u64,5u64),
32///     bar: (1000u64, 10u64)
33/// });
34///
35/// let mut s = String::new();
36///
37/// to_writer_custom()
38///     .add_custom_formatter(|v, w| format_hex(v, w))
39///     .write(&val, &mut s)
40///     .unwrap();
41///
42/// assert_eq!(s, r#"{ foo: 0x0102030405, bar: (1000, 10) }"#);
43/// ```
44pub fn format_hex<T, W: Write>(value: &Value<T>, writer: W) -> Option<core::fmt::Result> {
45    // Print unnamed sequences of u8s as hex strings; ignore anything else.
46    if let ValueDef::Composite(Composite::Unnamed(vals)) = &value.value {
47        if vals.is_empty() {
48            return None;
49        }
50        for val in vals {
51            if !matches!(val.value, ValueDef::Primitive(Primitive::U128(n)) if n < 256) {
52                return None;
53            }
54        }
55        Some(value_to_hex(vals, writer))
56    } else {
57        None
58    }
59}
60
61// Just to avoid needing to import the `hex` dependency just for this.
62fn value_to_hex<T, W: core::fmt::Write>(vals: &Vec<Value<T>>, mut writer: W) -> core::fmt::Result {
63    writer.write_str("0x")?;
64    for val in vals {
65        if let ValueDef::Primitive(Primitive::U128(n)) = &val.value {
66            let n = *n as u8;
67            writer.write_char(u4_to_hex(n >> 4))?;
68            writer.write_char(u4_to_hex(n & 0b00001111))?;
69        }
70    }
71    Ok(())
72}
73
74fn u4_to_hex(n: u8) -> char {
75    static HEX: [char; 16] =
76        ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
77    *HEX.get(n as usize).expect("Expected a u4 (value between 0..=15")
78}
79
80#[cfg(test)]
81mod test {
82    use super::*;
83    use crate::value;
84
85    #[test]
86    fn test_value_to_hex() {
87        let mut s = String::new();
88        format_hex(&value! {(0usize,230usize,255usize,15usize,12usize,4usize)}, &mut s)
89            .expect("decided not to convert to hex")
90            .expect("can't write to writer without issues");
91
92        assert_eq!(s, "0x00E6FF0F0C04");
93    }
94
95    #[test]
96    fn test_value_not_to_hex() {
97        let mut s = String::new();
98        // 256 is too big to be a u8, so this value isn't valid hex.
99        assert_eq!(format_hex(&value! {(0usize,230usize,256usize)}, &mut s), None);
100    }
101}