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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
//! Contains utility functions and traits to convert between slices of [`u16`] bits and [`f16`] or
//! [`bf16`] numbers.
//!
//! The utility [`HalfBitsSliceExt`] sealed extension trait is implemented for `[u16]` slices,
//! while the utility [`HalfFloatSliceExt`] sealed extension trait is implemented for both `[f16]`
//! and `[bf16]` slices. These traits provide efficient conversions and reinterpret casting of
//! larger buffers of floating point values, and are automatically included in the
//! [`prelude`][crate::prelude] module.

use crate::{bf16, binary16::arch, f16};
#[cfg(feature = "alloc")]
#[allow(unused_imports)]
use alloc::{vec, vec::Vec};
use core::slice;

/// Extensions to `[f16]` and `[bf16]` slices to support conversion and reinterpret operations.
///
/// This trait is sealed and cannot be implemented outside of this crate.
pub trait HalfFloatSliceExt: private::SealedHalfFloatSlice {
    /// Reinterprets a slice of [`f16`] or [`bf16`] numbers as a slice of [`u16`] bits.
    ///
    /// This is a zero-copy operation. The reinterpreted slice has the same lifetime and memory
    /// location as `self`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use half::prelude::*;
    /// let float_buffer = [f16::from_f32(1.), f16::from_f32(2.), f16::from_f32(3.)];
    /// let int_buffer = float_buffer.reinterpret_cast();
    ///
    /// assert_eq!(int_buffer, [float_buffer[0].to_bits(), float_buffer[1].to_bits(), float_buffer[2].to_bits()]);
    /// ```
    #[must_use]
    fn reinterpret_cast(&self) -> &[u16];

    /// Reinterprets a mutable slice of [`f16`] or [`bf16`] numbers as a mutable slice of [`u16`].
    /// bits
    ///
    /// This is a zero-copy operation. The transmuted slice has the same lifetime as the original,
    /// which prevents mutating `self` as long as the returned `&mut [u16]` is borrowed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use half::prelude::*;
    /// let mut float_buffer = [f16::from_f32(1.), f16::from_f32(2.), f16::from_f32(3.)];
    ///
    /// {
    ///     let int_buffer = float_buffer.reinterpret_cast_mut();
    ///
    ///     assert_eq!(int_buffer, [f16::from_f32(1.).to_bits(), f16::from_f32(2.).to_bits(), f16::from_f32(3.).to_bits()]);
    ///
    ///     // Mutating the u16 slice will mutating the original
    ///     int_buffer[0] = 0;
    /// }
    ///
    /// // Note that we need to drop int_buffer before using float_buffer again or we will get a borrow error.
    /// assert_eq!(float_buffer, [f16::from_f32(0.), f16::from_f32(2.), f16::from_f32(3.)]);
    /// ```
    #[must_use]
    fn reinterpret_cast_mut(&mut self) -> &mut [u16];

    /// Converts all of the elements of a `[f32]` slice into [`f16`] or [`bf16`] values in `self`.
    ///
    /// The length of `src` must be the same as `self`.
    ///
    /// The conversion operation is vectorized over the slice, meaning the conversion may be more
    /// efficient than converting individual elements on some hardware that supports SIMD
    /// conversions. See [crate documentation](crate) for more information on hardware conversion
    /// support.
    ///
    /// # Panics
    ///
    /// This function will panic if the two slices have different lengths.
    ///
    /// # Examples
    /// ```rust
    /// # use half::prelude::*;
    /// // Initialize an empty buffer
    /// let mut buffer = [0u16; 4];
    /// let buffer = buffer.reinterpret_cast_mut::<f16>();
    ///
    /// let float_values = [1., 2., 3., 4.];
    ///
    /// // Now convert
    /// buffer.convert_from_f32_slice(&float_values);
    ///
    /// assert_eq!(buffer, [f16::from_f32(1.), f16::from_f32(2.), f16::from_f32(3.), f16::from_f32(4.)]);
    /// ```
    fn convert_from_f32_slice(&mut self, src: &[f32]);

    /// Converts all of the elements of a `[f64]` slice into [`f16`] or [`bf16`] values in `self`.
    ///
    /// The length of `src` must be the same as `self`.
    ///
    /// The conversion operation is vectorized over the slice, meaning the conversion may be more
    /// efficient than converting individual elements on some hardware that supports SIMD
    /// conversions. See [crate documentation](crate) for more information on hardware conversion
    /// support.
    ///
    /// # Panics
    ///
    /// This function will panic if the two slices have different lengths.
    ///
    /// # Examples
    /// ```rust
    /// # use half::prelude::*;
    /// // Initialize an empty buffer
    /// let mut buffer = [0u16; 4];
    /// let buffer = buffer.reinterpret_cast_mut::<f16>();
    ///
    /// let float_values = [1., 2., 3., 4.];
    ///
    /// // Now convert
    /// buffer.convert_from_f64_slice(&float_values);
    ///
    /// assert_eq!(buffer, [f16::from_f64(1.), f16::from_f64(2.), f16::from_f64(3.), f16::from_f64(4.)]);
    /// ```
    fn convert_from_f64_slice(&mut self, src: &[f64]);

    /// Converts all of the [`f16`] or [`bf16`] elements of `self` into [`f32`] values in `dst`.
    ///
    /// The length of `src` must be the same as `self`.
    ///
    /// The conversion operation is vectorized over the slice, meaning the conversion may be more
    /// efficient than converting individual elements on some hardware that supports SIMD
    /// conversions. See [crate documentation](crate) for more information on hardware conversion
    /// support.
    ///
    /// # Panics
    ///
    /// This function will panic if the two slices have different lengths.
    ///
    /// # Examples
    /// ```rust
    /// # use half::prelude::*;
    /// // Initialize an empty buffer
    /// let mut buffer = [0f32; 4];
    ///
    /// let half_values = [f16::from_f32(1.), f16::from_f32(2.), f16::from_f32(3.), f16::from_f32(4.)];
    ///
    /// // Now convert
    /// half_values.convert_to_f32_slice(&mut buffer);
    ///
    /// assert_eq!(buffer, [1., 2., 3., 4.]);
    /// ```
    fn convert_to_f32_slice(&self, dst: &mut [f32]);

    /// Converts all of the [`f16`] or [`bf16`] elements of `self` into [`f64`] values in `dst`.
    ///
    /// The length of `src` must be the same as `self`.
    ///
    /// The conversion operation is vectorized over the slice, meaning the conversion may be more
    /// efficient than converting individual elements on some hardware that supports SIMD
    /// conversions. See [crate documentation](crate) for more information on hardware conversion
    /// support.
    ///
    /// # Panics
    ///
    /// This function will panic if the two slices have different lengths.
    ///
    /// # Examples
    /// ```rust
    /// # use half::prelude::*;
    /// // Initialize an empty buffer
    /// let mut buffer = [0f64; 4];
    ///
    /// let half_values = [f16::from_f64(1.), f16::from_f64(2.), f16::from_f64(3.), f16::from_f64(4.)];
    ///
    /// // Now convert
    /// half_values.convert_to_f64_slice(&mut buffer);
    ///
    /// assert_eq!(buffer, [1., 2., 3., 4.]);
    /// ```
    fn convert_to_f64_slice(&self, dst: &mut [f64]);

    // Because trait is sealed, we can get away with different interfaces between features.

    /// Converts all of the [`f16`] or [`bf16`] elements of `self` into [`f32`] values in a new
    /// vector
    ///
    /// The conversion operation is vectorized over the slice, meaning the conversion may be more
    /// efficient than converting individual elements on some hardware that supports SIMD
    /// conversions. See [crate documentation](crate) for more information on hardware conversion
    /// support.
    ///
    /// This method is only available with the `std` or `alloc` feature.
    ///
    /// # Examples
    /// ```rust
    /// # use half::prelude::*;
    /// let half_values = [f16::from_f32(1.), f16::from_f32(2.), f16::from_f32(3.), f16::from_f32(4.)];
    /// let vec = half_values.to_f32_vec();
    ///
    /// assert_eq!(vec, vec![1., 2., 3., 4.]);
    /// ```
    #[cfg(any(feature = "alloc", feature = "std"))]
    #[must_use]
    fn to_f32_vec(&self) -> Vec<f32>;

    /// Converts all of the [`f16`] or [`bf16`] elements of `self` into [`f64`] values in a new
    /// vector.
    ///
    /// The conversion operation is vectorized over the slice, meaning the conversion may be more
    /// efficient than converting individual elements on some hardware that supports SIMD
    /// conversions. See [crate documentation](crate) for more information on hardware conversion
    /// support.
    ///
    /// This method is only available with the `std` or `alloc` feature.
    ///
    /// # Examples
    /// ```rust
    /// # use half::prelude::*;
    /// let half_values = [f16::from_f64(1.), f16::from_f64(2.), f16::from_f64(3.), f16::from_f64(4.)];
    /// let vec = half_values.to_f64_vec();
    ///
    /// assert_eq!(vec, vec![1., 2., 3., 4.]);
    /// ```
    #[cfg(feature = "alloc")]
    #[must_use]
    fn to_f64_vec(&self) -> Vec<f64>;
}

/// Extensions to `[u16]` slices to support reinterpret operations.
///
/// This trait is sealed and cannot be implemented outside of this crate.
pub trait HalfBitsSliceExt: private::SealedHalfBitsSlice {
    /// Reinterprets a slice of [`u16`] bits as a slice of [`f16`] or [`bf16`] numbers.
    ///
    /// `H` is the type to cast to, and must be either the [`f16`] or [`bf16`] type.
    ///
    /// This is a zero-copy operation. The reinterpreted slice has the same lifetime and memory
    /// location as `self`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use half::prelude::*;
    /// let int_buffer = [f16::from_f32(1.).to_bits(), f16::from_f32(2.).to_bits(), f16::from_f32(3.).to_bits()];
    /// let float_buffer: &[f16] = int_buffer.reinterpret_cast();
    ///
    /// assert_eq!(float_buffer, [f16::from_f32(1.), f16::from_f32(2.), f16::from_f32(3.)]);
    ///
    /// // You may have to specify the cast type directly if the compiler can't infer the type.
    /// // The following is also valid in Rust.
    /// let typed_buffer = int_buffer.reinterpret_cast::<f16>();
    /// ```
    #[must_use]
    fn reinterpret_cast<H>(&self) -> &[H]
    where
        H: crate::private::SealedHalf;

    /// Reinterprets a mutable slice of [`u16`] bits as a mutable slice of [`f16`] or [`bf16`]
    /// numbers.
    ///
    /// `H` is the type to cast to, and must be either the [`f16`] or [`bf16`] type.
    ///
    /// This is a zero-copy operation. The transmuted slice has the same lifetime as the original,
    /// which prevents mutating `self` as long as the returned `&mut [f16]` is borrowed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use half::prelude::*;
    /// let mut int_buffer = [f16::from_f32(1.).to_bits(), f16::from_f32(2.).to_bits(), f16::from_f32(3.).to_bits()];
    ///
    /// {
    ///     let float_buffer: &mut [f16] = int_buffer.reinterpret_cast_mut();
    ///
    ///     assert_eq!(float_buffer, [f16::from_f32(1.), f16::from_f32(2.), f16::from_f32(3.)]);
    ///
    ///     // Mutating the f16 slice will mutating the original
    ///     float_buffer[0] = f16::from_f32(0.);
    /// }
    ///
    /// // Note that we need to drop float_buffer before using int_buffer again or we will get a borrow error.
    /// assert_eq!(int_buffer, [f16::from_f32(0.).to_bits(), f16::from_f32(2.).to_bits(), f16::from_f32(3.).to_bits()]);
    ///
    /// // You may have to specify the cast type directly if the compiler can't infer the type.
    /// // The following is also valid in Rust.
    /// let typed_buffer = int_buffer.reinterpret_cast_mut::<f16>();
    /// ```
    #[must_use]
    fn reinterpret_cast_mut<H>(&mut self) -> &mut [H]
    where
        H: crate::private::SealedHalf;
}

mod private {
    use crate::{bf16, f16};

    pub trait SealedHalfFloatSlice {}
    impl SealedHalfFloatSlice for [f16] {}
    impl SealedHalfFloatSlice for [bf16] {}

    pub trait SealedHalfBitsSlice {}
    impl SealedHalfBitsSlice for [u16] {}
}

impl HalfFloatSliceExt for [f16] {
    #[inline]
    fn reinterpret_cast(&self) -> &[u16] {
        let pointer = self.as_ptr() as *const u16;
        let length = self.len();
        // SAFETY: We are reconstructing full length of original slice, using its same lifetime,
        // and the size of elements are identical
        unsafe { slice::from_raw_parts(pointer, length) }
    }

    #[inline]
    fn reinterpret_cast_mut(&mut self) -> &mut [u16] {
        let pointer = self.as_mut_ptr().cast::<u16>();
        let length = self.len();
        // SAFETY: We are reconstructing full length of original slice, using its same lifetime,
        // and the size of elements are identical
        unsafe { slice::from_raw_parts_mut(pointer, length) }
    }

    #[inline]
    fn convert_from_f32_slice(&mut self, src: &[f32]) {
        assert_eq!(
            self.len(),
            src.len(),
            "destination and source slices have different lengths"
        );

        arch::f32_to_f16_slice(src, self.reinterpret_cast_mut())
    }

    #[inline]
    fn convert_from_f64_slice(&mut self, src: &[f64]) {
        assert_eq!(
            self.len(),
            src.len(),
            "destination and source slices have different lengths"
        );

        arch::f64_to_f16_slice(src, self.reinterpret_cast_mut())
    }

    #[inline]
    fn convert_to_f32_slice(&self, dst: &mut [f32]) {
        assert_eq!(
            self.len(),
            dst.len(),
            "destination and source slices have different lengths"
        );

        arch::f16_to_f32_slice(self.reinterpret_cast(), dst)
    }

    #[inline]
    fn convert_to_f64_slice(&self, dst: &mut [f64]) {
        assert_eq!(
            self.len(),
            dst.len(),
            "destination and source slices have different lengths"
        );

        arch::f16_to_f64_slice(self.reinterpret_cast(), dst)
    }

    #[cfg(any(feature = "alloc", feature = "std"))]
    #[inline]
    #[allow(clippy::uninit_vec)]
    fn to_f32_vec(&self) -> Vec<f32> {
        let mut vec = vec![0f32; self.len()];
        self.convert_to_f32_slice(&mut vec);
        vec
    }

    #[cfg(any(feature = "alloc", feature = "std"))]
    #[inline]
    #[allow(clippy::uninit_vec)]
    fn to_f64_vec(&self) -> Vec<f64> {
        let mut vec = vec![0f64; self.len()];
        self.convert_to_f64_slice(&mut vec);
        vec
    }
}

impl HalfFloatSliceExt for [bf16] {
    #[inline]
    fn reinterpret_cast(&self) -> &[u16] {
        let pointer = self.as_ptr() as *const u16;
        let length = self.len();
        // SAFETY: We are reconstructing full length of original slice, using its same lifetime,
        // and the size of elements are identical
        unsafe { slice::from_raw_parts(pointer, length) }
    }

    #[inline]
    fn reinterpret_cast_mut(&mut self) -> &mut [u16] {
        let pointer = self.as_mut_ptr().cast::<u16>();
        let length = self.len();
        // SAFETY: We are reconstructing full length of original slice, using its same lifetime,
        // and the size of elements are identical
        unsafe { slice::from_raw_parts_mut(pointer, length) }
    }

    #[inline]
    fn convert_from_f32_slice(&mut self, src: &[f32]) {
        assert_eq!(
            self.len(),
            src.len(),
            "destination and source slices have different lengths"
        );

        // Just use regular loop here until there's any bf16 SIMD support.
        for (i, f) in src.iter().enumerate() {
            self[i] = bf16::from_f32(*f);
        }
    }

    #[inline]
    fn convert_from_f64_slice(&mut self, src: &[f64]) {
        assert_eq!(
            self.len(),
            src.len(),
            "destination and source slices have different lengths"
        );

        // Just use regular loop here until there's any bf16 SIMD support.
        for (i, f) in src.iter().enumerate() {
            self[i] = bf16::from_f64(*f);
        }
    }

    #[inline]
    fn convert_to_f32_slice(&self, dst: &mut [f32]) {
        assert_eq!(
            self.len(),
            dst.len(),
            "destination and source slices have different lengths"
        );

        // Just use regular loop here until there's any bf16 SIMD support.
        for (i, f) in self.iter().enumerate() {
            dst[i] = f.to_f32();
        }
    }

    #[inline]
    fn convert_to_f64_slice(&self, dst: &mut [f64]) {
        assert_eq!(
            self.len(),
            dst.len(),
            "destination and source slices have different lengths"
        );

        // Just use regular loop here until there's any bf16 SIMD support.
        for (i, f) in self.iter().enumerate() {
            dst[i] = f.to_f64();
        }
    }

    #[cfg(any(feature = "alloc", feature = "std"))]
    #[inline]
    #[allow(clippy::uninit_vec)]
    fn to_f32_vec(&self) -> Vec<f32> {
        let mut vec = vec![0f32; self.len()];
        self.convert_to_f32_slice(&mut vec);
        vec
    }

    #[cfg(any(feature = "alloc", feature = "std"))]
    #[inline]
    #[allow(clippy::uninit_vec)]
    fn to_f64_vec(&self) -> Vec<f64> {
        let mut vec = vec![0f64; self.len()];
        self.convert_to_f64_slice(&mut vec);
        vec
    }
}

impl HalfBitsSliceExt for [u16] {
    // Since we sealed all the traits involved, these are safe.
    #[inline]
    fn reinterpret_cast<H>(&self) -> &[H]
    where
        H: crate::private::SealedHalf,
    {
        let pointer = self.as_ptr() as *const H;
        let length = self.len();
        // SAFETY: We are reconstructing full length of original slice, using its same lifetime,
        // and the size of elements are identical
        unsafe { slice::from_raw_parts(pointer, length) }
    }

    #[inline]
    fn reinterpret_cast_mut<H>(&mut self) -> &mut [H]
    where
        H: crate::private::SealedHalf,
    {
        let pointer = self.as_mut_ptr() as *mut H;
        let length = self.len();
        // SAFETY: We are reconstructing full length of original slice, using its same lifetime,
        // and the size of elements are identical
        unsafe { slice::from_raw_parts_mut(pointer, length) }
    }
}

#[allow(clippy::float_cmp)]
#[cfg(test)]
mod test {
    use super::{HalfBitsSliceExt, HalfFloatSliceExt};
    use crate::{bf16, f16};

    #[test]
    fn test_slice_conversions_f16() {
        let bits = &[
            f16::E.to_bits(),
            f16::PI.to_bits(),
            f16::EPSILON.to_bits(),
            f16::FRAC_1_SQRT_2.to_bits(),
        ];
        let numbers = &[f16::E, f16::PI, f16::EPSILON, f16::FRAC_1_SQRT_2];

        // Convert from bits to numbers
        let from_bits = bits.reinterpret_cast::<f16>();
        assert_eq!(from_bits, numbers);

        // Convert from numbers back to bits
        let to_bits = from_bits.reinterpret_cast();
        assert_eq!(to_bits, bits);
    }

    #[test]
    fn test_mutablility_f16() {
        let mut bits_array = [f16::PI.to_bits()];
        let bits = &mut bits_array[..];

        {
            // would not compile without these braces
            let numbers = bits.reinterpret_cast_mut();
            numbers[0] = f16::E;
        }

        assert_eq!(bits, &[f16::E.to_bits()]);

        bits[0] = f16::LN_2.to_bits();
        assert_eq!(bits, &[f16::LN_2.to_bits()]);
    }

    #[test]
    fn test_slice_conversions_bf16() {
        let bits = &[
            bf16::E.to_bits(),
            bf16::PI.to_bits(),
            bf16::EPSILON.to_bits(),
            bf16::FRAC_1_SQRT_2.to_bits(),
        ];
        let numbers = &[bf16::E, bf16::PI, bf16::EPSILON, bf16::FRAC_1_SQRT_2];

        // Convert from bits to numbers
        let from_bits = bits.reinterpret_cast::<bf16>();
        assert_eq!(from_bits, numbers);

        // Convert from numbers back to bits
        let to_bits = from_bits.reinterpret_cast();
        assert_eq!(to_bits, bits);
    }

    #[test]
    fn test_mutablility_bf16() {
        let mut bits_array = [bf16::PI.to_bits()];
        let bits = &mut bits_array[..];

        {
            // would not compile without these braces
            let numbers = bits.reinterpret_cast_mut();
            numbers[0] = bf16::E;
        }

        assert_eq!(bits, &[bf16::E.to_bits()]);

        bits[0] = bf16::LN_2.to_bits();
        assert_eq!(bits, &[bf16::LN_2.to_bits()]);
    }

    #[test]
    fn slice_convert_f16_f32() {
        // Exact chunks
        let vf32 = [1., 2., 3., 4., 5., 6., 7., 8.];
        let vf16 = [
            f16::from_f32(1.),
            f16::from_f32(2.),
            f16::from_f32(3.),
            f16::from_f32(4.),
            f16::from_f32(5.),
            f16::from_f32(6.),
            f16::from_f32(7.),
            f16::from_f32(8.),
        ];
        let mut buf32 = vf32;
        let mut buf16 = vf16;

        vf16.convert_to_f32_slice(&mut buf32);
        assert_eq!(&vf32, &buf32);

        buf16.convert_from_f32_slice(&vf32);
        assert_eq!(&vf16, &buf16);

        // Partial with chunks
        let vf32 = [1., 2., 3., 4., 5., 6., 7., 8., 9.];
        let vf16 = [
            f16::from_f32(1.),
            f16::from_f32(2.),
            f16::from_f32(3.),
            f16::from_f32(4.),
            f16::from_f32(5.),
            f16::from_f32(6.),
            f16::from_f32(7.),
            f16::from_f32(8.),
            f16::from_f32(9.),
        ];
        let mut buf32 = vf32;
        let mut buf16 = vf16;

        vf16.convert_to_f32_slice(&mut buf32);
        assert_eq!(&vf32, &buf32);

        buf16.convert_from_f32_slice(&vf32);
        assert_eq!(&vf16, &buf16);

        // Partial with chunks
        let vf32 = [1., 2.];
        let vf16 = [f16::from_f32(1.), f16::from_f32(2.)];
        let mut buf32 = vf32;
        let mut buf16 = vf16;

        vf16.convert_to_f32_slice(&mut buf32);
        assert_eq!(&vf32, &buf32);

        buf16.convert_from_f32_slice(&vf32);
        assert_eq!(&vf16, &buf16);
    }

    #[test]
    fn slice_convert_bf16_f32() {
        // Exact chunks
        let vf32 = [1., 2., 3., 4., 5., 6., 7., 8.];
        let vf16 = [
            bf16::from_f32(1.),
            bf16::from_f32(2.),
            bf16::from_f32(3.),
            bf16::from_f32(4.),
            bf16::from_f32(5.),
            bf16::from_f32(6.),
            bf16::from_f32(7.),
            bf16::from_f32(8.),
        ];
        let mut buf32 = vf32;
        let mut buf16 = vf16;

        vf16.convert_to_f32_slice(&mut buf32);
        assert_eq!(&vf32, &buf32);

        buf16.convert_from_f32_slice(&vf32);
        assert_eq!(&vf16, &buf16);

        // Partial with chunks
        let vf32 = [1., 2., 3., 4., 5., 6., 7., 8., 9.];
        let vf16 = [
            bf16::from_f32(1.),
            bf16::from_f32(2.),
            bf16::from_f32(3.),
            bf16::from_f32(4.),
            bf16::from_f32(5.),
            bf16::from_f32(6.),
            bf16::from_f32(7.),
            bf16::from_f32(8.),
            bf16::from_f32(9.),
        ];
        let mut buf32 = vf32;
        let mut buf16 = vf16;

        vf16.convert_to_f32_slice(&mut buf32);
        assert_eq!(&vf32, &buf32);

        buf16.convert_from_f32_slice(&vf32);
        assert_eq!(&vf16, &buf16);

        // Partial with chunks
        let vf32 = [1., 2.];
        let vf16 = [bf16::from_f32(1.), bf16::from_f32(2.)];
        let mut buf32 = vf32;
        let mut buf16 = vf16;

        vf16.convert_to_f32_slice(&mut buf32);
        assert_eq!(&vf32, &buf32);

        buf16.convert_from_f32_slice(&vf32);
        assert_eq!(&vf16, &buf16);
    }

    #[test]
    fn slice_convert_f16_f64() {
        // Exact chunks
        let vf64 = [1., 2., 3., 4., 5., 6., 7., 8.];
        let vf16 = [
            f16::from_f64(1.),
            f16::from_f64(2.),
            f16::from_f64(3.),
            f16::from_f64(4.),
            f16::from_f64(5.),
            f16::from_f64(6.),
            f16::from_f64(7.),
            f16::from_f64(8.),
        ];
        let mut buf64 = vf64;
        let mut buf16 = vf16;

        vf16.convert_to_f64_slice(&mut buf64);
        assert_eq!(&vf64, &buf64);

        buf16.convert_from_f64_slice(&vf64);
        assert_eq!(&vf16, &buf16);

        // Partial with chunks
        let vf64 = [1., 2., 3., 4., 5., 6., 7., 8., 9.];
        let vf16 = [
            f16::from_f64(1.),
            f16::from_f64(2.),
            f16::from_f64(3.),
            f16::from_f64(4.),
            f16::from_f64(5.),
            f16::from_f64(6.),
            f16::from_f64(7.),
            f16::from_f64(8.),
            f16::from_f64(9.),
        ];
        let mut buf64 = vf64;
        let mut buf16 = vf16;

        vf16.convert_to_f64_slice(&mut buf64);
        assert_eq!(&vf64, &buf64);

        buf16.convert_from_f64_slice(&vf64);
        assert_eq!(&vf16, &buf16);

        // Partial with chunks
        let vf64 = [1., 2.];
        let vf16 = [f16::from_f64(1.), f16::from_f64(2.)];
        let mut buf64 = vf64;
        let mut buf16 = vf16;

        vf16.convert_to_f64_slice(&mut buf64);
        assert_eq!(&vf64, &buf64);

        buf16.convert_from_f64_slice(&vf64);
        assert_eq!(&vf16, &buf16);
    }

    #[test]
    fn slice_convert_bf16_f64() {
        // Exact chunks
        let vf64 = [1., 2., 3., 4., 5., 6., 7., 8.];
        let vf16 = [
            bf16::from_f64(1.),
            bf16::from_f64(2.),
            bf16::from_f64(3.),
            bf16::from_f64(4.),
            bf16::from_f64(5.),
            bf16::from_f64(6.),
            bf16::from_f64(7.),
            bf16::from_f64(8.),
        ];
        let mut buf64 = vf64;
        let mut buf16 = vf16;

        vf16.convert_to_f64_slice(&mut buf64);
        assert_eq!(&vf64, &buf64);

        buf16.convert_from_f64_slice(&vf64);
        assert_eq!(&vf16, &buf16);

        // Partial with chunks
        let vf64 = [1., 2., 3., 4., 5., 6., 7., 8., 9.];
        let vf16 = [
            bf16::from_f64(1.),
            bf16::from_f64(2.),
            bf16::from_f64(3.),
            bf16::from_f64(4.),
            bf16::from_f64(5.),
            bf16::from_f64(6.),
            bf16::from_f64(7.),
            bf16::from_f64(8.),
            bf16::from_f64(9.),
        ];
        let mut buf64 = vf64;
        let mut buf16 = vf16;

        vf16.convert_to_f64_slice(&mut buf64);
        assert_eq!(&vf64, &buf64);

        buf16.convert_from_f64_slice(&vf64);
        assert_eq!(&vf16, &buf16);

        // Partial with chunks
        let vf64 = [1., 2.];
        let vf16 = [bf16::from_f64(1.), bf16::from_f64(2.)];
        let mut buf64 = vf64;
        let mut buf16 = vf16;

        vf16.convert_to_f64_slice(&mut buf64);
        assert_eq!(&vf64, &buf64);

        buf16.convert_from_f64_slice(&vf64);
        assert_eq!(&vf16, &buf16);
    }

    #[test]
    #[should_panic]
    fn convert_from_f32_slice_len_mismatch_panics() {
        let mut slice1 = [f16::ZERO; 3];
        let slice2 = [0f32; 4];
        slice1.convert_from_f32_slice(&slice2);
    }

    #[test]
    #[should_panic]
    fn convert_from_f64_slice_len_mismatch_panics() {
        let mut slice1 = [f16::ZERO; 3];
        let slice2 = [0f64; 4];
        slice1.convert_from_f64_slice(&slice2);
    }

    #[test]
    #[should_panic]
    fn convert_to_f32_slice_len_mismatch_panics() {
        let slice1 = [f16::ZERO; 3];
        let mut slice2 = [0f32; 4];
        slice1.convert_to_f32_slice(&mut slice2);
    }

    #[test]
    #[should_panic]
    fn convert_to_f64_slice_len_mismatch_panics() {
        let slice1 = [f16::ZERO; 3];
        let mut slice2 = [0f64; 4];
        slice1.convert_to_f64_slice(&mut slice2);
    }
}