-
Notifications
You must be signed in to change notification settings - Fork 133
Add support for arrays of ASCII and Unicode strings #378
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,230 @@ | ||
| //! 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::convert::TryInto; | ||
| 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, | ||
| Py, Python, | ||
| }; | ||
| use rustc_hash::FxHashMap; | ||
|
|
||
| use crate::dtype::{Element, PyArrayDescr}; | ||
| 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, PyFixedString}; | ||
| /// | ||
| /// # Python::with_gil(|py| { | ||
| /// let array = PyArray1::<PyFixedString<3>>::from_vec(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(py: Python) -> &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, PyFixedUnicode}; | ||
| /// | ||
| /// # Python::with_gil(|py| { | ||
| /// let array = PyArray1::<PyFixedUnicode<3>>::from_vec(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(py: Python) -> &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>( | ||
| &'py self, | ||
| py: Python<'py>, | ||
| npy_type: NPY_TYPES, | ||
| byteorder: c_char, | ||
| size: usize, | ||
| ) -> &'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_ref(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" | ||
| ); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.