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
//! Types to support arrays of [ASCII][ascii] and [UCS4][ucs4] strings
//!
//! [ascii]: https://numpy.org/doc/stable/reference/c-api/dtype.html#c.NPY_STRING
//! [ucs4]: https://numpy.org/doc/stable/reference/c-api/dtype.html#c.NPY_UNICODE

use std::cell::RefCell;
use std::collections::hash_map::Entry;
use std::fmt;
use std::mem::size_of;
use std::os::raw::c_char;
use std::str;

use pyo3::{
    ffi::{Py_UCS1, Py_UCS4},
    sync::GILProtected,
    Bound, Py, Python,
};
use rustc_hash::FxHashMap;

use crate::dtype::{Element, PyArrayDescr, PyArrayDescrMethods};
use crate::npyffi::NPY_TYPES;

/// A newtype wrapper around [`[u8; N]`][Py_UCS1] to handle [`byte` scalars][numpy-bytes] while satisfying coherence.
///
/// Note that when creating arrays of ASCII strings without an explicit `dtype`,
/// NumPy will automatically determine the smallest possible array length at runtime.
///
/// For example,
///
/// ```python
/// array = numpy.array([b"foo", b"bar", b"foobar"])
/// ```
///
/// yields `S6` for `array.dtype`.
///
/// On the Rust side however, the length `N` of `PyFixedString<N>` must always be given
/// explicitly and as a compile-time constant. For this work reliably, the Python code
/// should set the `dtype` explicitly, e.g.
///
/// ```python
/// numpy.array([b"foo", b"bar", b"foobar"], dtype='S12')
/// ```
///
/// always matching `PyArray1<PyFixedString<12>>`.
///
/// # Example
///
/// ```rust
/// # use pyo3::Python;
/// use numpy::{PyArray1, PyUntypedArrayMethods, PyFixedString};
///
/// # Python::with_gil(|py| {
/// let array = PyArray1::<PyFixedString<3>>::from_vec_bound(py, vec![[b'f', b'o', b'o'].into()]);
///
/// assert!(array.dtype().to_string().contains("S3"));
/// # });
/// ```
///
/// [numpy-bytes]: https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.bytes_
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PyFixedString<const N: usize>(pub [Py_UCS1; N]);

impl<const N: usize> fmt::Display for PyFixedString<N> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.write_str(str::from_utf8(&self.0).unwrap().trim_end_matches('\0'))
    }
}

impl<const N: usize> From<[Py_UCS1; N]> for PyFixedString<N> {
    fn from(val: [Py_UCS1; N]) -> Self {
        Self(val)
    }
}

unsafe impl<const N: usize> Element for PyFixedString<N> {
    const IS_COPY: bool = true;

    fn get_dtype_bound(py: Python<'_>) -> Bound<'_, PyArrayDescr> {
        static DTYPES: TypeDescriptors = TypeDescriptors::new();

        unsafe { DTYPES.from_size(py, NPY_TYPES::NPY_STRING, b'|' as _, size_of::<Self>()) }
    }
}

/// A newtype wrapper around [`[PyUCS4; N]`][Py_UCS4] to handle [`str_` scalars][numpy-str] while satisfying coherence.
///
/// Note that when creating arrays of Unicode strings without an explicit `dtype`,
/// NumPy will automatically determine the smallest possible array length at runtime.
///
/// For example,
///
/// ```python
/// numpy.array(["foo🐍", "bar🦀", "foobar"])
/// ```
///
/// yields `U6` for `array.dtype`.
///
/// On the Rust side however, the length `N` of `PyFixedUnicode<N>` must always be given
/// explicitly and as a compile-time constant. For this work reliably, the Python code
/// should set the `dtype` explicitly, e.g.
///
/// ```python
/// numpy.array(["foo🐍", "bar🦀", "foobar"], dtype='U12')
/// ```
///
/// always matching `PyArray1<PyFixedUnicode<12>>`.
///
/// # Example
///
/// ```rust
/// # use pyo3::Python;
/// use numpy::{PyArray1, PyUntypedArrayMethods, PyFixedUnicode};
///
/// # Python::with_gil(|py| {
/// let array = PyArray1::<PyFixedUnicode<3>>::from_vec_bound(py, vec![[b'b' as _, b'a' as _, b'r' as _].into()]);
///
/// assert!(array.dtype().to_string().contains("U3"));
/// # });
/// ```
///
/// [numpy-str]: https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.str_
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PyFixedUnicode<const N: usize>(pub [Py_UCS4; N]);

impl<const N: usize> fmt::Display for PyFixedUnicode<N> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        for character in self.0 {
            if character == 0 {
                break;
            }

            write!(fmt, "{}", char::from_u32(character).unwrap())?;
        }

        Ok(())
    }
}

impl<const N: usize> From<[Py_UCS4; N]> for PyFixedUnicode<N> {
    fn from(val: [Py_UCS4; N]) -> Self {
        Self(val)
    }
}

unsafe impl<const N: usize> Element for PyFixedUnicode<N> {
    const IS_COPY: bool = true;

    fn get_dtype_bound(py: Python<'_>) -> Bound<'_, PyArrayDescr> {
        static DTYPES: TypeDescriptors = TypeDescriptors::new();

        unsafe { DTYPES.from_size(py, NPY_TYPES::NPY_UNICODE, b'=' as _, size_of::<Self>()) }
    }
}

struct TypeDescriptors {
    #[allow(clippy::type_complexity)]
    dtypes: GILProtected<RefCell<Option<FxHashMap<usize, Py<PyArrayDescr>>>>>,
}

impl TypeDescriptors {
    const fn new() -> Self {
        Self {
            dtypes: GILProtected::new(RefCell::new(None)),
        }
    }

    /// `npy_type` must be either `NPY_STRING` or `NPY_UNICODE` with matching `byteorder` and `size`
    #[allow(clippy::wrong_self_convention)]
    unsafe fn from_size<'py>(
        &self,
        py: Python<'py>,
        npy_type: NPY_TYPES,
        byteorder: c_char,
        size: usize,
    ) -> Bound<'py, PyArrayDescr> {
        let mut dtypes = self.dtypes.get(py).borrow_mut();

        let dtype = match dtypes.get_or_insert_with(Default::default).entry(size) {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => {
                let dtype = PyArrayDescr::new_from_npy_type(py, npy_type);

                let descr = &mut *dtype.as_dtype_ptr();
                descr.elsize = size.try_into().unwrap();
                descr.byteorder = byteorder;

                entry.insert(dtype.into())
            }
        };

        dtype.clone().into_bound(py)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn format_fixed_string() {
        assert_eq!(
            PyFixedString([b'f', b'o', b'o', 0, 0, 0]).to_string(),
            "foo"
        );
        assert_eq!(
            PyFixedString([b'f', b'o', b'o', b'b', b'a', b'r']).to_string(),
            "foobar"
        );
    }

    #[test]
    fn format_fixed_unicode() {
        assert_eq!(
            PyFixedUnicode([b'f' as _, b'o' as _, b'o' as _, 0, 0, 0]).to_string(),
            "foo"
        );
        assert_eq!(
            PyFixedUnicode([0x1F980, 0x1F40D, 0, 0, 0, 0]).to_string(),
            "🦀🐍"
        );
        assert_eq!(
            PyFixedUnicode([b'f' as _, b'o' as _, b'o' as _, b'b' as _, b'a' as _, b'r' as _])
                .to_string(),
            "foobar"
        );
    }
}