Skip to main content

mlx_rs/ops/
windows.rs

1//! Window functions for signal processing.
2
3use crate::error::{Exception, Result};
4use crate::utils::guard::Guarded;
5use crate::{Array, Stream};
6
7fn checked_size(size: usize) -> Result<i32> {
8    i32::try_from(size).map_err(|_| Exception::custom("window size exceeds i32::MAX"))
9}
10
11/// Returns a Bartlett window of `size` samples.
12///
13/// # Example
14///
15/// ```rust
16/// use mlx_rs::{ops::windows::bartlett, Device, Dtype};
17///
18/// Device::set_default(&Device::cpu());
19/// let window = bartlett(7).unwrap();
20/// assert_eq!(window.shape(), &[7]);
21/// assert_eq!(window.dtype(), Dtype::Float32);
22/// ```
23pub fn bartlett(size: usize) -> Result<Array> {
24    let size = checked_size(size)?;
25    let stream = Stream::thread_local_or_default();
26    Array::try_from_op(|res| unsafe { mlx_sys::mlx_bartlett(res, size, stream.as_ptr()) })
27}
28
29/// Returns a Blackman window of `size` samples.
30///
31/// # Example
32///
33/// ```rust
34/// use mlx_rs::{ops::windows::blackman, Device, Dtype};
35///
36/// Device::set_default(&Device::cpu());
37/// let window = blackman(7).unwrap();
38/// assert_eq!(window.shape(), &[7]);
39/// assert_eq!(window.dtype(), Dtype::Float32);
40/// ```
41pub fn blackman(size: usize) -> Result<Array> {
42    let size = checked_size(size)?;
43    let stream = Stream::thread_local_or_default();
44    Array::try_from_op(|res| unsafe { mlx_sys::mlx_blackman(res, size, stream.as_ptr()) })
45}
46
47/// Returns a Hamming window of `size` samples.
48///
49/// # Example
50///
51/// ```rust
52/// use mlx_rs::{ops::windows::hamming, Device, Dtype};
53///
54/// Device::set_default(&Device::cpu());
55/// let window = hamming(7).unwrap();
56/// assert_eq!(window.shape(), &[7]);
57/// assert_eq!(window.dtype(), Dtype::Float32);
58/// ```
59pub fn hamming(size: usize) -> Result<Array> {
60    let size = checked_size(size)?;
61    let stream = Stream::thread_local_or_default();
62    Array::try_from_op(|res| unsafe { mlx_sys::mlx_hamming(res, size, stream.as_ptr()) })
63}
64
65/// Returns a Hann window of `size` samples.
66///
67/// # Example
68///
69/// ```rust
70/// use mlx_rs::{ops::windows::hann, Device, Dtype};
71///
72/// Device::set_default(&Device::cpu());
73/// let window = hann(7).unwrap();
74/// assert_eq!(window.shape(), &[7]);
75/// assert_eq!(window.dtype(), Dtype::Float32);
76/// ```
77pub fn hann(size: usize) -> Result<Array> {
78    let size = checked_size(size)?;
79    let stream = Stream::thread_local_or_default();
80    Array::try_from_op(|res| unsafe { mlx_sys::mlx_hanning(res, size, stream.as_ptr()) })
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86
87    #[test]
88    fn rejects_sizes_above_i32_max() {
89        assert!(bartlett(usize::MAX).is_err());
90        assert!(blackman(usize::MAX).is_err());
91        assert!(hamming(usize::MAX).is_err());
92        assert!(hann(usize::MAX).is_err());
93    }
94}