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
use pyo3::{
    ffi::PyTypeObject,
    intern,
    prelude::*,
    types::{DerefToPyAny, PyDict, PyType},
    PyTypeInfo,
};

use crate::{sealed::Sealed, PyCodec};

/// Represents a [`numcodecs.abc.Codec`] *class* object.
///
/// The [`Bound<CodecClass>`] type implements the [`PyCodecClassMethods`] API.
///
/// [`numcodecs.abc.Codec`]: https://numcodecs.readthedocs.io/en/stable/abc.html#module-numcodecs.abc
#[repr(transparent)]
pub struct PyCodecClass {
    _class: PyType,
}

/// Methods implemented for [`PyCodecClass`]es.
pub trait PyCodecClassMethods<'py>: Sealed {
    /// Gets the codec identifier.
    ///
    /// # Errors
    ///
    /// Errors if the codec does not provide an identifier.
    fn codec_id(&self) -> Result<String, PyErr>;

    /// Instantiate a codec from a configuration dictionary.
    ///
    /// The `config` dict must *not* contain an `id` field.
    ///
    /// # Errors
    ///
    /// Errors if constructing the codec fails.
    fn codec_from_config(
        &self,
        config: Borrowed<'_, 'py, PyDict>,
    ) -> Result<Bound<'py, PyCodec>, PyErr>;

    /// Gets the [`PyType`] that this [`PyCodecClass`] represents.
    fn as_type(&self) -> &Bound<'py, PyType>;
}

impl<'py> PyCodecClassMethods<'py> for Bound<'py, PyCodecClass> {
    fn codec_id(&self) -> Result<String, PyErr> {
        let py = self.py();

        let codec_id = self.as_any().getattr(intern!(py, "codec_id"))?.extract()?;

        Ok(codec_id)
    }

    fn codec_from_config(
        &self,
        config: Borrowed<'_, 'py, PyDict>,
    ) -> Result<Bound<'py, PyCodec>, PyErr> {
        let py = self.py();

        self.as_any()
            .call_method1(intern!(py, "from_config"), (config,))?
            .extract()
    }

    fn as_type(&self) -> &Bound<'py, PyType> {
        #[allow(unsafe_code)]
        // Safety: PyCodecClass is a wrapper around PyType
        unsafe {
            self.downcast_unchecked()
        }
    }
}

impl<'py> Sealed for Bound<'py, PyCodecClass> {}

#[doc(hidden)]
impl DerefToPyAny for PyCodecClass {}

#[doc(hidden)]
#[allow(unsafe_code)]
unsafe impl PyNativeType for PyCodecClass {
    type AsRefSource = Self;
}

#[doc(hidden)]
#[allow(unsafe_code)]
unsafe impl PyTypeInfo for PyCodecClass {
    const MODULE: Option<&'static str> = Some("numcodecs.abc");
    const NAME: &'static str = "Codec";

    #[inline]
    fn type_object_raw(py: Python) -> *mut PyTypeObject {
        PyType::type_object_raw(py)
    }

    #[inline]
    fn is_type_of_bound(object: &Bound<'_, PyAny>) -> bool {
        let Ok(ty) = object.downcast::<PyType>() else {
            return false;
        };

        ty.is_subclass_of::<PyCodec>().unwrap_or(false)
    }

    #[inline]
    fn is_exact_type_of_bound(object: &Bound<'_, PyAny>) -> bool {
        object.as_ptr() == PyCodec::type_object_raw(object.py()).cast()
    }
}