synta-python 0.1.4

Python extension module for the synta ASN.1 library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Python wrappers for primitive ASN.1 types: INTEGER, OCTET STRING, BIT STRING,
//! BOOLEAN, UTCTime, GeneralizedTime, REAL, NULL.

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use pyo3::exceptions::{PyOverflowError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::PyBytes;

use synta::{BitString, Boolean, GeneralizedTime, Integer, OctetString, Real, UtcTime};

/// Python wrapper for ASN.1 INTEGER
#[pyclass(name = "Integer")]
#[derive(Debug, Clone)]
pub struct PyInteger {
    pub(crate) inner: Integer,
}

#[pymethods]
impl PyInteger {
    /// Create a new Integer from a Python int
    #[new]
    fn new(value: i64) -> Self {
        Self {
            inner: Integer::from_i64(value),
        }
    }

    /// Convert to Python int (i64)
    fn to_int(&self) -> PyResult<i64> {
        self.inner
            .as_i64()
            .map_err(|_| PyOverflowError::new_err("Integer too large for i64"))
    }

    /// Get the raw bytes (big-endian two's complement)
    fn to_bytes<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, self.inner.as_bytes())
    }

    /// Create Integer from raw bytes
    #[staticmethod]
    fn from_bytes(bytes: &[u8]) -> Self {
        Self {
            inner: Integer::from_bytes(bytes),
        }
    }

    /// Create Integer from an unsigned 64-bit value
    #[staticmethod]
    fn from_u64(value: u64) -> Self {
        Self {
            inner: Integer::from_u64(value),
        }
    }

    /// Convert to Python int (i128) for larger integers
    fn to_i128(&self) -> PyResult<i128> {
        self.inner
            .as_i128()
            .map_err(|_| PyOverflowError::new_err("Integer too large for i128"))
    }

    fn __eq__(&self, other: &Self) -> bool {
        // DER encodes integers with minimal bytes (no redundant leading zeros),
        // so comparing the raw bytes is equivalent to comparing by value.
        self.inner.as_bytes() == other.inner.as_bytes()
    }

    fn __hash__(&self) -> u64 {
        let mut h = DefaultHasher::new();
        self.inner.as_bytes().hash(&mut h);
        h.finish()
    }

    fn __repr__(&self) -> PyResult<String> {
        match self.inner.as_i64() {
            Ok(val) => Ok(format!("Integer({})", val)),
            Err(_) => Ok(format!("Integer(<{} bytes>)", self.inner.as_bytes().len())),
        }
    }

    fn __str__(&self) -> PyResult<String> {
        match self.inner.as_i64() {
            Ok(val) => Ok(val.to_string()),
            Err(_) => Ok(format!("<integer {} bytes>", self.inner.as_bytes().len())),
        }
    }
}

/// Python wrapper for ASN.1 OCTET STRING
#[pyclass(name = "OctetString")]
#[derive(Debug, Clone)]
pub struct PyOctetString {
    pub(crate) inner: OctetString,
}

#[pymethods]
impl PyOctetString {
    /// Create a new OctetString from bytes
    #[new]
    fn new(data: Vec<u8>) -> Self {
        Self {
            inner: OctetString::new(data),
        }
    }

    /// Get the bytes as a Python bytes object
    fn to_bytes<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, self.inner.as_bytes())
    }

    /// Get the length
    fn __len__(&self) -> usize {
        self.inner.as_bytes().len()
    }

    fn __eq__(&self, other: &Self) -> bool {
        self.inner == other.inner
    }

    fn __repr__(&self) -> String {
        format!("OctetString(<{} bytes>)", self.inner.as_bytes().len())
    }
}

/// Python wrapper for ASN.1 BIT STRING
#[pyclass(name = "BitString")]
#[derive(Debug, Clone)]
pub struct PyBitString {
    pub(crate) inner: BitString,
}

#[pymethods]
impl PyBitString {
    /// Create a new BitString from bytes and unused bits count
    #[new]
    fn new(data: Vec<u8>, unused_bits: u8) -> PyResult<Self> {
        if unused_bits > 7 {
            return Err(PyValueError::new_err("unused_bits must be 0-7"));
        }
        let inner = BitString::new(data, unused_bits)
            .map_err(|e| PyValueError::new_err(format!("Invalid BitString: {:?}", e)))?;
        Ok(Self { inner })
    }

    /// Get the bytes
    fn to_bytes<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, self.inner.as_bytes())
    }

    /// Get the number of unused bits in the last byte
    fn unused_bits(&self) -> u8 {
        self.inner.unused_bits()
    }

    /// Get the number of bits
    fn bit_len(&self) -> usize {
        self.inner.bit_len()
    }

    fn __len__(&self) -> usize {
        self.inner.bit_len()
    }

    fn __eq__(&self, other: &Self) -> bool {
        self.inner == other.inner
    }

    fn __repr__(&self) -> String {
        format!(
            "BitString(<{} bits, {} unused>)",
            self.inner.bit_len(),
            self.inner.unused_bits()
        )
    }
}

/// Python wrapper for ASN.1 BOOLEAN
#[pyclass(name = "Boolean")]
#[derive(Debug, Clone, Copy)]
pub struct PyBoolean {
    pub(crate) inner: Boolean,
}

#[pymethods]
impl PyBoolean {
    /// Create a new Boolean
    #[new]
    fn new(value: bool) -> Self {
        Self {
            inner: Boolean::new(value),
        }
    }

    /// Get the boolean value
    fn value(&self) -> bool {
        self.inner.value()
    }

    fn __bool__(&self) -> bool {
        self.inner.value()
    }

    fn __eq__(&self, other: &Self) -> bool {
        self.inner.value() == other.inner.value()
    }

    fn __hash__(&self) -> isize {
        // Matches Python's hash(True) == 1, hash(False) == 0.
        self.inner.value() as isize
    }

    fn __repr__(&self) -> String {
        format!("Boolean({})", self.inner.value())
    }
}

/// Python wrapper for ASN.1 UTCTime
#[pyclass(name = "UtcTime")]
#[derive(Debug, Clone)]
pub struct PyUtcTime {
    pub(crate) inner: UtcTime,
}

#[pymethods]
impl PyUtcTime {
    /// Create a new UTCTime (year must be in 1950-2049 range)
    #[new]
    fn new(year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8) -> PyResult<Self> {
        let inner = UtcTime::new(year, month, day, hour, minute, second)
            .map_err(|e| PyValueError::new_err(format!("Invalid UTCTime: {:?}", e)))?;
        Ok(Self { inner })
    }

    #[getter]
    fn year(&self) -> u16 {
        self.inner.year
    }

    #[getter]
    fn month(&self) -> u8 {
        self.inner.month
    }

    #[getter]
    fn day(&self) -> u8 {
        self.inner.day
    }

    #[getter]
    fn hour(&self) -> u8 {
        self.inner.hour
    }

    #[getter]
    fn minute(&self) -> u8 {
        self.inner.minute
    }

    #[getter]
    fn second(&self) -> u8 {
        self.inner.second
    }

    fn __str__(&self) -> String {
        self.inner.to_string()
    }

    fn __repr__(&self) -> String {
        format!("UtcTime('{}')", self.inner)
    }
}

impl std::fmt::Display for PyUtcTime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.inner)
    }
}

/// Python wrapper for ASN.1 GeneralizedTime
#[pyclass(name = "GeneralizedTime")]
#[derive(Debug, Clone)]
pub struct PyGeneralizedTime {
    pub(crate) inner: GeneralizedTime,
}

#[pymethods]
impl PyGeneralizedTime {
    /// Create a new GeneralizedTime
    ///
    /// Args:
    ///     milliseconds: Optional fractional seconds in milliseconds (0-999)
    #[new]
    fn new(
        year: u16,
        month: u8,
        day: u8,
        hour: u8,
        minute: u8,
        second: u8,
        milliseconds: Option<u16>,
    ) -> PyResult<Self> {
        let inner = GeneralizedTime::new(year, month, day, hour, minute, second, milliseconds)
            .map_err(|e| PyValueError::new_err(format!("Invalid GeneralizedTime: {:?}", e)))?;
        Ok(Self { inner })
    }

    #[getter]
    fn year(&self) -> u16 {
        self.inner.year
    }

    #[getter]
    fn month(&self) -> u8 {
        self.inner.month
    }

    #[getter]
    fn day(&self) -> u8 {
        self.inner.day
    }

    #[getter]
    fn hour(&self) -> u8 {
        self.inner.hour
    }

    #[getter]
    fn minute(&self) -> u8 {
        self.inner.minute
    }

    #[getter]
    fn second(&self) -> u8 {
        self.inner.second
    }

    #[getter]
    fn milliseconds(&self) -> Option<u16> {
        self.inner.milliseconds
    }

    fn __str__(&self) -> String {
        self.inner.to_string()
    }

    fn __repr__(&self) -> String {
        format!("GeneralizedTime('{}')", self.inner)
    }
}

impl std::fmt::Display for PyGeneralizedTime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.inner)
    }
}

/// Python wrapper for ASN.1 REAL
#[pyclass(name = "Real")]
#[derive(Debug, Clone, Copy)]
pub struct PyReal {
    pub(crate) inner: Real,
}

#[pymethods]
impl PyReal {
    /// Create a new Real from a Python float
    #[new]
    fn new(value: f64) -> Self {
        Self {
            inner: Real::new(value),
        }
    }

    /// Get the f64 value
    fn value(&self) -> f64 {
        self.inner.value()
    }

    /// Return True if this is positive infinity
    fn is_infinite(&self) -> bool {
        self.inner.value().is_infinite()
    }

    /// Return True if this is NaN (not-a-number)
    fn is_nan(&self) -> bool {
        self.inner.value().is_nan()
    }

    /// Return True if the value is finite
    fn is_finite(&self) -> bool {
        self.inner.value().is_finite()
    }

    fn __float__(&self) -> f64 {
        self.inner.value()
    }

    fn __repr__(&self) -> String {
        format!("Real({})", self.inner.value())
    }

    fn __str__(&self) -> String {
        self.inner.value().to_string()
    }

    fn __eq__(&self, other: &Self) -> bool {
        // NaN != NaN by IEEE 754 — mirror Python float behaviour
        self.inner.value() == other.inner.value()
    }

    fn __hash__(&self, py: Python<'_>) -> PyResult<isize> {
        // Delegate to Python's float.__hash__ so that hash(Real(1.0)) == hash(1.0) == hash(1),
        // matching the Python data model guarantee for numeric types.
        self.inner.value().into_pyobject(py)?.hash()
    }
}

/// Python wrapper for ASN.1 NULL
#[pyclass(name = "Null")]
#[derive(Debug, Clone, Copy)]
pub struct PyNull;

#[pymethods]
impl PyNull {
    #[new]
    fn new() -> Self {
        Self
    }

    fn __repr__(&self) -> String {
        "Null()".to_string()
    }

    fn __eq__(&self, _other: &Self) -> bool {
        true
    }

    fn __hash__(&self) -> isize {
        // All Null values are equal; use a fixed hash consistent with __eq__.
        0
    }
}