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