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
#![feature(
ptr_metadata,
allocator_api,
unsize,
layout_for_ptr,
clone_to_uninit,
ptr_as_uninit,
non_null_from_ref,
maybe_uninit_write_slice
)]
#![cfg_attr(not(test), warn(clippy::unwrap_used, clippy::expect_used))]
#![cfg_attr(not(debug_assertions), warn(clippy::panic_in_result_fn))]
#![cfg_attr(not(feature = "std"), no_std)]
#![doc = include_str!("../README.md")]
#[cfg(feature = "alloc")]
mod alloc {
extern crate alloc;
pub use alloc::{alloc::Global, boxed::Box};
}
use core::{
alloc::Allocator,
clone::CloneToUninit,
fmt,
marker::{PhantomData, Unsize},
mem::{self, ManuallyDrop},
ptr::{self, NonNull, Pointee},
};
mod any;
mod array;
pub mod cursor;
pub mod iter;
mod node;
mod sized;
mod string;
use cursor::{Cursor, CursorMut};
use dynode::AllocateError;
#[cfg(feature = "alloc")]
use iter::IntoIterBoxed;
use iter::{Iter, IterMut};
pub use node::MaybeUninitNode;
use node::{Header, Node};
struct Ends<U>
where
U: ?Sized,
{
front: Node<U>,
back: Node<U>,
}
impl<U> Clone for Ends<U>
where
U: ?Sized,
{
fn clone(&self) -> Self {
*self
}
}
impl<U> Copy for Ends<U> where U: ?Sized {}
/// A doubly-linked list that allows nodes with dynamically sized types.
pub struct DynList<U, #[cfg(feature = "alloc")] A = alloc::Global, #[cfg(not(feature = "alloc"))] A>
where
U: ?Sized,
A: Allocator,
{
ends: Option<Ends<U>>,
allocator: A,
_phantom: PhantomData<U>,
}
impl<U, A> DynList<U, A>
where
U: ?Sized,
A: Allocator,
{
#[must_use]
#[inline]
/// Creates an empty [`DynList`] in the given allocator.
pub const fn new_in(allocator: A) -> Self {
Self {
ends: None,
allocator,
_phantom: PhantomData,
}
}
#[must_use]
/// Decomposes the [`DynList`] into pointers to the front and back (if not empty), and the allocator.
pub fn into_raw_parts(self) -> (Option<(NonNull<()>, NonNull<()>)>, A) {
let ends = self
.ends
.map(|Ends { front, back }| (front.value_ptr(), back.value_ptr()));
let allocator = {
let me = ManuallyDrop::new(self);
unsafe { ptr::read(&me.allocator) }
};
(ends, allocator)
}
#[must_use]
#[inline]
/// Creates a [`DynList`] from pointers to the front and back (if not empty), and an allocator.
///
/// # Safety
/// - If the `ends` are not [`None`], they must have come from a call to [`Self::into_raw_parts`] with a `U` with the same layout and invariants.
/// - `allocator` must be valid for the nodes in the list.
pub unsafe fn from_raw_parts(ends: Option<(NonNull<()>, NonNull<()>)>, allocator: A) -> Self {
let ends = ends.map(|(front, back)| Ends {
front: unsafe { Node::from_value_ptr(front) },
back: unsafe { Node::from_value_ptr(back) },
});
Self {
ends,
allocator,
_phantom: PhantomData,
}
}
/// Attempts to allocate an uninitialised node at the front of the list.
///
/// # Safety
/// The `metadata` must be valid under the safety conditions for [`Layout::for_value_raw`](core::alloc::Layout::for_value_raw).
///
/// # Errors
/// If allocation fails, this will return an [`AllocateError`].
pub unsafe fn try_allocate_uninit_front(
&mut self,
metadata: <U as Pointee>::Metadata,
) -> Result<MaybeUninitNode<U, A>, AllocateError> {
let header = Header {
next: self.ends.map(|Ends { front, .. }| front),
previous: None,
};
unsafe { node::try_new(self, metadata, header) }
}
/// Attempts to allocate an uninitialised node at the back of the list.
///
/// # Safety
/// The `metadata` must be valid under the safety conditions for [`Layout::for_value_raw`](core::alloc::Layout::for_value_raw).
///
/// # Errors
/// If allocation fails, this will return an [`AllocateError`].
pub unsafe fn try_allocate_uninit_back(
&mut self,
metadata: <U as Pointee>::Metadata,
) -> Result<MaybeUninitNode<U, A>, AllocateError> {
let header = Header {
next: None,
previous: self.ends.map(|Ends { back, .. }| back),
};
unsafe { node::try_new(self, metadata, header) }
}
#[must_use]
/// Allocates an uninitialised node at the front of the list.
///
/// # Safety
/// The `metadata` must be valid under the safety conditions for [`Layout::for_value_raw`](core::alloc::Layout::for_value_raw).
pub unsafe fn allocate_uninit_front(
&mut self,
metadata: <U as Pointee>::Metadata,
) -> MaybeUninitNode<U, A> {
AllocateError::unwrap_result(unsafe { self.try_allocate_uninit_front(metadata) })
}
#[must_use]
/// Allocates an uninitialised node at the back of the list.
///
/// # Safety
/// The `metadata` must be valid under the safety conditions for [`Layout::for_value_raw`](core::alloc::Layout::for_value_raw).
pub unsafe fn allocate_uninit_back(
&mut self,
metadata: <U as Pointee>::Metadata,
) -> MaybeUninitNode<U, A> {
AllocateError::unwrap_result(unsafe { self.try_allocate_uninit_back(metadata) })
}
/// Attempts to push `value` to the front of the list and unsize it to `U`.
///
/// # Errors
/// If allocation fails, this will return an [`AllocateError`].
pub fn try_push_front_unsize<T>(&mut self, value: T) -> Result<(), AllocateError<T>>
where
T: Unsize<U>,
{
let metadata = ptr::metadata(&value as &U);
let node = match unsafe { self.try_allocate_uninit_front(metadata) } {
Ok(node) => node,
Err(error) => return Err(error.with_value(value)),
};
unsafe { node.value_ptr().cast().write(value) };
unsafe { node.insert() };
Ok(())
}
/// Attempts to push `value` to the back of the list and unsize it to `U`.
///
/// # Errors
/// If allocation fails, this will return an [`AllocateError`].
pub fn try_push_back_unsize<T>(&mut self, value: T) -> Result<(), AllocateError<T>>
where
T: Unsize<U>,
{
let metadata = ptr::metadata(&value as &U);
let node = match unsafe { self.try_allocate_uninit_back(metadata) } {
Ok(node) => node,
Err(error) => return Err(error.with_value(value)),
};
unsafe { node.value_ptr().cast().write(value) };
unsafe { node.insert() };
Ok(())
}
/// Pushes `value` to the front of the list and unsizes it to `U`.
///
/// # Examples
/// ```
/// # use core::fmt::Debug;
/// # use dyn_list::DynList;
/// let mut list = DynList::<dyn Debug>::new();
/// list.push_front_unsize("Hello, World!");
/// ```
pub fn push_front_unsize<T>(&mut self, value: T)
where
T: Unsize<U>,
{
let metadata = ptr::metadata(&value as &U);
let node = unsafe { self.allocate_uninit_front(metadata) };
unsafe { node.value_ptr().cast().write(value) };
unsafe { node.insert() };
}
/// Pushes `value` to the back of the list and unsizes it to `U`.
///
/// # Examples
/// ```
/// # use core::fmt::Debug;
/// # use dyn_list::DynList;
/// let mut list = DynList::<dyn Debug>::new();
/// list.push_back_unsize("Hello, World!");
/// ```
pub fn push_back_unsize<T>(&mut self, value: T)
where
T: Unsize<U>,
{
let metadata = ptr::metadata(&value as &U);
let node = unsafe { self.allocate_uninit_back(metadata) };
unsafe { node.value_ptr().cast().write(value) };
unsafe { node.insert() };
}
#[must_use]
/// Gets a reference to the element at the front of the list.
///
/// If the list is empty, this returns [`None`].
pub fn front(&self) -> Option<&U> {
let Ends { front, .. } = self.ends?;
let ptr = unsafe { front.data_ptr() };
Some(unsafe { ptr.as_ref() })
}
#[must_use]
/// Gets a reference to the element at the back of the list.
///
/// If the list is empty, this returns [`None`].
pub fn back(&self) -> Option<&U> {
let Ends { back, .. } = self.ends?;
let ptr = unsafe { back.data_ptr() };
Some(unsafe { ptr.as_ref() })
}
#[must_use]
/// Gets a mutable reference to the element at the front of the list.
///
/// If the list is empty, this returns [`None`].
pub fn front_mut(&mut self) -> Option<&mut U> {
let Ends { front, .. } = self.ends?;
let mut ptr = unsafe { front.data_ptr() };
Some(unsafe { ptr.as_mut() })
}
#[must_use]
/// Gets a mutable reference to the element at the back of the list.
///
/// If the list is empty, this returns [`None`].
pub fn back_mut(&mut self) -> Option<&mut U> {
let Ends { back, .. } = self.ends?;
let mut ptr = unsafe { back.data_ptr() };
Some(unsafe { ptr.as_mut() })
}
#[must_use]
/// Removes the front node of the list.
/// If you do not want a [`MaybeUninitNode`], this is the wrong function!
pub fn pop_front_node(&mut self) -> Option<MaybeUninitNode<U, A>> {
let Ends { front, back } = self.ends.as_mut()?;
let node = *front;
let header = unsafe { node.header_ptr().as_ref() };
debug_assert!(header.previous.is_none());
if let Some(next) = header.next {
let next_header = unsafe { next.header_ptr().as_mut() };
debug_assert_eq!(next_header.previous, Some(node));
next_header.previous = header.previous;
*front = next;
} else {
debug_assert_eq!(*back, node);
self.ends = None;
}
Some(unsafe { dynode::new_maybe_uninit(self, node.into()) })
}
#[must_use]
/// Removes the back node of the list.
/// If you do not want a [`MaybeUninitNode`], this is the wrong function!
pub fn pop_back_node(&mut self) -> Option<MaybeUninitNode<U, A>> {
let Ends { front, back } = self.ends.as_mut()?;
let node = *back;
let header = unsafe { node.header_ptr().as_ref() };
debug_assert!(header.next.is_none());
if let Some(previous) = header.previous {
let previous_header = unsafe { previous.header_ptr().as_mut() };
debug_assert_eq!(previous_header.next, Some(node));
previous_header.next = header.next;
*back = previous;
} else {
debug_assert_eq!(*front, node);
self.ends = None;
}
Some(unsafe { dynode::new_maybe_uninit(self, node.into()) })
}
#[inline]
/// Deletes and drops the node at the front of the list.
///
/// Returns [`true`] if a node was removed and [`false`] if the list was empty.
///
/// # Examples
/// ```
/// # use core::fmt::Debug;
/// # use dyn_list::DynList;
/// let mut list = DynList::<dyn Debug>::new();
/// assert!(!list.delete_front());
///
/// list.push_back_unsize("Hello, World!");
/// assert!(list.delete_front());
/// ```
pub fn delete_front(&mut self) -> bool {
self.pop_front_node()
.map(|mut front| unsafe { front.drop_in_place() })
.is_some()
}
#[inline]
/// Deletes and drops the node at the back of the list.
///
/// Returns [`true`] if a node was removed and [`false`] if the list was empty.
///
/// # Examples
/// ```
/// # use core::fmt::Debug;
/// # use dyn_list::DynList;
/// let mut list = DynList::<dyn Debug>::new();
/// assert!(!list.delete_back());
///
/// list.push_back_unsize("Hello, World!");
/// assert!(list.delete_back());
/// ```
pub fn delete_back(&mut self) -> bool {
self.pop_back_node()
.map(|mut back| unsafe { back.drop_in_place() })
.is_some()
}
#[cfg(feature = "alloc")]
#[must_use]
#[inline]
/// Attempts to remove the front node and return it in a [`Box`].
///
/// # Errors
/// If allocation fails, this will return an [`AllocateError`].
/// The node will be deleted.
pub fn try_pop_front_boxed(&mut self) -> Option<Result<alloc::Box<U, A>, AllocateError>>
where
A: Clone,
{
self.pop_front_node().map(|front| {
unsafe { front.try_take_boxed() }.map_err(|error| {
let (front, error) = error.into_parts();
unsafe { front.insert() };
error
})
})
}
#[cfg(feature = "alloc")]
#[must_use]
#[inline]
/// Attempts to remove the back node and return it in a [`Box`].
///
/// # Errors
/// If allocation fails, this will return an [`AllocateError`].
/// The node will be deleted.
pub fn try_pop_back_boxed(&mut self) -> Option<Result<alloc::Box<U, A>, AllocateError>>
where
A: Clone,
{
self.pop_back_node().map(|front| {
unsafe { front.try_take_boxed() }.map_err(|error| {
let (front, error) = error.into_parts();
unsafe { front.insert() };
error
})
})
}
#[cfg(feature = "alloc")]
#[must_use]
#[inline]
/// Removes the front node and returns it in a [`Box`].
///
/// ```
/// # use core::cmp::PartialEq;
/// # use dyn_list::DynList;
/// let mut list = DynList::<dyn PartialEq<u8>>::new();
/// list.push_back_unsize(5);
/// assert!(&*list.pop_front_boxed().unwrap() == &5_u8);
/// ```
pub fn pop_front_boxed(&mut self) -> Option<alloc::Box<U, A>>
where
A: Clone,
{
self.try_pop_front_boxed().map(AllocateError::unwrap_result)
}
#[cfg(feature = "alloc")]
#[must_use]
#[inline]
/// Removes the back node and returns it in a [`Box`].
///
/// ```
/// # use core::cmp::PartialEq;
/// # use dyn_list::DynList;
/// let mut list = DynList::<dyn PartialEq<u8>>::new();
/// list.push_back_unsize(5);
/// assert!(&*list.pop_back_boxed().unwrap() == &5_u8);
/// ```
pub fn pop_back_boxed(&mut self) -> Option<alloc::Box<U, A>>
where
A: Clone,
{
self.try_pop_back_boxed().map(AllocateError::unwrap_result)
}
#[must_use]
#[inline]
/// Creates a [`Cursor`] at the front of the list.
///
/// If the list is empty, this will point to the "ghost" element.
pub const fn cursor_front(&self) -> Cursor<U, A> {
// Using match rather than map to allow function to be const
let current = match self.ends {
Some(Ends { front, .. }) => Some(front),
None => None,
};
Cursor {
current,
list: self,
}
}
#[must_use]
#[inline]
/// Creates a [`Cursor`] at the back of the list.
///
/// If the list is empty, this will point to the "ghost" element.
pub const fn cursor_back(&self) -> Cursor<U, A> {
// Using match rather than map to allow function to be const
let current = match self.ends {
Some(Ends { back, .. }) => Some(back),
None => None,
};
Cursor {
current,
list: self,
}
}
#[must_use]
#[inline]
/// Creates a [`CursorMut`] at the front of the list that can mutate the list.
///
/// If the list is empty, this will point to the "ghost" element.
pub const fn cursor_front_mut(&mut self) -> CursorMut<U, A> {
// Using match rather than map to allow function to be const
let current = match self.ends {
Some(Ends { front, .. }) => Some(front),
None => None,
};
CursorMut {
current,
list: self,
}
}
#[must_use]
#[inline]
/// Creates a [`CursorMut`] at the back of the list that can mutate the list.
///
/// If the list is empty, this will point to the "ghost" element.
pub const fn cursor_back_mut(&mut self) -> CursorMut<U, A> {
// Using match rather than map to allow function to be const
let current = match self.ends {
Some(Ends { back, .. }) => Some(back),
None => None,
};
CursorMut {
current,
list: self,
}
}
#[must_use]
#[inline]
/// Creates an iterator over references to the items in the list.
pub const fn iter(&self) -> Iter<U> {
Iter::new(self)
}
#[must_use]
#[inline]
/// Creates an iterator over mutable references to the items in the list.
pub const fn iter_mut(&mut self) -> IterMut<U> {
IterMut::new(self)
}
#[cfg(feature = "alloc")]
#[must_use]
#[inline]
/// Converts the list to an iterator that yields the elements in boxes.
pub const fn into_iter_boxed(self) -> IntoIterBoxed<U, A>
where
A: Clone,
{
IntoIterBoxed::new(self)
}
/// Attempts to clone the list into another allocator.
///
/// # Errors
/// If allocation fails, this will return an [`AllocateError`].
pub fn try_clone_in<A2>(&self, allocator: A2) -> Result<DynList<U, A2>, AllocateError>
where
U: CloneToUninit,
A2: Allocator,
{
let mut new_list = DynList::new_in(allocator);
for item in self {
let node = unsafe { new_list.try_allocate_uninit_back(ptr::metadata(item)) }?;
unsafe { item.clone_to_uninit(node.value_ptr().cast().as_ptr()) };
unsafe { node.insert() };
}
Ok(new_list)
}
#[must_use]
/// Clones the list into another allocator.
pub fn clone_in<A2>(&self, allocator: A2) -> DynList<U, A2>
where
U: CloneToUninit,
A2: Allocator,
{
AllocateError::unwrap_result(self.try_clone_in(allocator))
}
#[cfg(test)]
fn check_debug(&self) {
let Some(Ends { front, back }) = self.ends else {
return;
};
let mut forward_len: usize = 1;
let mut backward_len: usize = 1;
let mut node = front;
let mut header = unsafe { node.header_ptr().as_ref() };
while let Some(next) = header.next {
forward_len += 1;
let next_header = unsafe { next.header_ptr().as_ref() };
debug_assert_eq!(next_header.previous, Some(node));
node = next;
header = next_header;
}
assert_eq!(node.value_ptr(), back.value_ptr());
while let Some(previous) = header.previous {
backward_len += 1;
let previous_header = unsafe { previous.header_ptr().as_ref() };
debug_assert_eq!(previous_header.next, Some(node));
node = previous;
header = previous_header;
}
assert_eq!(node.value_ptr(), front.value_ptr());
assert_eq!(forward_len, backward_len);
}
}
#[cfg(feature = "alloc")]
impl<U> DynList<U>
where
U: ?Sized,
{
#[must_use]
#[inline]
/// Creates an empty [`DynList`].
pub const fn new() -> Self {
Self::new_in(alloc::Global)
}
}
#[cfg(feature = "alloc")]
impl<U> Default for DynList<U>
where
U: ?Sized,
{
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<U, A> Drop for DynList<U, A>
where
U: ?Sized,
A: Allocator,
{
fn drop(&mut self) {
// Based on https://doc.rust-lang.org/1.82.0/src/alloc/collections/linked_list.rs.html#1169-1186
struct DropGuard<'a, U: ?Sized, A: Allocator> {
list: &'a mut DynList<U, A>,
}
impl<U: ?Sized, A: Allocator> Drop for DropGuard<'_, U, A> {
// https://doc.rust-lang.org/1.82.0/src/alloc/collections/linked_list.rs.html#1175-1176
// Continue the same loop we do below. This only runs when a destructor has
// panicked. If another one panics this will abort.
fn drop(&mut self) {
while self.list.delete_front() {}
}
}
// https://doc.rust-lang.org/1.82.0/src/alloc/collections/linked_list.rs.html#1181
// Wrap self so that if a destructor panics, we can try to keep looping
let guard = DropGuard { list: self };
while guard.list.delete_front() {}
mem::forget(guard);
}
}
impl<U, A> Clone for DynList<U, A>
where
U: ?Sized + CloneToUninit,
A: Allocator + Clone,
{
fn clone(&self) -> Self {
let allocator = self.allocator.clone();
self.clone_in(allocator)
}
}
impl<U, A> fmt::Debug for DynList<U, A>
where
U: ?Sized + fmt::Debug,
A: Allocator,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
unsafe impl<U, A> Send for DynList<U, A>
where
U: ?Sized + Send,
A: Allocator + Send,
{
}
unsafe impl<U, A> Sync for DynList<U, A>
where
U: ?Sized + Sync,
A: Allocator + Sync,
{
}