ink_metadata/
utils.rs

1// Copyright (C) Use Ink (UK) Ltd.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::serde_hex;
16use std::str;
17
18/// Serializes the given bytes as byte string.
19pub fn serialize_as_byte_str<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
20where
21    S: serde::Serializer,
22{
23    if bytes.is_empty() {
24        // Return empty string without prepended `0x`.
25        return serializer.serialize_str("")
26    }
27    serde_hex::serialize(bytes, serializer)
28}
29
30/// Deserializes the given hex string with optional `0x` prefix.
31pub fn deserialize_from_byte_str<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
32where
33    D: serde::Deserializer<'de>,
34{
35    struct Visitor;
36
37    impl serde::de::Visitor<'_> for Visitor {
38        type Value = Vec<u8>;
39
40        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
41            write!(formatter, "hex string with optional 0x prefix")
42        }
43
44        fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
45            let result = if v.starts_with("0x") {
46                serde_hex::from_hex(v)
47            } else {
48                serde_hex::from_hex(&format!("0x{v}"))
49            };
50            result.map_err(E::custom)
51        }
52
53        fn visit_string<E: serde::de::Error>(self, v: String) -> Result<Self::Value, E> {
54            self.visit_str(&v)
55        }
56    }
57
58    deserializer.deserialize_str(Visitor)
59}
60
61/// Strips a single whitespace at the start and removes trailing spaces
62pub fn trim_extra_whitespace(item: &str) -> &str {
63    if let Some(stripped) = item.strip_prefix(' ') {
64        stripped.trim_end()
65    } else {
66        item.trim_end()
67    }
68}