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 helpers 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    #[allow(
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    #[allow(
99        clippy::unnecessary_wraps,
100        reason = "Python FFI requires Result return type"
101    )]
102    fn _safe_constructor() -> PyResult<Self> {
103        Ok(Self::new()) // Safe default
104    }
105
106    /// Compares two `UUID4` instances for equality
107    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
108        match op {
109            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
110            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
111            _ => py.NotImplemented(),
112        }
113    }
114
115    /// Returns a hash value for the `UUID4` instance.
116    #[allow(
117        clippy::cast_possible_truncation,
118        clippy::cast_possible_wrap,
119        reason = "Intentional cast for Python interop"
120    )]
121    fn __hash__(&self) -> isize {
122        let mut h = DefaultHasher::new();
123        self.hash(&mut h);
124        h.finish() as isize
125    }
126
127    /// Returns a detailed string representation of the `UUID4` instance.
128    fn __repr__(&self) -> String {
129        format!("{self:?}")
130    }
131
132    /// Returns the `UUID4` as a string.
133    fn __str__(&self) -> String {
134        self.to_string()
135    }
136
137    /// Gets the `UUID4` value as a string.
138    #[getter]
139    #[pyo3(name = "value")]
140    fn py_value(&self) -> String {
141        self.to_string()
142    }
143
144    /// Creates a new [`UUID4`] from a string representation.
145    #[staticmethod]
146    #[pyo3(name = "from_str")]
147    fn py_from_str(value: &str) -> PyResult<Self> {
148        Self::from_str(value).map_err(to_pyvalue_err)
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use std::sync::Once;
155
156    use pyo3::Python;
157    use rstest::rstest;
158
159    use super::*;
160
161    fn ensure_python_initialized() {
162        static INIT: Once = Once::new();
163        INIT.call_once(|| {
164            Python::initialize();
165        });
166    }
167
168    #[rstest]
169    fn test_setstate_rejects_invalid_uuid_bytes() {
170        ensure_python_initialized();
171        Python::attach(|py| {
172            let mut uuid = UUID4::new();
173            let mut invalid = [b'a'; UUID4_LEN];
174            invalid[UUID4_LEN - 1] = 0;
175            let py_bytes = PyBytes::new(py, &invalid);
176            let err = uuid
177                .__setstate__(py, py_bytes.into_py_any_unwrap(py))
178                .expect_err("expected invalid state to error");
179            assert!(err.to_string().contains("Invalid state for deserializing"));
180        });
181    }
182
183    #[rstest]
184    fn test_setstate_rejects_missing_null_terminator() {
185        ensure_python_initialized();
186        Python::attach(|py| {
187            let mut uuid = UUID4::new();
188            let mut bytes = uuid.value;
189            bytes[UUID4_LEN - 1] = b'0';
190            let py_bytes = PyBytes::new(py, &bytes);
191            let err = uuid
192                .__setstate__(py, py_bytes.into_py_any_unwrap(py))
193                .expect_err("expected missing NUL terminator to error");
194            assert!(
195                err.to_string()
196                    .contains("Invalid state for deserializing, missing null terminator")
197            );
198        });
199    }
200
201    #[rstest]
202    fn test_setstate_accepts_valid_state() {
203        ensure_python_initialized();
204        Python::attach(|py| {
205            let source = UUID4::new();
206            let mut target = UUID4::new();
207            let py_bytes = PyBytes::new(py, &source.value);
208            target
209                .__setstate__(py, py_bytes.into_py_any_unwrap(py))
210                .expect("valid state should succeed");
211            assert_eq!(target.to_string(), source.to_string());
212        });
213    }
214}