nautilus_core/python/
enums.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 ::pyo3::exceptions::PyValueError;
17use ::strum::{IntoEnumIterator, ParseError};
18use pyo3::PyResult;
19
20/// Converts a raw string to the enum `E`, returning a nicely‑formatted
21/// `PyValueError` if the string does not match any variant.
22///
23/// The helper is aimed at Python‑exposed functions that still accept plain
24/// `&str` parameters internally: call `parse_enum` instead of writing repetitive
25/// `str::parse()` + error‑formatting logic yourself.
26///
27/// # Errors
28///
29/// Returns an error if `input` does not match any known variant of `E`.
30pub fn parse_enum<E>(input: &str, param: &str) -> PyResult<E>
31where
32    E: std::str::FromStr<Err = ParseError> + IntoEnumIterator + ToString,
33{
34    input.parse::<E>().map_err(|_| {
35        let allowed = E::iter()
36            .map(|v| v.to_string())
37            .collect::<Vec<_>>()
38            .join(", ");
39        PyValueError::new_err(format!(
40            "unknown {param} `{input}`; valid values: {allowed}"
41        ))
42    })
43}