Skip to main content

trait_obj_list/iters/
into_ptrs_iter.rs

1use crate::DynList;
2use crate::ptr;
3use crate::types::ListType;
4
5/// Iterator that transfers ownership of items by yielding pointers to them.
6///
7/// The pointers are valid until the `IntoPtrsIter` structure is dropped, at
8/// which point they are all deallocated.
9///
10/// Yielded pointers will not have their contents dropped, so it is safe to
11/// move the data out of them. Any remaining unyielded pointers will have their
12/// contents dropped once the iterator is dropped.
13pub struct IntoPtrsIter<T, Typ>
14where
15	T: ptr::Pointee<Metadata = ptr::DynMetadata<T>> + ?Sized,
16	Typ: ListType<T>,
17{
18	pub(crate) list: DynList<T, Typ>,
19	pub(crate) offset: usize,
20	pub(crate) index: usize,
21}
22impl<T, Typ> Iterator for IntoPtrsIter<T, Typ>
23where
24	T: ptr::Pointee<Metadata = ptr::DynMetadata<T>> + ?Sized,
25	Typ: ListType<T>,
26{
27	type Item = *mut T;
28
29	fn next(&mut self) -> Option<Self::Item> {
30		if self.offset >= self.list.end {
31			return None;
32		}
33		let (p, size) = unsafe {
34			self.list
35				.typ
36				.read_entry(self.list.data.as_ptr(), self.offset, self.index)
37		};
38		self.offset += size;
39		self.index += 1;
40		Some(p)
41	}
42
43	fn size_hint(&self) -> (usize, Option<usize>) {
44		let n = self.list.typ.num_items() - self.index;
45		(n, Some(n))
46	}
47}
48impl<T, Typ> ExactSizeIterator for IntoPtrsIter<T, Typ>
49where
50	T: ptr::Pointee<Metadata = ptr::DynMetadata<T>> + ?Sized,
51	Typ: ListType<T>,
52{
53}
54impl<T, Typ> core::ops::Drop for IntoPtrsIter<T, Typ>
55where
56	T: ptr::Pointee<Metadata = ptr::DynMetadata<T>> + ?Sized,
57	Typ: ListType<T>,
58{
59	fn drop(&mut self) {
60		unsafe {
61			while self.offset < self.list.end {
62				let (p, size) =
63					self.list
64						.typ
65						.read_entry(self.list.data.as_ptr(), self.offset, self.index);
66				core::ptr::drop_in_place(p);
67				self.offset += size;
68				self.index += 1;
69			}
70			self.list.realloc_to(0);
71			self.list.end = 0;
72			self.list.capacity = 0;
73		}
74	}
75}