nautilus_core/
parsing.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
16//! Core parsing functions.
17
18/// Returns the decimal precision inferred from the given string.
19///
20/// # Panics
21///
22/// Panics if the input string is not a valid decimal or scientific notation format.
23#[must_use]
24#[allow(clippy::cast_possible_truncation)]
25pub fn precision_from_str(s: &str) -> u8 {
26    let s = s.trim().to_ascii_lowercase();
27
28    // Check for scientific notation
29    if s.contains("e-") {
30        // SAFETY: Double unwrap is acceptable here because:
31        // 1. We already validated the string contains "e-"
32        // 2. Function is used only for parsing valid numeric strings in controlled contexts
33        // 3. Alternative error handling would complicate the API for minimal benefit
34        return s.split("e-").last().unwrap().parse::<u8>().unwrap();
35    }
36
37    // Check for decimal precision
38    if let Some((_, decimal_part)) = s.split_once('.') {
39        // Clamp decimal precision to u8::MAX for very long decimal strings
40        decimal_part.len().min(u8::MAX as usize) as u8
41    } else {
42        0
43    }
44}
45
46/// Returns the minimum increment precision inferred from the given string,
47/// ignoring trailing zeros.
48#[must_use]
49#[allow(clippy::cast_possible_truncation)]
50pub fn min_increment_precision_from_str(s: &str) -> u8 {
51    let s = s.trim().to_ascii_lowercase();
52
53    // Check for scientific notation
54    if let Some(pos) = s.find('e') {
55        if s[pos + 1..].starts_with('-') {
56            return s[pos + 2..].parse::<u8>().unwrap_or(0);
57        }
58    }
59
60    // Check for decimal precision
61    if let Some(dot_pos) = s.find('.') {
62        let decimal_part = &s[dot_pos + 1..];
63        if decimal_part.chars().any(|c| c != '0') {
64            let trimmed_len = decimal_part.trim_end_matches('0').len();
65            return trimmed_len.min(u8::MAX as usize) as u8;
66        }
67        return decimal_part.len().min(u8::MAX as usize) as u8;
68    }
69
70    0
71}
72
73/// Returns a `usize` from the given bytes.
74///
75/// # Errors
76///
77/// Returns an error if there are not enough bytes to represent a `usize`.
78pub fn bytes_to_usize(bytes: &[u8]) -> anyhow::Result<usize> {
79    // Check bytes width
80    if bytes.len() >= std::mem::size_of::<usize>() {
81        let mut buffer = [0u8; std::mem::size_of::<usize>()];
82        buffer.copy_from_slice(&bytes[..std::mem::size_of::<usize>()]);
83
84        Ok(usize::from_le_bytes(buffer))
85    } else {
86        anyhow::bail!("Not enough bytes to represent a `usize`");
87    }
88}
89
90////////////////////////////////////////////////////////////////////////////////
91// Tests
92////////////////////////////////////////////////////////////////////////////////
93#[cfg(test)]
94mod tests {
95    use rstest::rstest;
96
97    use super::*;
98
99    #[rstest]
100    #[case("", 0)]
101    #[case("0", 0)]
102    #[case("1.0", 1)]
103    #[case("1.00", 2)]
104    #[case("1.23456789", 8)]
105    #[case("123456.789101112", 9)]
106    #[case("0.000000001", 9)]
107    #[case("1e-1", 1)]
108    #[case("1e-2", 2)]
109    #[case("1e-3", 3)]
110    #[case("1e8", 0)]
111    #[case("-1.23", 2)]
112    #[case("-1e-2", 2)]
113    #[case("1E-2", 2)]
114    #[case("  1.23", 2)]
115    #[case("1.23  ", 2)]
116    fn test_precision_from_str(#[case] s: &str, #[case] expected: u8) {
117        let result = precision_from_str(s);
118        assert_eq!(result, expected);
119    }
120
121    #[rstest]
122    #[case("", 0)]
123    #[case("0", 0)]
124    #[case("1.0", 1)]
125    #[case("1.00", 2)]
126    #[case("1.23456789", 8)]
127    #[case("123456.789101112", 9)]
128    #[case("0.000000001", 9)]
129    #[case("1e-1", 1)]
130    #[case("1e-2", 2)]
131    #[case("1e-3", 3)]
132    #[case("1e8", 0)]
133    #[case("-1.23", 2)]
134    #[case("-1e-2", 2)]
135    #[case("1E-2", 2)]
136    #[case("  1.23", 2)]
137    #[case("1.23  ", 2)]
138    #[case("1.010", 2)]
139    #[case("1.00100", 3)]
140    #[case("0.0001000", 4)]
141    #[case("1.000000000", 9)]
142    fn test_min_increment_precision_from_str(#[case] s: &str, #[case] expected: u8) {
143        let result = min_increment_precision_from_str(s);
144        assert_eq!(result, expected);
145    }
146
147    #[rstest]
148    fn test_bytes_to_usize_empty() {
149        let payload: Vec<u8> = vec![];
150        let result = bytes_to_usize(&payload);
151        assert!(result.is_err());
152        assert_eq!(
153            result.err().unwrap().to_string(),
154            "Not enough bytes to represent a `usize`"
155        );
156    }
157
158    #[rstest]
159    fn test_bytes_to_usize_invalid() {
160        let payload: Vec<u8> = vec![0x01, 0x02, 0x03];
161        let result = bytes_to_usize(&payload);
162        assert!(result.is_err());
163        assert_eq!(
164            result.err().unwrap().to_string(),
165            "Not enough bytes to represent a `usize`"
166        );
167    }
168
169    #[rstest]
170    fn test_bytes_to_usize_valid() {
171        let payload: Vec<u8> = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
172        let result = bytes_to_usize(&payload).unwrap();
173        assert_eq!(result, 0x0807_0605_0403_0201);
174        assert_eq!(result, 578_437_695_752_307_201);
175    }
176}