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