1use std::str::FromStr;
4use std::sync::OnceLock;
5
6use pyo3::prelude::*;
7use pyo3::types::{PyString, PyTuple};
8
9use synta::ObjectIdentifier;
10
11pub mod elements;
12pub mod primitives;
13pub mod strings;
14
15pub use elements::{element_to_pyobject, PyRawElement, PyTaggedElement};
16pub use primitives::{
17 PyBitString, PyBoolean, PyGeneralizedTime, PyInteger, PyNull, PyOctetString, PyReal, PyUtcTime,
18};
19pub use strings::{
20 PyBmpString, PyGeneralString, PyIA5String, PyNumericString, PyPrintableString, PyTeletexString,
21 PyUniversalString, PyUtf8String, PyVisibleString,
22};
23
24#[pyclass(frozen, name = "ObjectIdentifier")]
37#[derive(Debug, Clone)]
38pub struct PyObjectIdentifier {
39 pub(crate) inner: ObjectIdentifier,
40 dotted_cache: OnceLock<String>,
43}
44
45impl PyObjectIdentifier {
46 pub fn from_oid(inner: ObjectIdentifier) -> Self {
49 Self {
50 inner,
51 dotted_cache: OnceLock::new(),
52 }
53 }
54}
55
56#[pymethods]
57impl PyObjectIdentifier {
58 #[new]
60 fn new(oid_str: &str) -> PyResult<Self> {
61 let inner = ObjectIdentifier::from_str(oid_str)
62 .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid OID: {e:?}")))?;
63 Ok(Self {
64 inner,
65 dotted_cache: OnceLock::new(),
66 })
67 }
68
69 #[staticmethod]
71 fn from_components(components: Vec<u32>) -> PyResult<Self> {
72 let inner = ObjectIdentifier::new(&components)
73 .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid OID: {e:?}")))?;
74 Ok(Self {
75 inner,
76 dotted_cache: OnceLock::new(),
77 })
78 }
79
80 #[staticmethod]
93 fn from_der_value(data: &[u8]) -> PyResult<Self> {
94 let inner = ObjectIdentifier::from_content_bytes(data).map_err(|e| {
95 pyo3::exceptions::PyValueError::new_err(format!("Invalid OID content: {e:?}"))
96 })?;
97 Ok(Self {
98 inner,
99 dotted_cache: OnceLock::new(),
100 })
101 }
102
103 fn components<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyTuple>> {
105 PyTuple::new(py, self.inner.components())
106 }
107
108 fn __str__(&self) -> &str {
109 self.dotted_cache.get_or_init(|| self.inner.to_string())
110 }
111
112 fn __repr__(&self) -> String {
113 format!(
114 "ObjectIdentifier('{}')",
115 self.dotted_cache.get_or_init(|| self.inner.to_string())
116 )
117 }
118
119 fn __eq__(&self, other: &Bound<'_, PyAny>) -> bool {
122 if let Ok(other_oid) = other.extract::<PyRef<PyObjectIdentifier>>() {
123 return self.inner == other_oid.inner;
124 }
125 if let Ok(s) = other.extract::<String>() {
126 return self.dotted_cache.get_or_init(|| self.inner.to_string()) == &s;
127 }
128 false
129 }
130
131 fn __hash__(&self, py: Python<'_>) -> PyResult<isize> {
135 PyString::new(py, self.dotted_cache.get_or_init(|| self.inner.to_string())).hash()
136 }
137}