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
#![cfg_attr(feature = "allocator_api", feature(allocator_api))]
#![cfg_attr(not(feature = "std"), no_std)]

#![warn(unsafe_op_in_unsafe_fn)]
#![deny(missing_docs)]
//! This is a way to "transmute" Vecs soundly.
//! ```
//! #![feature(allocator_api)] // this requires the allocator api because the way that this
//! // handles deallocating hooks into the allocator api
//! use transvec::transmute_vec;
//! let input_vec: Vec<u16> = vec![1, 2, 3, 4, 5, 6, 7, 8];
//! let output: Vec<u8, _> = match transmute_vec(input_vec) {
//!     Ok(x) => x,
//!     // the "transmute" can fail, if the alignment/capacity/length is incorrect
//!     // consider using `transmute_vec_may_copy`
//!     Err((old_vec, err)) => return println!("Error: {:?}", err),
//! };
//! if cfg!(target_endian = "big") {
//!     assert_eq!(
//!         &output,
//!         &[0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8]
//!     );
//! } else {
//!     assert_eq!(
//!         &output,
//!         &[1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0]
//!     );
//! }

extern crate alloc;

use alloc::vec::Vec;
use bytemuck::Pod;
#[cfg(feature = "allocator_api")]
use core::alloc::{AllocError, Allocator, Layout};
use core::{
    cell::Cell,
    cmp::Ordering,
    fmt::Display,
    hint,
    marker::PhantomData,
    mem::{self, ManuallyDrop},
    ptr::{self, NonNull},
    slice,
};

#[cfg(feature = "std")]
use std::error::Error;

/// Error for Vec transmutes.
/// It will always be `Alignment` -> `Length` -> `Capacity`
#[derive(Debug, PartialEq, Eq)]
pub enum TransmuteError {
    // #[error("alignment of vec is incorrect")]
    /// When the alignment of vec is incorrect.
    Alignment,
    // #[error("length of vec is incorrect")]
    /// When the length wouldn't be able to fit.
    Length,
    // #[error("capacicty of vec is incorrect")]
    /// When the capacity wouldn't be able to fit.
    Capacity,
}

impl Display for TransmuteError {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            TransmuteError::Alignment => write!(formatter, "Alignment: alignment of the pointer to I must be equal or greater than the alignment of O"),
            TransmuteError::Length => write!(formatter, "Length: I's items cant fit in O's (e.g. 1 u8 to 1 u16)"),
            TransmuteError::Capacity => write!(formatter, "Capacity: capacicty of vec is incorrect"),
        }
    }
}

#[cfg(feature = "std")]
impl Error for TransmuteError {}

#[cfg(feature = "allocator_api")]
/// Handling correcting the alignment fed into the inner allocator.
#[derive(Debug)]
pub struct AlignmentCorrectorAllocator<I, O, A: Allocator> {
    allocator: A,
    ptr: Cell<Option<NonNull<O>>>,
    phantom: PhantomData<I>,
}
#[cfg(feature = "allocator_api")]
impl<I, O, A: Allocator> AlignmentCorrectorAllocator<I, O, A> {
    /// Create new `AlignmentCorrectorAllocator`.
    ///
    /// # Safety
    /// The `ptr` must be allocated with the `allocator` in the alignment of `I`.
    pub unsafe fn new(ptr: NonNull<O>, allocator: A) -> Self {
        Self {
            allocator,
            ptr: Cell::new(Some(ptr)),
            phantom: PhantomData::default(),
        }
    }
    /// Create a new `AlignmentCorrectorAllocator` that acts the same as the allocator fed into it.
    pub fn new_null(allocator: A) -> Self {
        Self {
            allocator,
            ptr: Cell::new(None),
            phantom: PhantomData::default(),
        }
    }
}

#[cfg(feature = "allocator_api")]
unsafe impl<I, O, A: Allocator> Allocator for AlignmentCorrectorAllocator<I, O, A> {
    #[inline]
    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        self.allocator.allocate(layout)
    }

    #[inline]
    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        self.allocator.allocate_zeroed(layout)
    }

    #[inline]
    unsafe fn deallocate(&self, ptr: NonNull<u8>, mut layout: Layout) {
        if Some(ptr.cast()) == self.ptr.get() {
            layout =
                unsafe { Layout::from_size_align_unchecked(layout.size(), mem::align_of::<I>()) };
            self.ptr.set(None);
        }
        // SAFETY: all conditions must be upheld by the caller
        unsafe { self.allocator.deallocate(ptr, layout) }
    }

    #[inline]
    unsafe fn grow(
        &self,
        ptr: NonNull<u8>,
        mut old_layout: Layout,
        new_layout: Layout,
    ) -> Result<NonNull<[u8]>, AllocError> {
        if Some(ptr.cast()) == self.ptr.get() {
            old_layout = unsafe {
                Layout::from_size_align_unchecked(old_layout.size(), mem::align_of::<I>())
            };
            self.ptr.set(None);
        }
        // SAFETY: all conditions must be upheld by the caller
        unsafe { self.allocator.grow(ptr, old_layout, new_layout) }
    }

    #[inline]
    unsafe fn grow_zeroed(
        &self,
        ptr: NonNull<u8>,
        mut old_layout: Layout,
        new_layout: Layout,
    ) -> Result<NonNull<[u8]>, AllocError> {
        if Some(ptr.cast()) == self.ptr.get() {
            old_layout = unsafe {
                Layout::from_size_align_unchecked(old_layout.size(), mem::align_of::<I>())
            };
            self.ptr.set(None);
        }
        // SAFETY: all conditions must be upheld by the caller
        unsafe { self.allocator.grow_zeroed(ptr, old_layout, new_layout) }
    }

    #[inline]
    unsafe fn shrink(
        &self,
        ptr: NonNull<u8>,
        mut old_layout: Layout,
        new_layout: Layout,
    ) -> Result<NonNull<[u8]>, AllocError> {
        if Some(ptr.cast()) == self.ptr.get() {
            old_layout = unsafe {
                Layout::from_size_align_unchecked(old_layout.size(), mem::align_of::<I>())
            };
            self.ptr.set(None);
        }
        // SAFETY: all conditions must be upheld by the caller
        unsafe { self.allocator.shrink(ptr, old_layout, new_layout) }
    }
}

#[cfg(feature = "allocator_api")]
unsafe fn from_raw_parts<I, O, A: Allocator>(
    old_ptr: NonNull<O>,
    length: usize,
    capacity: usize,
    allocator: A,
) -> Vec<O, AlignmentCorrectorAllocator<I, O, A>> {
    // SAFETY: the caller uploads the constrants for from_raw_parts except for the alignment of the
    // allocation that created the old pointer
    unsafe {
        Vec::<O, AlignmentCorrectorAllocator<I, O, A>>::from_raw_parts_in(
            old_ptr.as_ptr(),
            length,
            capacity,
            AlignmentCorrectorAllocator::<I, O, A>::new(old_ptr, allocator),
        )
    }
}

#[cfg(feature = "allocator_api")]
/// Whether or not a copy occured.
/// Also the copy variant doesn't have the custom allocator, and is therefore one usize smaller.
pub enum CopyNot<I, O, A: Allocator> {
    /// Copy occured.
    Copy(Vec<O, A>),
    /// There was no copy.
    Not(Vec<O, AlignmentCorrectorAllocator<I, O, A>>),
}

#[cfg(feature = "allocator_api")]
/// [`transmute_vec_may_copy`] but it tells you whether or not a copy occured and returns a normal
/// vec if it doesn't.
pub fn transmute_vec_copy_enum<I: Pod, O: Pod, A: Allocator>(input: Vec<I, A>) -> CopyNot<I, O, A> {
    match transmute_vec(input) {
        Ok(x) => CopyNot::Not(x),
        Err((old_vec, err)) => match err {
            TransmuteError::Alignment => {
                // I don't have to deal with ZSTs because transmute_vec will never fail with a ZST.
                let (ptr, length, capacity, allocator) = {
                    let mut me = ManuallyDrop::new(old_vec);
                    (me.as_mut_ptr(), me.len(), me.capacity(), unsafe {
                        ptr::read(me.allocator())
                    })
                };

                // SAFETY: the ptr comes from a vec and the length is calcuated properly
                let bytes_slice = unsafe {
                    slice::from_raw_parts(ptr.cast::<u8>(), length * mem::size_of::<I>())
                };
                let mut return_vec = Vec::with_capacity_in(
                    (length * mem::size_of::<I>()) / mem::size_of::<O>(),
                    allocator,
                );
                for x in bytes_slice.chunks_exact(mem::size_of::<O>()) {
                    // SAFETY: O is Pod and the slice is the same length as the type.
                    // also its
                    return_vec.push(unsafe { ptr::read_unaligned(x.as_ptr().cast()) })
                }
                // freeing memory
                // SAFETY: this size and align come from a vec and the allocator is the same one
                // that allocated the memory. i dont have to call drop because its Pod
                unsafe {
                    let align = mem::align_of::<I>();
                    let size = mem::size_of::<I>() * capacity;
                    let layout = Layout::from_size_align_unchecked(size, align);
                    // ensuring i dont deallocate unallocated memory
                    if size != 0 {
                        return_vec
                            .allocator()
                            .deallocate(NonNull::new_unchecked(ptr.cast()), layout);
                    }
                };
                CopyNot::Copy(return_vec)
            }
            TransmuteError::Capacity | TransmuteError::Length => {
                // I don't have to deal with ZSTs because transmute_vec will never fail with a ZST.
                let (ptr, length, capacity, allocator) = {
                    let mut me = ManuallyDrop::new(old_vec);
                    (me.as_mut_ptr(), me.len(), me.capacity(), unsafe {
                        ptr::read(me.allocator())
                    })
                };

                // SAFETY: the divide rounds down so the length is correct
                let return_vec = unsafe {
                    slice::from_raw_parts(
                        ptr.cast::<O>(),
                        (length * mem::size_of::<I>()) / mem::size_of::<O>(),
                    )
                }
                .to_vec_in(allocator);

                // freeing memory
                // SAFETY: this size and align come from a vec and the allocator is the same one
                // that allocated the memory. i dont have to call drop because its Pod
                unsafe {
                    let align = mem::align_of::<I>();
                    let size = mem::size_of::<I>() * capacity;
                    let layout = Layout::from_size_align_unchecked(size, align);
                    // ensuring i dont deallocate ZSTs or unallocated memory
                    if size != 0 {
                        return_vec
                            .allocator()
                            .deallocate(NonNull::new_unchecked(ptr.cast()), layout);
                    }
                };
                CopyNot::Copy(return_vec)
            }
        },
    }
}

#[cfg(feature = "allocator_api")]
/// Same as `transmute_vec` but in case of an error it copies instead.
/// If it's over the length it removes whatever doesn't fit.
///
/// You may want to use [`transmute_vec_copy_enum`].
pub fn transmute_vec_may_copy<I: Pod, O: Pod, A: Allocator>(
    input: Vec<I, A>,
) -> Vec<O, AlignmentCorrectorAllocator<I, O, A>> {
    match transmute_vec_copy_enum(input) {
        CopyNot::Copy(x) => {
            let (ptr, length, capacity, allocator) = {
                let mut me = ManuallyDrop::new(x);
                (me.as_mut_ptr(), me.len(), me.capacity(), unsafe {
                    ptr::read(me.allocator())
                })
            };

            // SAFETY: comes directly from vec and AlignmentCorrectorAllocator::new_null
            // doesn't interfere with the allocator within
            unsafe {
                Vec::from_raw_parts_in(
                    ptr,
                    length,
                    capacity,
                    AlignmentCorrectorAllocator::new_null(allocator),
                )
            }
        }
        CopyNot::Not(x) => x,
    }
}

/// Allows transmuting of a Vec to another vec of a different size, with 0 copies.
/// # Example
/// ```
/// #![feature(allocator_api)] // this requires the allocator api because the way that this
/// // handles deallocating hooks into the allocator api
/// use transvec::transmute_vec;
/// let input_vec: Vec<u16> = vec![1, 2, 3, 4, 5, 6, 7, 8];
/// let output: Vec<u8, _> = match transmute_vec(input_vec) {
///     Ok(x) => x,
///     // the "transmute" can fail, if the alignment/capacity/length is incorrect
///     // consider using `transmute_vec_may_copy`
///     Err((old_vec, err)) => return println!("Error: {:?}", err),
/// };
/// if cfg!(target_endian = "big") {
///     assert_eq!(
///         &output,
///         &[0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8]
///     );
/// } else {
///     assert_eq!(
///         &output,
///         &[1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0]
///     );
/// }
/// ```
/// # Errors
/// This errors when:
/// 1. The length of the vector wouldn't fit the type.
/// ```should_panic
/// # #![feature(allocator_api)]
/// # use transvec::transmute_vec;
/// let input: Vec<u8> = vec![1, 2, 3];
/// let output: Vec<u16, _> = transmute_vec(input).unwrap();
/// ```
/// 2. The capacity can't be converted to units of the output type.
/// ```should_panic
/// # #![feature(allocator_api)]
/// # use transvec::transmute_vec;
/// let input: Vec<u8> = Vec::with_capacity(3);
/// let output: Vec<u16, _> = transmute_vec(input).unwrap();
/// ```
/// 3. The alignment of the vec is wrong.
///
/// Alignment, then length, then capacity will always be returned.
/// # ZSTs
/// 1. Anything -> ZST
///     - Keeps length, deallocates data.
/// 2. ZST -> Non ZST
///     - New Vec from previous allocator.
/// 3. Just don't do this.
///
/// # See also
/// - [`transmute_vec_may_copy`] -- Infailable
/// - [`transmute_vec_basic`] -- Returns a Vec without a specical allocator and works on stable, but only works with types with the same alignment.
#[cfg(feature = "allocator_api")]
#[allow(clippy::type_complexity)]
pub fn transmute_vec<I: Pod, O: Pod, A: Allocator>(
    input: Vec<I, A>,
) -> Result<Vec<O, AlignmentCorrectorAllocator<I, O, A>>, (Vec<I, A>, TransmuteError)> {
    let (ptr, length, capacity, allocator) = {
        let mut me = ManuallyDrop::new(input);
        (me.as_mut_ptr(), me.len(), me.capacity(), unsafe {
            ptr::read(me.allocator())
        })
    };
    if mem::size_of::<O>() == 0 {
        // freeing memory
        // SAFETY: this size and align come from a vec and the allocator is the same one
        // that allocated the memory. i dont have to call drop because its Pod
        unsafe {
            let align = mem::align_of::<I>();
            let size = mem::size_of::<I>() * capacity;
            // ensuring i dont deallocate ZSTs or stuff with 0 capacity.
            if size != 0 {
                let layout = Layout::from_size_align_unchecked(size, align);
                allocator.deallocate(NonNull::new_unchecked(ptr.cast()), layout);
            }
        };

        let mut return_vec =
            Vec::with_capacity_in(capacity, AlignmentCorrectorAllocator::new_null(allocator));
        unsafe { return_vec.set_len(length) };

        return Ok(return_vec);
    } else if mem::size_of::<I>() == 0 || capacity == 0 {
        // freeing memory
        // SAFETY: this size and align come from a vec and the allocator is the same one
        // that allocated the memory. i dont have to call drop because its Pod
        unsafe {
            let align = mem::align_of::<I>();
            let size = mem::size_of::<I>() * capacity;
            // ensuring i dont deallocate ZSTs or stuff with 0 capacity.
            if size != 0 {
                let layout = Layout::from_size_align_unchecked(size, align);
                allocator.deallocate(NonNull::new_unchecked(ptr.cast()), layout);
            }
        };
        return Ok(Vec::new_in(AlignmentCorrectorAllocator::new_null(
            allocator,
        )));
    }

    match mem::size_of::<I>().cmp(&mem::size_of::<O>()) {
        Ordering::Greater | Ordering::Less => {
            if ptr.align_offset(mem::align_of::<O>()) != 0 {
                Err((
                    // SAFETY: this came directly from a vec
                    unsafe { Vec::from_raw_parts_in(ptr, length, capacity, allocator) },
                    TransmuteError::Alignment,
                ))
            } else if (length * mem::size_of::<I>()) % mem::size_of::<O>() != 0 {
                Err((
                    // SAFETY: this came directly from a vec
                    unsafe { Vec::from_raw_parts_in(ptr, length, capacity, allocator) },
                    TransmuteError::Length,
                ))
            } else if (capacity * mem::size_of::<I>()) % mem::size_of::<O>() != 0 {
                Err((
                    // SAFETY: this came directly from a vec
                    unsafe { Vec::from_raw_parts_in(ptr, length, capacity, allocator) },
                    TransmuteError::Capacity,
                ))
            } else {
                // SAFETY: the length and capacity of vec is corrected to be the correct size,
                // and its not discarding bytes on the end. the alignment is also checked and on
                // drop, the custom allocator ensures deallocation is handled properly
                // vecs also only give out nonnull ptrs
                Ok(unsafe {
                    from_raw_parts(
                        NonNull::new_unchecked(ptr).cast(),
                        (length * mem::size_of::<I>()) / mem::size_of::<O>(),
                        (capacity * mem::size_of::<I>()) / mem::size_of::<O>(),
                        allocator,
                    )
                })
            }
        }
        Ordering::Equal => {
            if ptr.align_offset(mem::align_of::<O>()) == 0 {
                // SAFETY: its aligned and thats all that matters
                Ok(unsafe {
                    from_raw_parts(
                        NonNull::new_unchecked(ptr).cast(),
                        length,
                        capacity,
                        allocator,
                    )
                })
            } else {
                Err((
                    // SAFETY: this came directly from a vec
                    unsafe { Vec::from_raw_parts_in(ptr, length, capacity, allocator) },
                    TransmuteError::Alignment,
                ))
            }
        }
    }
}

/// If alignment is the same this function is preferred over [`transmute_vec`].
/// # Panics
/// Panics if the alignment is not the same.
/// (This may be turned into a compile time error in the future, when possible without using nightly
/// features).
/// 
/// Otherwise this acts exactly the same as [`transmute_vec`].
pub fn transmute_vec_basic<I: Pod, O: Pod>(
    input: Vec<I>,
) -> Result<Vec<O>, (Vec<I>, TransmuteError)> {
    let (ptr, length, capacity) = {
        let mut me = ManuallyDrop::new(input);
        (me.as_mut_ptr(), me.len(), me.capacity())
    };

    if mem::align_of::<I>() != mem::align_of::<O>() {
        panic!(
            "Alignment of {} and {} are not the same",
            core::any::type_name::<I>(),
            core::any::type_name::<O>(),
        )
    } else if mem::size_of::<O>() == 0 {
        drop(unsafe { Vec::from_raw_parts(ptr, length, capacity) });
        let mut vec = Vec::with_capacity(capacity);
        // SAFETY: its a zst so this is allowed
        unsafe { vec.set_len(length) };
        return Ok(vec);
    } else if mem::size_of::<I>() == 0 || capacity == 0 {
        // SAFETY: this came directly from a vec
        drop(unsafe { Vec::from_raw_parts(ptr, length, capacity) });
        return Ok(Vec::new());
    }

    match mem::size_of::<I>().cmp(&mem::size_of::<O>()) {
        Ordering::Greater | Ordering::Less => {
            if (length * mem::size_of::<I>()) % mem::size_of::<O>() != 0 {
                Err((
                    // SAFETY: this came directly from a vec
                    unsafe { Vec::from_raw_parts(ptr, length, capacity) },
                    TransmuteError::Length,
                ))
            } else if (capacity * mem::size_of::<I>()) % mem::size_of::<O>() != 0 {
                Err((
                    // SAFETY: this came directly from a vec
                    unsafe { Vec::from_raw_parts(ptr, length, capacity) },
                    TransmuteError::Capacity,
                ))
            } else {
                // SAFETY: the length and capacity of vec is corrected to be the correct size,
                // and its not discarding bytes on the end. the alignment is also checked.
                Ok(unsafe {
                    Vec::from_raw_parts(
                        ptr.cast(),
                        (length * mem::size_of::<I>()) / mem::size_of::<O>(),
                        (capacity * mem::size_of::<I>()) / mem::size_of::<O>(),
                    )
                })
            }
        }
        Ordering::Equal => {
            // SAFETY: they are both the same size and Pod
            Ok(unsafe {
                Vec::from_raw_parts(
                    ptr.cast(),
                    (length * mem::size_of::<I>()) / mem::size_of::<O>(),
                    (capacity * mem::size_of::<I>()) / mem::size_of::<O>(),
                )
            })
        }
    }
}

/// [`transmute_vec_basic`] but on fail it copies instead.
pub fn transmute_vec_basic_copy<I: Pod, O: Pod>(input: Vec<I>) -> Vec<O> {
    match transmute_vec_basic(input) {
        Ok(x) => x,
        Err((old_vec, err)) => match err {
            TransmuteError::Alignment => unsafe { hint::unreachable_unchecked() },
            TransmuteError::Capacity | TransmuteError::Length => {
                // I don't have to deal with ZSTs because transmute_vec will never fail with a ZST.
                let ptr = old_vec.as_ptr();
                let length = old_vec.len();
                // SAFETY: the divide rounds down so the length is correct
                unsafe {
                    slice::from_raw_parts(
                        ptr.cast::<O>(),
                        (length * mem::size_of::<I>()) / mem::size_of::<O>(),
                    )
                }
                .to_vec()
            }
        },
    }
}

#[cfg(test)]
mod tests {

    use alloc::{vec, vec::Vec};

    use crate::{
        transmute_vec, transmute_vec_basic, transmute_vec_basic_copy, transmute_vec_may_copy,
        TransmuteError,
    };

    #[test]
    #[cfg(feature = "allocator_api")]
    // It does work with the same sized types
    fn basic_functioning() {
        let input: Vec<u8> = vec![0, 1, 2, 3, 4, 6];
        let output: Vec<i8, _> = match transmute_vec(input) {
            Ok(x) => x,
            Err(_) => return,
        };
        assert_eq!(&output, &[0, 1, 2, 3, 4, 6]);
    }
    #[test]
    // It does work with the same sized types
    
    fn basic_basic_functioning() {
        let input: Vec<u8> = vec![0, 1, 2, 3, 4, 6];
        let output: Vec<i8> = match transmute_vec_basic(input) {
            Ok(x) => x,
            Err(_) => return,
        };
        assert_eq!(&output, &[0, 1, 2, 3, 4, 6]);
    }

    #[test]
    #[should_panic]
    fn unalign_panic() {
        let _ = transmute_vec_basic::<u8, u16>(Vec::new());
    }

    #[test]
    fn different_size_same_align() {
        let input: Vec<u8> = vec![0, 1, 2, 3, 4, 6];
        let output: Vec<[u8; 2]> = match transmute_vec_basic(input) {
            Ok(x) => x,
            Err(_) => return,
        };
        assert_eq!(&output, &[[0, 1], [2, 3], [4, 6]])
    }

    #[test]
    #[cfg(feature = "allocator_api")]
    fn small_to_large() {
        let input: Vec<u8> = vec![0, 1, 2, 3, 4, 6];
        let output: Vec<u16, _> = match transmute_vec(input) {
            Ok(x) => x,
            Err(_) => return,
        };
        if cfg!(target_endian = "big") {
            assert_eq!(&output, &[1, 515, 1030]);
        } else {
            assert_eq!(&output, &[256, 770, 1540]);
        }
    }
    #[test]
    #[cfg(feature = "allocator_api")]
    fn large_to_small() {
        let input: Vec<u16> = vec![1, 2, 3, 4, 5, 6, 7, 8];
        let output: Vec<u8, _> = match transmute_vec(input) {
            Ok(x) => x,
            Err(_) => return ,
        };
        if cfg!(target_endian = "big") {
            assert_eq!(&output, &[0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8]);
        } else {
            assert_eq!(&output, &[1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0]);
        }
    }


    #[test]
    fn to_zsts_basic() {
        let input: Vec<u8> = vec![0, 1, 2, 3, 4, 5];
        let output: Vec<()> = match transmute_vec_basic(input) {
            Ok(x) => x,
            Err(_) => return,
        };
        assert_eq!(output.len(), 6);
    }

    #[test]
    #[cfg(feature = "allocator_api")]
    fn add_and_remove() {
        let input: Vec<u16> = vec![1, 2, 3, 4, 5, 6, 7, 8];
        let mut output: Vec<u8, _> = match transmute_vec(input) {
            Ok(x) => x,
            Err(_) => return,
        };
        output.extend_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 9]);
        for _ in 0..10 {
            output.pop();
        }
        output.shrink_to_fit()
    }

    #[test]
    fn wrong_length() {
        let input: Vec<u8> = vec![1, 2, 3];
        match transmute_vec::<_, u16, _>(input) {
            Ok(_) => panic!(),
            Err((_, err)) => match err {
                TransmuteError::Alignment | TransmuteError::Length => (),
                x => panic!("{:?}", x),
            },
        };
    }

    #[test]
    #[cfg(feature = "allocator_api")]
    fn wrong_length_copy() {
        let input: Vec<u8> = vec![1, 2, 3];
        let output: Vec<u16, _> = transmute_vec_may_copy::<_, u16, _>(input);
        if cfg!(target_endian = "big") {
            assert_eq!(&output, &[258]);
        } else {
            assert_eq!(&output, &[513]);
        }
    }

    #[test]
    #[cfg(feature = "allocator_api")]
    fn may_copy() {
        let input: Vec<u8> = vec![1, 2];
        let output: Vec<u16, _> = transmute_vec_may_copy::<_, u16, _>(input);
        if cfg!(target_endian = "big") {
            assert_eq!(&output, &[258]);
        } else {
            assert_eq!(&output, &[513]);
        }
    }

    #[test]
    fn basic_copy() {
        let input: Vec<u8> = vec![1, 2];
        let output: Vec<[u8; 2]> = transmute_vec_basic_copy(input);
        assert_eq!(&output, &[[1, 2]]);
    }

    #[test]
    #[cfg(feature = "allocator_api")]
    fn from_zsts() {
        let input = vec![(), (), ()];
        let output: Vec<u8, _> = match transmute_vec(input) {
            Ok(x) => x,
            Err(_) => return,
        };
        assert_eq!(output.len(), 0);
    }

    #[test]
    #[cfg(feature = "allocator_api")]
    fn to_zsts() {
        let input: Vec<u8> = vec![0, 1, 2, 3, 4, 5];
        let output: Vec<(), _> = match transmute_vec(input) {
            Ok(x) => x,
            Err(_) => return,
        };
        assert_eq!(output.len(), 6);
    }
}