uninit_buffers 0.1.1

Safe uninitialized buffers that take input from functions or iterators.
Documentation
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
// src/lib.rs
//
// Copyright (C) 2023-2025 James Petersen <m@jamespetersen.ca>
// Licensed under Apache 2.0 OR MIT. See LICENSE-APACHE or LICENSE-MIT

#![cfg_attr(not(test), no_std)]
#![warn(missing_docs)]

//! This crate aims to fill a hole in the currently-unstable [`MaybeUninit`] slice-filling API:
//! there is a safe way to fill a slice, but there is no safe way to drop elements of the slice.
//! For this purpose, we introduce a wrapper type, [`Initialized`], which will drop the initialized
//! elements when it goes out of scope.
//!
//! Regarding safety, we treat the [`Initialized`] structure as if it owns the elements that are
//! filled. It is instantiated by using the [`SliceExt`] trait, which is implemented on all
//! [`MaybeUninit`] slices.
//!
//! # Usage
//! This crate is on [crates.io](https://crates.io/crates/uninit_buffers) and can be used
//! by executing `cargo add uninit_buffers` or by adding the following to the dependencies in your
//! `Cargo.toml` file.
//!
//! ```toml
//! [dependencies]
//! uninit_buffers = "0.1"
//! ```
//!
//! From here, you will want to
//! ```no_run
//! use uninit_buffers::SliceExt;
//! ```
//! This will allow you to write into any [`MaybeUninit`] slices.
//!
//! # Examples
//! ## Fill a buffer from an iterator.
//! ```
//! use std::mem::MaybeUninit;
//! use uninit_buffers::SliceExt;
//!
//! let mut buf = [const { MaybeUninit::uninit() }; 8];
//!
//! let original = ["fundamental", "theorem", "of", "calculus"].as_ref();
//! // strings are allocated in to_owned
//! let iter = original.iter().map(ToOwned::to_owned);
//! let (initialized, remainder) = buf.write_iter_owned(iter);
//!
//! assert_eq!(&*initialized, original);
//! assert_eq!(remainder.len(), 4);
//!
//! // this will drop the created strings. no need for unsafe!
//! drop(initialized);
//! ```
//! ## Fill a byte buffer from an input stream.
//! ```
//! # use std::io;
//! # fn main() -> io::Result<()> {
//! use std::io::Read;
//! use std::mem::MaybeUninit;
//!
//! use uninit_buffers::SliceExt;
//!
//! let input = /* <omitted> */
//! # io::empty();
//! let mut buf = [const { MaybeUninit::uninit() }; 2048];
//!
//! let (read_data, _) = buf.try_write_iter_owned(input.bytes())?;
//!
//! println!("read {} bytes.", read_data.len());
//!
//! # Ok(())
//! # }
//! ```
//!
//! For more examples, see the documentation of the methods of the [`SliceExt`] trait.

use core::{
    borrow::{Borrow, BorrowMut},
    iter::FusedIterator,
    marker::PhantomData,
    mem::{MaybeUninit, forget, take, transmute},
    ops::{Deref, DerefMut},
    slice::IterMut,
};

/// This structure owns initialized data contained in a slice of
/// [`MaybeUninit`]. To obtain one, use the [`SliceExt`] trait, which is automatically
/// implemented on slices of [`MaybeUninit`].
///
/// Regarding safety: this object "owns" the initialized data, and will drop them
/// automatically.
#[derive(Debug)]
pub struct Initialized<'a, T> {
    // for this object to exist, all elements of data must be initialized.
    data: &'a mut [MaybeUninit<T>],
    _marker: PhantomData<T>,
}

type InitializedWithRemainder<'a, T> = (Initialized<'a, T>, &'a mut [MaybeUninit<T>]);

/// This trait implements methods to construct initialized data on a [`MaybeUninit`] buffer.
/// It mimics the (currently unstable) API in the [standard library](slice::write_copy_of_slice).
/// The implementation and documentation are near-identical copies for all but the
/// `try_write_iter_owned` method.
pub trait SliceExt {
    /// This is the item that may be uninitialized.
    type Item;

    /// Copies the elements from `src` to `self`, returning the [`Initialized`] structure
    /// which owns the now-initialized contents of `self`.
    ///
    /// If `T` does not implement `Copy`, use
    /// [`write_clone_of_slice_owned`](SliceExt::write_clone_of_slice_owned) instead.
    ///
    /// This is similar to [`slice::copy_from_slice`].
    ///
    /// # Panics
    /// This function will panic if the two slices have different lengths.
    ///
    /// # Examples
    /// ```
    /// use std::mem::MaybeUninit;
    /// use uninit_buffers::SliceExt;
    ///
    /// let mut dst = [MaybeUninit::uninit(); 32];
    /// let src = [0; 32];
    ///
    /// let init = dst.write_copy_of_slice_owned(&src);
    ///
    /// assert_eq!(*init, src);
    /// ```
    fn write_copy_of_slice_owned(&mut self, src: &[Self::Item]) -> Initialized<Self::Item>
    where
        Self::Item: Copy;

    /// Clones the elements from `src` to `self`, returning the [`Initialized`] structure
    /// which owns the now-initialized contents of `self`. Any already initialized items
    /// will not be dropped.
    ///
    /// If `T` implements `Copy`, use
    /// [`write_copy_of_slice_owned`](SliceExt::write_copy_of_slice_owned) instead.
    ///
    /// This is similar to [`slice::clone_from_slice`] but does not drop existing elements.
    ///
    /// # Panics
    /// This function will panic if the two slices have different lengths, or if the implementation
    /// of `Clone` panics.
    ///
    /// If there is a panic, the already cloned elements will be dropped.
    ///
    /// # Examples
    /// ```
    /// use std::mem::MaybeUninit;
    /// use uninit_buffers::SliceExt;
    ///
    /// let mut dst = [const { MaybeUninit::uninit() }; 5];
    /// let src = ["wibbly", "wobbly", "timey", "wimey", "stuff"].map(ToOwned::to_owned);
    ///
    /// let init = dst.write_clone_of_slice_owned(&src);
    ///
    /// assert_eq!(*init, src);
    /// ```
    fn write_clone_of_slice_owned(&mut self, src: &[Self::Item]) -> Initialized<Self::Item>
    where
        Self::Item: Clone;

    /// Fills a slice with elements by cloning `value`, returning a mutable reference to the now
    /// initialized contents of the slice. Any previously initialized elements will not be dropped.
    ///
    /// This is similar to [`slice::fill`].
    ///
    /// # Panics
    /// This function will panic if any call to `Clone` panics.
    ///
    /// If such a panic occurs, any elements previously initialized during this operation will be
    /// dropped.
    ///
    /// # Examples
    /// ```
    /// use std::mem::MaybeUninit;
    /// use uninit_buffers::SliceExt;
    ///
    /// let mut buf = [const { MaybeUninit::uninit() }; 10];
    /// let initialized = buf.write_filled_owned(1);
    /// assert_eq!(&*initialized, [1; 10].as_ref());
    /// ```
    fn write_filled_owned(&mut self, value: Self::Item) -> Initialized<Self::Item>
    where
        Self::Item: Clone;

    /// Fills a slice with elements returned by calling a closure for each index.
    ///
    /// This method uses a closure to create new values. If you'd rather `Clone` a given value, use
    /// [`MaybeUninit::fill`]. If you want to use the `Default` trait to generate values, you can
    /// pass [`|_| Default::default()`](Default::default) as the argument.
    ///
    /// # Panics
    /// This function will panic if any call to the provided closure panics.
    ///
    /// If such a panic occurs, any elements previously initialized during this operation will be
    /// dropped.
    ///
    /// # Examples
    /// ```
    /// use std::mem::MaybeUninit;
    /// use uninit_buffers::SliceExt;
    ///
    /// let mut buf = [const { MaybeUninit::<usize>::uninit() }; 5];
    /// let initialized = buf.write_with_owned(|idx| idx + 1);
    /// assert_eq!(&*initialized, &[1, 2, 3, 4, 5]);
    /// ```
    fn write_with_owned<F>(&mut self, f: F) -> Initialized<Self::Item>
    where
        F: FnMut(usize) -> Self::Item;

    /// Fills a slice with elements yielded by an iterator until either all elements have been
    /// initialized or the iterator is empty.
    ///
    /// Returns the owned initialized data in [`Initialized`] and the remainder in the second
    /// slice.
    ///
    /// # Panics
    /// This function panics if the iterator's `next` function panics.
    ///
    /// If such a panic occurs, any elements previously initialized during this operation will be
    /// dropped.
    ///
    /// # Examples
    /// Completely filling the slice:
    /// ```
    /// use std::mem::MaybeUninit;
    /// use uninit_buffers::SliceExt;
    ///
    /// let mut buf = [const { MaybeUninit::uninit() }; 5];
    ///
    /// let iter = [1, 2, 3].into_iter().cycle();
    /// let (initialized, remainder) = buf.write_iter_owned(iter);
    ///
    /// assert_eq!(&*initialized, &[1, 2, 3, 1, 2]);
    /// assert!(remainder.is_empty());
    /// ```
    /// Partially filling the slice:
    /// ```
    /// use std::mem::MaybeUninit;
    /// use uninit_buffers::SliceExt;
    ///
    /// let mut buf = [const { MaybeUninit::uninit() }; 5];
    /// let iter = [1, 2];
    /// let (initialized, remainder) = buf.write_iter_owned(iter);
    ///
    /// assert_eq!(&*initialized, &[1, 2]);
    /// assert_eq!(remainder.len(), 3);
    /// ```
    /// Checking an iterator after filling a slice:
    /// ```
    /// use std::mem::MaybeUninit;
    /// use uninit_buffers::SliceExt;
    ///
    /// let mut buf = [const { MaybeUninit::uninit() }; 3];
    /// let mut iter = [1, 2, 3, 4, 5].into_iter();
    /// let (initialized, remainder) = buf.write_iter_owned(iter.by_ref());
    ///
    /// assert_eq!(&*initialized, &[1, 2, 3]);
    /// assert!(remainder.is_empty());
    /// assert_eq!(iter.as_slice(), &[4, 5]);
    /// ```
    fn write_iter_owned<I>(&mut self, it: I) -> InitializedWithRemainder<Self::Item>
    where
        I: IntoIterator<Item = Self::Item>;

    /// Tries to fill a slice with elements yielded by an iterator until either all elements have
    /// been initialized or the iterator is empty.
    ///
    /// Returns the owned initialized data in [`Initialized`] and the remainder in the second
    /// slice.
    ///
    /// If the iterator at any point returns `Err`, the previously-consumed elements are dropped
    /// and the error is returned.
    ///
    /// # Panics
    /// This function panics if the iterator's `next` function panics.
    ///
    /// If such a panic occurs, any elements previously initialized during this operation will be
    /// dropped.
    ///
    /// # Examples
    // this is identical to the example in the crate documentation. do not run it.
    /// ```no_run
    /// # use std::io;
    /// # fn main() -> io::Result<()> {
    /// use std::io::Read;
    /// use std::mem::MaybeUninit;
    ///
    /// use uninit_buffers::SliceExt;
    ///
    /// let input = /* <omitted> */
    /// # io::empty();
    /// let mut buf = [const { MaybeUninit::uninit() }; 2048];
    ///
    /// let (read_data, _) = buf.try_write_iter_owned(input.bytes())?;
    ///
    /// println!("read {} bytes.", read_data.len());
    ///
    /// # Ok(())
    /// # }
    /// ```
    fn try_write_iter_owned<I, E>(
        &mut self,
        it: I,
    ) -> Result<InitializedWithRemainder<Self::Item>, E>
    where
        I: IntoIterator<Item = Result<Self::Item, E>>;
}

/// An iterator that moves out of [`Initialized`].
///
/// This `struct` is created by the `into_iter` method on [`Initialized`] (provided by the
/// [`IntoIterator`] trait).
#[derive(Debug, Default)]
pub struct IntoIter<'a, T> {
    iter: IterMut<'a, MaybeUninit<T>>,
    _marker: PhantomData<T>,
}

struct Guard<'a, T> {
    slice: &'a mut [MaybeUninit<T>],
    initialized: usize,
}

impl<T> Deref for Initialized<'_, T> {
    type Target = [T];

    fn deref(&self) -> &Self::Target {
        // SAFETY: all elements of self.data are already initialized, and this object owns them.
        unsafe { &*(self.data as *const [MaybeUninit<T>] as *const [T]) }
    }
}

impl<T> DerefMut for Initialized<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        // SAFETY: all elements of self.data are already initialized, and this object owns them.
        unsafe { &mut *(self.data as *mut [MaybeUninit<T>] as *mut [T]) }
    }
}

impl<'a, T> IntoIterator for Initialized<'a, T> {
    type Item = T;
    type IntoIter = IntoIter<'a, T>;

    fn into_iter(mut self) -> Self::IntoIter {
        let im = take(&mut self.data).iter_mut();
        forget(self);
        IntoIter {
            iter: im,
            _marker: PhantomData,
        }
    }
}

impl<T> Iterator for IntoIter<'_, T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|v| unsafe { v.assume_init_read() })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<T> DoubleEndedIterator for IntoIter<'_, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter
            .next_back()
            .map(|v| unsafe { v.assume_init_read() })
    }
}

impl<T> ExactSizeIterator for IntoIter<'_, T> {
    fn len(&self) -> usize {
        self.iter.len()
    }
}

impl<T> Drop for Initialized<'_, T> {
    fn drop(&mut self) {
        for v in self.data.iter_mut() {
            unsafe { v.assume_init_drop() }
        }
    }
}

impl<T> Drop for IntoIter<'_, T> {
    fn drop(&mut self) {
        for v in self.iter.by_ref() {
            unsafe { v.assume_init_drop() }
        }
    }
}

impl<T> SliceExt for [MaybeUninit<T>] {
    type Item = T;

    fn write_copy_of_slice_owned(&mut self, src: &[Self::Item]) -> Initialized<Self::Item>
    where
        Self::Item: Copy,
    {
        let uninit_src: &[MaybeUninit<T>] = unsafe { transmute(src) };

        self.copy_from_slice(uninit_src);

        Initialized {
            data: self,
            _marker: PhantomData,
        }
    }

    fn write_clone_of_slice_owned(&mut self, src: &[Self::Item]) -> Initialized<Self::Item>
    where
        Self::Item: Clone,
    {
        assert_eq!(
            self.len(),
            src.len(),
            "destination and source slices have different lengths"
        );

        let len = self.len();
        let src = &src[..len];

        let mut guard = Guard {
            slice: self,
            initialized: 0,
        };

        for (i, val) in src.iter().enumerate() {
            guard.slice[i].write(val.clone());
            guard.initialized += 1;
        }

        forget(guard);

        Initialized {
            data: self,
            _marker: PhantomData,
        }
    }

    #[doc(alias = "memset")]
    fn write_filled_owned(&mut self, value: Self::Item) -> Initialized<Self::Item>
    where
        Self::Item: Clone,
    {
        // oh to long for specialization
        let mut guard = Guard {
            slice: self,
            initialized: 0,
        };

        if let Some((last, elems)) = guard.slice.split_last_mut() {
            for el in elems {
                el.write(value.clone());
                guard.initialized += 1;
            }

            last.write(value);
        }

        forget(guard);

        Initialized {
            data: self,
            _marker: PhantomData,
        }
    }

    fn write_with_owned<F>(&mut self, mut f: F) -> Initialized<Self::Item>
    where
        F: FnMut(usize) -> Self::Item,
    {
        let mut guard = Guard {
            slice: self,
            initialized: 0,
        };

        for (idx, element) in guard.slice.iter_mut().enumerate() {
            element.write(f(idx));
            guard.initialized += 1;
        }

        forget(guard);

        Initialized {
            data: self,
            _marker: PhantomData,
        }
    }

    fn write_iter_owned<I>(
        &mut self,
        it: I,
    ) -> (Initialized<Self::Item>, &mut [MaybeUninit<Self::Item>])
    where
        I: IntoIterator<Item = Self::Item>,
    {
        let iter = it.into_iter();
        let mut guard = Guard {
            slice: self,
            initialized: 0,
        };

        for (element, val) in guard.slice.iter_mut().zip(iter) {
            element.write(val);
            guard.initialized += 1;
        }

        let initialized_len = guard.initialized;
        forget(guard);

        let (initted, remainder) = unsafe { self.split_at_mut_unchecked(initialized_len) };

        (
            Initialized {
                data: initted,
                _marker: PhantomData,
            },
            remainder,
        )
    }

    fn try_write_iter_owned<I, E>(
        &mut self,
        it: I,
    ) -> Result<(Initialized<Self::Item>, &mut [MaybeUninit<Self::Item>]), E>
    where
        I: IntoIterator<Item = Result<Self::Item, E>>,
    {
        let iter = it.into_iter();
        let mut guard = Guard {
            slice: self,
            initialized: 0,
        };

        for (element, val) in guard.slice.iter_mut().zip(iter) {
            element.write(val?);
            guard.initialized += 1;
        }

        let initialized_len = guard.initialized;
        forget(guard);

        let (initted, remainder) = unsafe { self.split_at_mut_unchecked(initialized_len) };

        Ok((
            Initialized {
                data: initted,
                _marker: PhantomData,
            },
            remainder,
        ))
    }
}

impl<T> Drop for Guard<'_, T> {
    fn drop(&mut self) {
        for v in self.slice[..self.initialized].iter_mut() {
            unsafe {
                v.assume_init_drop();
            }
        }
    }
}

impl<T> AsRef<[T]> for Initialized<'_, T> {
    fn as_ref(&self) -> &[T] {
        self.deref()
    }
}

impl<T> AsRef<[T]> for IntoIter<'_, T> {
    fn as_ref(&self) -> &[T] {
        unsafe { &*(self.iter.as_slice() as *const [MaybeUninit<T>] as *const [T]) }
    }
}

impl<T> AsMut<[T]> for Initialized<'_, T> {
    fn as_mut(&mut self) -> &mut [T] {
        self.deref_mut()
    }
}

impl<T> Borrow<[T]> for Initialized<'_, T> {
    fn borrow(&self) -> &[T] {
        self.deref()
    }
}

impl<T> BorrowMut<[T]> for Initialized<'_, T> {
    fn borrow_mut(&mut self) -> &mut [T] {
        self.deref_mut()
    }
}

unsafe impl<T: Send> Send for Initialized<'_, T> {}
unsafe impl<T: Send> Send for IntoIter<'_, T> {}

unsafe impl<T: Sync> Sync for Initialized<'_, T> {}
unsafe impl<T: Sync> Sync for IntoIter<'_, T> {}

impl<T> Default for Initialized<'_, T> {
    fn default() -> Self {
        Self {
            data: &mut [],
            _marker: PhantomData,
        }
    }
}

impl<T> FusedIterator for IntoIter<'_, T> {}

impl<T> IntoIter<'_, T> {
    /// Returns the remaining items of this iterator as a slice.
    /// # Example
    /// ```
    /// use std::mem::MaybeUninit;
    /// use uninit_buffers::SliceExt;
    ///
    /// let mut buf = [const { MaybeUninit::uninit() }; 3];
    /// let mut into_iter = buf.write_copy_of_slice_owned(&['a', 'b', 'c']).into_iter();
    /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
    /// let _ = into_iter.next().unwrap();
    /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
    /// ```
    pub fn as_slice(&self) -> &[T] {
        self.as_ref()
    }
}

#[cfg(test)]
mod tests {
    use core::cell::RefCell;
    use std::collections::HashSet;

    use super::*;

    #[derive(Debug)]
    struct DropKey<'a> {
        index: usize,
        set: &'a RefCell<HashSet<usize>>,
        inset: bool,
    }

    impl<'a> DropKey<'a> {
        fn new(index: usize, set: &'a RefCell<HashSet<usize>>) -> Self {
            assert!(
                set.borrow_mut().insert(index),
                "set already contains index {index}"
            );
            Self {
                index,
                set,
                inset: true,
            }
        }

        fn new_notinset(index: usize, set: &'a RefCell<HashSet<usize>>) -> Self {
            Self {
                index,
                set,
                inset: false,
            }
        }
    }

    impl<'a> Drop for DropKey<'a> {
        fn drop(&mut self) {
            if self.inset {
                assert!(
                    self.set.borrow_mut().remove(&self.index),
                    "set does not contain index {}",
                    self.index
                );
            }
        }
    }

    impl<'a> Clone for DropKey<'a> {
        fn clone(&self) -> Self {
            assert!(
                self.set.borrow_mut().insert(self.index),
                "set already contains index {}",
                self.index
            );
            Self {
                index: self.index,
                set: self.set,
                inset: true,
            }
        }
    }

    struct DropCount<'a> {
        count: &'a RefCell<usize>,
    }

    impl<'a> DropCount<'a> {
        fn new(count: &'a RefCell<usize>) -> Self {
            *count.borrow_mut() += 1;
            Self { count }
        }
    }

    impl<'a> Clone for DropCount<'a> {
        fn clone(&self) -> Self {
            Self::new(self.count)
        }
    }

    impl<'a> Drop for DropCount<'a> {
        fn drop(&mut self) {
            *self.count.borrow_mut() -= 1;
        }
    }

    impl<'a> PartialEq for DropKey<'a> {
        fn eq(&self, other: &Self) -> bool {
            self.index == other.index
        }
    }

    #[test]
    fn write_iter() {
        let set = RefCell::new(HashSet::new());
        const CAP: usize = 10;
        const NUM: usize = 5;
        let mut buf = [const { MaybeUninit::uninit() }; CAP];
        let (written, uninit) = buf.write_iter_owned((0..NUM).map(|v| DropKey::new(v, &set)));

        let setcmp = RefCell::new(HashSet::new());
        let expected = (0..NUM)
            .map(|v| DropKey::new(v, &setcmp))
            .collect::<Vec<_>>();

        assert_eq!(*written, *expected);
        assert_eq!(uninit.len(), CAP - NUM);

        for idx in 0..NUM {
            assert!(
                set.borrow().contains(&idx),
                "set does not contain index {idx}"
            );
        }

        drop(written);
        assert!(set.borrow().is_empty(), "set is empty after dropping");
    }

    #[test]
    fn write_with() {
        let set = RefCell::new(HashSet::new());
        const CAP: usize = 10;
        let mut buf = [const { MaybeUninit::uninit() }; CAP];
        let written = buf.write_with_owned(|i| DropKey::new(i, &set));

        let setcmp = RefCell::new(HashSet::new());
        let expected = (0..CAP)
            .map(|v| DropKey::new(v, &setcmp))
            .collect::<Vec<_>>();

        assert_eq!(*written, *expected);

        for idx in 0..CAP {
            assert!(
                set.borrow().contains(&idx),
                "set does not contain index {idx}"
            );
        }

        drop(written);
        assert!(set.borrow().is_empty(), "set is empty after dropping");
    }

    #[test]
    fn write_clone_of_slice() {
        let set = RefCell::new(HashSet::new());
        const CAP: usize = 10;
        let slc = (0..CAP)
            .map(|v| DropKey::new_notinset(v, &set))
            .collect::<Vec<_>>();
        let mut buf = [const { MaybeUninit::uninit() }; CAP];
        let written = buf.write_clone_of_slice_owned(&slc);

        assert_eq!(*written, *slc);

        for idx in 0..CAP {
            assert!(
                set.borrow().contains(&idx),
                "set does not contain index {idx}"
            );
        }

        drop(written);
        assert!(set.borrow().is_empty(), "set is empty after dropping");
    }

    #[test]
    fn write_copy_of_slice() {
        const CAP: usize = 10;
        let slc = (0..CAP).collect::<Vec<_>>();
        let mut buf = [const { MaybeUninit::uninit() }; CAP];
        let written = buf.write_copy_of_slice_owned(&slc);

        assert_eq!(*written, *slc);
    }

    #[test]
    fn write_filled() {
        const CAP: usize = 10;
        let count = RefCell::new(0);
        let mut buf = [const { MaybeUninit::uninit() }; CAP];
        let written = buf.write_filled_owned(DropCount::new(&count));
        assert_eq!(*count.borrow(), 10);
        drop(written);
        assert_eq!(*count.borrow(), 0);
    }

    #[test]
    fn test_into_iter() {
        let set = RefCell::new(HashSet::new());
        const CAP: usize = 10;
        let mut buf = [const { MaybeUninit::uninit() }; CAP];
        let mut iter = buf.write_with_owned(|i| DropKey::new(i, &set)).into_iter();
        assert_eq!(iter.len(), 10);

        const TAKE: usize = 5;
        iter.nth(TAKE - 1).unwrap();

        let borrow = set.borrow();
        for j in 0..TAKE {
            assert!(!borrow.contains(&j), "set contains index {j}");
        }
        for j in TAKE..CAP {
            assert!(borrow.contains(&j), "set does not contains index {j}");
        }
        drop(borrow);

        assert_eq!(iter.len(), 5);
        iter.next_back().unwrap();

        let borrow = set.borrow();
        for j in 0..TAKE {
            assert!(!borrow.contains(&j), "set contains index {j}");
        }
        for j in TAKE..(CAP - 1) {
            assert!(borrow.contains(&j), "set does not contains index {j}");
        }
        assert!(!borrow.contains(&CAP), "set contains index 9");
        drop(borrow);

        drop(iter);
        assert!(set.borrow().is_empty(), "set is not empty");
    }

    #[test]
    fn try_write_iter() {
        const CAP: usize = 10;
        let mut buf = [const { MaybeUninit::uninit() }; CAP];

        let first_batch = [Ok::<_, ()>(1), Ok(2), Ok(3), Ok(4)];
        let (initialized, remainder) = buf
            .try_write_iter_owned(first_batch.iter().cloned())
            .unwrap();
        let expected = first_batch
            .into_iter()
            .map(Result::unwrap)
            .collect::<Vec<_>>();
        assert_eq!(expected.as_slice(), &*initialized);
        assert_eq!(remainder.len(), 6);
        drop(initialized);

        let second_batch = [Ok(1), Ok(2), Err("err")];
        assert_eq!(buf.try_write_iter_owned(second_batch).unwrap_err(), "err");

        let third_batch = (0..CAP).map(Result::Ok).chain([Err("err")]);
        let (initialized, remainder) = buf.try_write_iter_owned(third_batch).unwrap();
        assert!(initialized.into_iter().eq(0..CAP));
        assert!(remainder.is_empty());
    }
}