nautilus_model/defi/
hex.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
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// -------------------------------------------------------------------------------------------------
15
16use nautilus_core::{UnixNanos, datetime::NANOSECONDS_IN_SECOND};
17use serde::{Deserialize, Deserializer};
18
19/// Converts a hexadecimal string to a u64 integer.
20///
21/// # Errors
22///
23/// Returns a `std::num::ParseIntError` if:
24/// - The input string contains non-hexadecimal characters
25/// - The hexadecimal value is too large to fit in a u64
26pub fn from_str_hex_to_u64(hex_string: &str) -> Result<u64, std::num::ParseIntError> {
27    let without_prefix = hex_string.trim_start_matches("0x");
28    u64::from_str_radix(without_prefix, 16)
29}
30
31/// Custom deserializer function for hex numbers.
32///
33/// # Errors
34///
35/// Returns an error if parsing the hex string to a number fails.
36pub fn deserialize_hex_number<'de, D>(deserializer: D) -> Result<u64, D::Error>
37where
38    D: Deserializer<'de>,
39{
40    let hex_string = String::deserialize(deserializer)?;
41    from_str_hex_to_u64(hex_string.as_str()).map_err(serde::de::Error::custom)
42}
43
44/// Custom deserializer function for hex timestamps to convert hex seconds to `UnixNanos`.
45///
46/// # Errors
47///
48/// Returns an error if parsing the hex string to a timestamp fails.
49pub fn deserialize_hex_timestamp<'de, D>(deserializer: D) -> Result<UnixNanos, D::Error>
50where
51    D: Deserializer<'de>,
52{
53    let hex_string = String::deserialize(deserializer)?;
54    from_str_hex_to_u64(hex_string.as_str())
55        .map(|num| UnixNanos::new(num * NANOSECONDS_IN_SECOND))
56        .map_err(serde::de::Error::custom)
57}