Skip to main content

nautilus_core/python/
uuid.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//! UUID bindings for PyO3.
17
18use std::{
19    collections::hash_map::DefaultHasher,
20    ffi::CStr,
21    hash::{Hash, Hasher},
22    str::FromStr,
23};
24
25use pyo3::{
26    IntoPyObjectExt, Py,
27    prelude::*,
28    pyclass::CompareOp,
29    types::{PyBytes, PyTuple},
30};
31
32use super::{IntoPyObjectNautilusExt, to_pyvalue_err};
33use crate::uuid::{UUID4, UUID4_LEN};
34
35#[pymethods]
36#[pyo3_stub_gen::derive::gen_stub_pymethods]
37impl UUID4 {
38    /// Represents a Universally Unique Identifier (UUID)
39    /// version 4 based on a 128-bit label as specified in RFC 4122.
40    #[new]
41    fn py_new() -> Self {
42        Self::new()
43    }
44
45    /// Sets the state of the `UUID4` instance during unpickling.
46    #[expect(
47        clippy::needless_pass_by_value,
48        reason = "Python FFI requires owned types"
49    )]
50    fn __setstate__(&mut self, py: Python<'_>, state: Py<PyAny>) -> PyResult<()> {
51        let bytes: &Bound<'_, PyBytes> = state.cast_bound::<PyBytes>(py)?;
52        let slice = bytes.as_bytes();
53
54        if slice.len() != UUID4_LEN {
55            return Err(to_pyvalue_err(
56                "Invalid state for deserializing, incorrect bytes length",
57            ));
58        }
59
60        if slice[UUID4_LEN - 1] != 0 {
61            return Err(to_pyvalue_err(
62                "Invalid state for deserializing, missing null terminator",
63            ));
64        }
65
66        let cstr = CStr::from_bytes_with_nul(slice).map_err(|_| {
67            to_pyvalue_err("Invalid state for deserializing, bytes must be null-terminated UTF-8")
68        })?;
69
70        let value = cstr.to_str().map_err(|_| {
71            to_pyvalue_err("Invalid state for deserializing, bytes must be valid UTF-8")
72        })?;
73
74        let parsed = Self::from_str(value).map_err(|e| {
75            to_pyvalue_err(format!(
76                "Invalid state for deserializing, unable to parse UUID: {e}"
77            ))
78        })?;
79
80        self.value.copy_from_slice(&parsed.value);
81        Ok(())
82    }
83
84    /// Gets the state of the `UUID4` instance for pickling.
85    fn __getstate__(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
86        PyBytes::new(py, &self.value).into_py_any(py)
87    }
88
89    /// Reduces the `UUID4` instance for pickling.
90    fn __reduce__(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
91        let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
92        let state = self.__getstate__(py)?;
93        (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
94    }
95
96    /// A safe constructor used during unpickling to ensure the correct initialization of `UUID4`.
97    #[staticmethod]
98    #[pyo3(name = "_safe_constructor")]
99    #[expect(
100        clippy::unnecessary_wraps,
101        reason = "Python FFI requires Result return type"
102    )]
103    fn py_safe_constructor() -> PyResult<Self> {
104        Ok(Self::new()) // Safe default
105    }
106
107    /// Compares two `UUID4` instances for equality
108    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
109        match op {
110            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
111            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
112            _ => py.NotImplemented(),
113        }
114    }
115
116    /// Returns a hash value for the `UUID4` instance.
117    #[expect(
118        clippy::cast_possible_truncation,
119        clippy::cast_possible_wrap,
120        reason = "Intentional cast for Python interop"
121    )]
122    fn __hash__(&self) -> isize {
123        let mut h = DefaultHasher::new();
124        self.hash(&mut h);
125        h.finish() as isize
126    }
127
128    /// Returns a detailed string representation of the `UUID4` instance.
129    fn __repr__(&self) -> String {
130        format!("{self:?}")
131    }
132
133    /// Returns the `UUID4` as a string.
134    fn __str__(&self) -> String {
135        self.to_string()
136    }
137
138    /// Gets the `UUID4` value as a string.
139    #[getter]
140    #[pyo3(name = "value")]
141    fn py_value(&self) -> String {
142        self.to_string()
143    }
144
145    /// Creates a new [`UUID4`] from a string representation.
146    #[staticmethod]
147    #[pyo3(name = "from_str")]
148    fn py_from_str(value: &str) -> PyResult<Self> {
149        Self::from_str(value).map_err(to_pyvalue_err)
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use std::sync::Once;
156
157    use pyo3::Python;
158    use rstest::rstest;
159
160    use super::*;
161
162    fn ensure_python_initialized() {
163        static INIT: Once = Once::new();
164        INIT.call_once(|| {
165            Python::initialize();
166        });
167    }
168
169    #[rstest]
170    fn test_reduce_reconstructs_uuid() {
171        ensure_python_initialized();
172        Python::attach(|py| {
173            let source = UUID4::from_str("2d89666b-1a1e-4a75-b193-4eb3b454c757").unwrap();
174            let reduced = source.__reduce__(py).unwrap();
175            let (constructor, args, state): (Py<PyAny>, Py<PyTuple>, Py<PyAny>) =
176                reduced.extract(py).unwrap();
177            let restored = constructor.call1(py, args).unwrap();
178            restored.call_method1(py, "__setstate__", (state,)).unwrap();
179
180            assert_eq!(restored.extract::<UUID4>(py).unwrap(), source);
181        });
182    }
183
184    #[rstest]
185    fn test_setstate_rejects_invalid_uuid_bytes() {
186        ensure_python_initialized();
187        Python::attach(|py| {
188            let mut uuid = UUID4::new();
189            let mut invalid = [b'a'; UUID4_LEN];
190            invalid[UUID4_LEN - 1] = 0;
191            let py_bytes = PyBytes::new(py, &invalid);
192            let err = uuid
193                .__setstate__(py, py_bytes.into_py_any_unwrap(py))
194                .expect_err("expected invalid state to error");
195            assert!(err.to_string().contains("Invalid state for deserializing"));
196        });
197    }
198
199    #[rstest]
200    fn test_setstate_rejects_missing_null_terminator() {
201        ensure_python_initialized();
202        Python::attach(|py| {
203            let mut uuid = UUID4::new();
204            let mut bytes = uuid.value;
205            bytes[UUID4_LEN - 1] = b'0';
206            let py_bytes = PyBytes::new(py, &bytes);
207            let err = uuid
208                .__setstate__(py, py_bytes.into_py_any_unwrap(py))
209                .expect_err("expected missing NUL terminator to error");
210            assert!(
211                err.to_string()
212                    .contains("Invalid state for deserializing, missing null terminator")
213            );
214        });
215    }
216
217    #[rstest]
218    fn test_setstate_accepts_valid_state() {
219        ensure_python_initialized();
220        Python::attach(|py| {
221            let source = UUID4::new();
222            let mut target = UUID4::new();
223            let py_bytes = PyBytes::new(py, &source.value);
224            target
225                .__setstate__(py, py_bytes.into_py_any_unwrap(py))
226                .expect("valid state should succeed");
227            assert_eq!(target.to_string(), source.to_string());
228        });
229    }
230}