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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! 与 vectors 的掩码 lanes 相关的类型和 traits。
//! 代表的类型
#![allow(non_camel_case_types)]

#[cfg_attr(
    not(all(target_arch = "x86_64", target_feature = "avx512f")),
    path = "masks/full_masks.rs"
)]
#[cfg_attr(
    all(target_arch = "x86_64", target_feature = "avx512f"),
    path = "masks/bitmask.rs"
)]
mod mask_impl;

mod to_bitmask;
pub use to_bitmask::ToBitMask;

#[cfg(feature = "generic_const_exprs")]
pub use to_bitmask::{bitmask_len, ToBitMaskArray};

use crate::simd::{intrinsics, LaneCount, Simd, SimdElement, SimdPartialEq, SupportedLaneCount};
use core::cmp::Ordering;
use core::{fmt, mem};

mod sealed {
    use super::*;

    /// 这不仅封装了 `MaskElement` trait,而且这些函数还防止了其他 trait 进入父边界。
    ///
    /// 例如,可以通过要求 `MaskElement: PartialEq` 来提供 `eq`,但这将阻止我们永远删除该限制,或者阻止我们在将来在非 `PartialEq` 类型上实现 `MaskElement`。
    ///
    ///
    ///
    pub trait Sealed {
        fn valid<const LANES: usize>(values: Simd<Self, LANES>) -> bool
        where
            LaneCount<LANES>: SupportedLaneCount,
            Self: SimdElement;

        fn eq(self, other: Self) -> bool;

        const TRUE: Self;

        const FALSE: Self;
    }
}
use sealed::Sealed;

/// 可用作 SIMD 掩码元素的类型的标记 trait。
///
/// # Safety
/// 类型必须是有符号整数。
pub unsafe trait MaskElement: SimdElement + Sealed {}

macro_rules! impl_element {
    { $ty:ty } => {
        impl Sealed for $ty {
            #[inline]
            fn valid<const LANES: usize>(value: Simd<Self, LANES>) -> bool
            where
                LaneCount<LANES>: SupportedLaneCount,
            {
                (value.simd_eq(Simd::splat(0 as _)) | value.simd_eq(Simd::splat(-1 as _))).all()
            }

            #[inline]
            fn eq(self, other: Self) -> bool { self == other }

            const TRUE: Self = -1;
            const FALSE: Self = 0;
        }

        // 安全性: 这是一个有效的掩码元素类型
        unsafe impl MaskElement for $ty {}
    }
}

impl_element! { i8 }
impl_element! { i16 }
impl_element! { i32 }
impl_element! { i64 }
impl_element! { isize }

/// `Element` 指定宽度的 `LANES` 元素的 SIMD vector 掩码。
///
/// 掩码代表基于每个 lane 的布尔 inclusion/exclusion。
///
/// 此类型的布局未指定,可能会在平台或者 Rust 版本之间发生变化,并且代码不应假定它等同于 `[T; LANES]`。
///
///
#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/90435
pub struct Mask<T, const LANES: usize>(mask_impl::Mask<T, LANES>)
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount;

impl<T, const LANES: usize> Copy for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
}

impl<T, const LANES: usize> Clone for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    #[inline]
    fn clone(&self) -> Self {
        *self
    }
}

impl<T, const LANES: usize> Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    /// 通过将所有 lanes 设置为给定值来构建掩码。
    #[inline]
    pub fn splat(value: bool) -> Self {
        Self(mask_impl::Mask::splat(value))
    }

    /// 将布尔数组转换为 SIMD 掩码。
    #[inline]
    pub fn from_array(array: [bool; LANES]) -> Self {
        // SAFETY: Rust 的 bool 具有 1 字节 (u8) 的布局,值为 true: 0b_0000_0001 false: 0b_0000_0000 因此,布尔数组也是有效的字节数组: [u8; N] 这作为 "in-place" 转换假设是有效的,但这些是 "dependently-sized" 类型,所以复制省略它是!
        //
        //
        //
        //
        //
        unsafe {
            let bytes: [u8; LANES] = mem::transmute_copy(&array);
            let bools: Simd<i8, LANES> =
                intrinsics::simd_ne(Simd::from_array(bytes), Simd::splat(0u8));
            Mask::from_int_unchecked(intrinsics::simd_cast(bools))
        }
    }

    /// 将 SIMD 掩码转换为布尔数组。
    #[inline]
    pub fn to_array(self) -> [bool; LANES] {
        // 这遵循与 from_array 大体相同的逻辑。
        // SAFETY: Rust 的 bool 具有 1 字节 (u8) 的布局,值为 true: 0b_0000_0001 false: 0b_0000_0000 因此,布尔数组也是有效的字节数组: [u8; N] 由于我们的掩码等于设置所有位的整数,我们可以简单地将它们转换为 i8s,然后通过 Rust 的 "true" bool 的位模式对它们进行位和位。
        //
        // 这作为 "in-place" 变形假设是有效的,但这些是 "dependently-sized" 类型,所以它是复制省略!
        //
        //
        //
        //
        //
        //
        unsafe {
            let mut bytes: Simd<i8, LANES> = intrinsics::simd_cast(self.to_int());
            bytes &= Simd::splat(1i8);
            mem::transmute_copy(&bytes)
        }
    }

    /// 将整数 vector 转换为掩码,其中 0 代表 `false`,-1 代表 `true`。
    ///
    ///
    /// # Safety
    /// 所有 lanes 必须为 0 或 -1。
    #[inline]
    #[must_use = "method returns a new mask and does not mutate the original value"]
    pub unsafe fn from_int_unchecked(value: Simd<T, LANES>) -> Self {
        // 安全性: 调用者必须确认这个不,变体
        unsafe { Self(mask_impl::Mask::from_int_unchecked(value)) }
    }

    /// 将整数 vector 转换为掩码,其中 0 代表 `false`,-1 代表 `true`。
    ///
    ///
    /// # Panics
    /// 如果任何 lane 不是 0 或 -1,就会出现 panics。
    #[inline]
    #[must_use = "method returns a new mask and does not mutate the original value"]
    pub fn from_int(value: Simd<T, LANES>) -> Self {
        assert!(T::valid(value), "all values must be either 0 or -1",);
        // 安全性: 有效性已经过检查
        unsafe { Self::from_int_unchecked(value) }
    }

    /// 将掩码转换为整数 vector,其中 0 代表 `false`,-1 代表 `true`。
    ///
    #[inline]
    #[must_use = "method returns a new vector and does not mutate the original value"]
    pub fn to_int(self) -> Simd<T, LANES> {
        self.0.to_int()
    }

    /// 将遮罩转换为任何其他 lane 大小的遮罩。
    #[inline]
    #[must_use = "method returns a new mask and does not mutate the original value"]
    pub fn cast<U: MaskElement>(self) -> Mask<U, LANES> {
        Mask(self.0.convert())
    }

    /// 测试指定 lane 的值。
    ///
    /// # Safety
    /// `lane` 必须小于 `LANES`。
    #[inline]
    #[must_use = "method returns a new bool and does not mutate the original value"]
    pub unsafe fn test_unchecked(&self, lane: usize) -> bool {
        // 安全性: 调用者必须确认这个不,变体
        unsafe { self.0.test_unchecked(lane) }
    }

    /// 测试指定 lane 的值。
    ///
    /// # Panics
    /// 如果 `lane` 大于或等于 vector 中的 lane 数,则出现 panics。
    #[inline]
    #[must_use = "method returns a new bool and does not mutate the original value"]
    pub fn test(&self, lane: usize) -> bool {
        assert!(lane < LANES, "lane index out of range");
        // 安全性: 已检查 lane 指数
        unsafe { self.test_unchecked(lane) }
    }

    /// 设置指定 lane 的值。
    ///
    /// # Safety
    /// `lane` 必须小于 `LANES`。
    #[inline]
    pub unsafe fn set_unchecked(&mut self, lane: usize, value: bool) {
        // 安全性: 调用者必须确认这个不,变体
        unsafe {
            self.0.set_unchecked(lane, value);
        }
    }

    /// 设置指定 lane 的值。
    ///
    /// # Panics
    /// 如果 `lane` 大于或等于 vector 中的 lane 数,则出现 panics。
    #[inline]
    pub fn set(&mut self, lane: usize, value: bool) {
        assert!(lane < LANES, "lane index out of range");
        // 安全性: 已检查 lane 指数
        unsafe {
            self.set_unchecked(lane, value);
        }
    }

    /// 如果设置了任何 lane,则返回 true,否则返回 false。
    #[inline]
    #[must_use = "method returns a new bool and does not mutate the original value"]
    pub fn any(self) -> bool {
        self.0.any()
    }

    /// 如果设置了所有 lanes,则返回 true,否则返回 false。
    #[inline]
    #[must_use = "method returns a new bool and does not mutate the original value"]
    pub fn all(self) -> bool {
        self.0.all()
    }
}

// vector 和 array 的转换
impl<T, const LANES: usize> From<[bool; LANES]> for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    #[inline]
    fn from(array: [bool; LANES]) -> Self {
        Self::from_array(array)
    }
}

impl<T, const LANES: usize> From<Mask<T, LANES>> for [bool; LANES]
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    #[inline]
    fn from(vector: Mask<T, LANES>) -> Self {
        vector.to_array()
    }
}

impl<T, const LANES: usize> Default for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    #[inline]
    #[must_use = "method returns a defaulted mask with all lanes set to false (0)"]
    fn default() -> Self {
        Self::splat(false)
    }
}

impl<T, const LANES: usize> PartialEq for Mask<T, LANES>
where
    T: MaskElement + PartialEq,
    LaneCount<LANES>: SupportedLaneCount,
{
    #[inline]
    #[must_use = "method returns a new bool and does not mutate the original value"]
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T, const LANES: usize> PartialOrd for Mask<T, LANES>
where
    T: MaskElement + PartialOrd,
    LaneCount<LANES>: SupportedLaneCount,
{
    #[inline]
    #[must_use = "method returns a new Ordering and does not mutate the original value"]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.0.partial_cmp(&other.0)
    }
}

impl<T, const LANES: usize> fmt::Debug for Mask<T, LANES>
where
    T: MaskElement + fmt::Debug,
    LaneCount<LANES>: SupportedLaneCount,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list()
            .entries((0..LANES).map(|lane| self.test(lane)))
            .finish()
    }
}

impl<T, const LANES: usize> core::ops::BitAnd for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    type Output = Self;
    #[inline]
    #[must_use = "method returns a new mask and does not mutate the original value"]
    fn bitand(self, rhs: Self) -> Self {
        Self(self.0 & rhs.0)
    }
}

impl<T, const LANES: usize> core::ops::BitAnd<bool> for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    type Output = Self;
    #[inline]
    #[must_use = "method returns a new mask and does not mutate the original value"]
    fn bitand(self, rhs: bool) -> Self {
        self & Self::splat(rhs)
    }
}

impl<T, const LANES: usize> core::ops::BitAnd<Mask<T, LANES>> for bool
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    type Output = Mask<T, LANES>;
    #[inline]
    #[must_use = "method returns a new mask and does not mutate the original value"]
    fn bitand(self, rhs: Mask<T, LANES>) -> Mask<T, LANES> {
        Mask::splat(self) & rhs
    }
}

impl<T, const LANES: usize> core::ops::BitOr for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    type Output = Self;
    #[inline]
    #[must_use = "method returns a new mask and does not mutate the original value"]
    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

impl<T, const LANES: usize> core::ops::BitOr<bool> for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    type Output = Self;
    #[inline]
    #[must_use = "method returns a new mask and does not mutate the original value"]
    fn bitor(self, rhs: bool) -> Self {
        self | Self::splat(rhs)
    }
}

impl<T, const LANES: usize> core::ops::BitOr<Mask<T, LANES>> for bool
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    type Output = Mask<T, LANES>;
    #[inline]
    #[must_use = "method returns a new mask and does not mutate the original value"]
    fn bitor(self, rhs: Mask<T, LANES>) -> Mask<T, LANES> {
        Mask::splat(self) | rhs
    }
}

impl<T, const LANES: usize> core::ops::BitXor for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    type Output = Self;
    #[inline]
    #[must_use = "method returns a new mask and does not mutate the original value"]
    fn bitxor(self, rhs: Self) -> Self::Output {
        Self(self.0 ^ rhs.0)
    }
}

impl<T, const LANES: usize> core::ops::BitXor<bool> for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    type Output = Self;
    #[inline]
    #[must_use = "method returns a new mask and does not mutate the original value"]
    fn bitxor(self, rhs: bool) -> Self::Output {
        self ^ Self::splat(rhs)
    }
}

impl<T, const LANES: usize> core::ops::BitXor<Mask<T, LANES>> for bool
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    type Output = Mask<T, LANES>;
    #[inline]
    #[must_use = "method returns a new mask and does not mutate the original value"]
    fn bitxor(self, rhs: Mask<T, LANES>) -> Self::Output {
        Mask::splat(self) ^ rhs
    }
}

impl<T, const LANES: usize> core::ops::Not for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    type Output = Mask<T, LANES>;
    #[inline]
    #[must_use = "method returns a new mask and does not mutate the original value"]
    fn not(self) -> Self::Output {
        Self(!self.0)
    }
}

impl<T, const LANES: usize> core::ops::BitAndAssign for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    #[inline]
    fn bitand_assign(&mut self, rhs: Self) {
        self.0 = self.0 & rhs.0;
    }
}

impl<T, const LANES: usize> core::ops::BitAndAssign<bool> for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    #[inline]
    fn bitand_assign(&mut self, rhs: bool) {
        *self &= Self::splat(rhs);
    }
}

impl<T, const LANES: usize> core::ops::BitOrAssign for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    #[inline]
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 = self.0 | rhs.0;
    }
}

impl<T, const LANES: usize> core::ops::BitOrAssign<bool> for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    #[inline]
    fn bitor_assign(&mut self, rhs: bool) {
        *self |= Self::splat(rhs);
    }
}

impl<T, const LANES: usize> core::ops::BitXorAssign for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    #[inline]
    fn bitxor_assign(&mut self, rhs: Self) {
        self.0 = self.0 ^ rhs.0;
    }
}

impl<T, const LANES: usize> core::ops::BitXorAssign<bool> for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
{
    #[inline]
    fn bitxor_assign(&mut self, rhs: bool) {
        *self ^= Self::splat(rhs);
    }
}

macro_rules! impl_from {
    { $from:ty  => $($to:ty),* } => {
        $(
        impl<const LANES: usize> From<Mask<$from, LANES>> for Mask<$to, LANES>
        where
            LaneCount<LANES>: SupportedLaneCount,
        {
            #[inline]
            fn from(value: Mask<$from, LANES>) -> Self {
                value.cast()
            }
        }
        )*
    }
}
impl_from! { i8 => i16, i32, i64, isize }
impl_from! { i16 => i32, i64, isize, i8 }
impl_from! { i32 => i64, isize, i8, i16 }
impl_from! { i64 => isize, i8, i16, i32 }
impl_from! { isize => i8, i16, i32, i64 }