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 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
#![deny(missing_docs)] /*! The `ArrayLinkedList` data structure combines the benefit of an array and a linked list. Every supported operation, which does not (re-)allocate the array, is done in *O*(1): * inserting elements at the front and back * popping element at the front or back * getting the element count * removing elements at an arbitrary index * inserting elements at an arbitrary index * replacing elements at an arbitrary index It's stored like an array, but contains some additional information. You would typically use it, where you need to be able to do multiple of the following tasks efficiently: * accessing single elements by index * adding and removing elements without changing order or indices * sorting elements without changing indices or moving the content around. # Order and indexing You might also use it as a more convenient version of a `Vec<Option<T>>`. When iterating over it, only the elements, which are `Some` are given to the user. And even the checks for `Some` are optimized away. So when it's likely, that most of the options of a large array are `None`, this might be a huge performance improvement. Another advantage over a `LinkedList` is the cache locality. Everything is laid out in a contiguous region of memory. Compared to a `Vec` on the other hand, it might be bad. The iteration does not necessarily take place in the same order. That's mostly a problem for large arrays. The iterator would jump back and forth in the array. In order to understand this type, it's necessary to know about the iteration order. There is a logical order, which is used by the iterators, or when doing anything with the first and last elements. You can think of it as the order of a linked list, which is just packed into an array here. And then there is indexing, which has nothing to do with the order of the linked list. The indices just return the array elements. ## Index Example So when adding an element to the linked array without specifying the index, you get the index, it was put to, as a result. The results are always added to the array in order, so the indices increase, no matter if you add the indices to the front or to the back: ``` use array_linked_list::ArrayLinkedList; let mut array = ArrayLinkedList::new(); assert_eq!(array.push_front(1), 0); assert_eq!(array.push_back(2), 1); assert_eq!(array.push_front(3), 2); assert_eq!(array.push_front(4), 3); assert_eq!(array.push_back(5), 4); ``` ## Order example When you just apped elements from the front or back, the indices even correlate to the order: ``` use array_linked_list::ArrayLinkedList; let mut array = ArrayLinkedList::new(); array.push_front(1); array.push_front(2); array.push_front(3); for (i, element) in array.iter().rev().enumerate() { assert_eq!(*element, array[i].unwrap()); } ``` ``` use array_linked_list::ArrayLinkedList; let mut array = ArrayLinkedList::new(); array.push_back(1); array.push_back(2); array.push_back(3); for (i, element) in array.iter().enumerate() { assert_eq!(*element, array[i].unwrap()); } ``` ## Iteration over unsorted lists In realistic cases, you need to store the indices somewhere else, if you need them. Alternatively, you can also use ``` use array_linked_list::ArrayLinkedList; let mut array = ArrayLinkedList::new(); array.push_back(1); array.push_front(2); array.push_front(3); array.push_back(4); array.push_front(5); for (index, element) in array.indexed().rev() { assert_eq!(*element, array[index].unwrap()); } ``` ## Conclusion Just remember, that indices and order are two different things, which don't correlate, and you should be safe. **/ use std::{ hint, mem, ops::{Index, IndexMut}, }; #[derive(Copy, Clone, Debug, PartialEq)] struct LinkedListNode<T> { next_index: usize, prev_index: usize, data: Option<T>, } impl<T> LinkedListNode<T> { fn new(prev_index: usize, next_index: usize, data: T) -> Self { Self { next_index, prev_index, data: Some(data), } } fn front(first_index: usize, data: T) -> Self { Self { next_index: first_index, prev_index: 0, data: Some(data), } } fn back(last_index: usize, data: T) -> Self { Self { next_index: 0, prev_index: last_index, data: Some(data), } } fn deleted(free_index: usize) -> Self { Self { next_index: free_index, prev_index: 0, data: None, } } } /// The `ArrayLinkedList` type, which combines the advantages of dynamic arrays and linked lists. #[derive(Clone, Debug, PartialEq)] pub struct ArrayLinkedList<T> { count: usize, first_index: usize, last_index: usize, free_index: usize, end_index: usize, elements: Vec<LinkedListNode<T>>, } impl<T> ArrayLinkedList<T> { /// Constructs a new, empty ArrayLinkedList<T>. /// /// The linked array will not allocate until elements are pushed onto it. pub fn new() -> Self { Self { count: 0, first_index: 0, last_index: 0, free_index: 0, end_index: 0, elements: Vec::new(), } } #[inline] fn fill_elements(&mut self, capacity: usize) { if capacity == 0 { return; } for i in 1..capacity { self.elements.push(LinkedListNode::deleted(i + 1)) } self.elements.push(LinkedListNode::deleted(0)); self.free_index = 1; self.end_index = capacity; } /// Constructs a new, empty `ArrayLinkedList<T>` with the specified capacity. /// /// The array will be able to hold exactly `capacity` elements without reallocating. // If `capacity` is 0, the vector will not allocate. pub fn with_capacity(capacity: usize) -> Self { let mut result = Self::new(); result.elements = Vec::with_capacity(capacity); result.fill_elements(capacity); result } fn insert_free_element(&mut self, element: LinkedListNode<T>) -> usize { if self.free_index == 0 { self.elements.push(element); self.elements.len() } else { let free_index = self.free_index; let recycle_element = &mut self.elements[free_index - 1]; self.free_index = recycle_element.next_index; *recycle_element = element; free_index } } /// Adds an element at the front of the array and returns its index. /// The indices are returned in a raising order, starting with zero. /// See the module description for more information. /// /// This operation should compute in *O*(1) time. /// /// # Examples /// /// ``` /// use array_linked_list::ArrayLinkedList; /// /// let mut array = ArrayLinkedList::new(); /// /// assert_eq!(array.push_front(2), 0); /// assert_eq!(array.front().unwrap(), &2); /// /// assert_eq!(array.push_front(1), 1); /// assert_eq!(array.front().unwrap(), &1); /// ``` pub fn push_front(&mut self, value: T) -> usize { let element = LinkedListNode::front(self.first_index, value); let next_index = self.insert_free_element(element); *self.prev_of_next(self.first_index, true) = next_index; self.first_index = next_index; self.count += 1; next_index - 1 } /// Adds an element at the back of the array and returns its index. /// The indices are returned in a raising order, starting with zero. /// See the module description for more information. /// /// This operation should compute in *O*(1) time. /// /// # Examples /// /// ``` /// use array_linked_list::ArrayLinkedList; /// /// let mut array = ArrayLinkedList::new(); /// /// assert_eq!(array.push_back(1), 0); /// assert_eq!(array.push_back(3), 1); /// assert_eq!(3, *array.back().unwrap()); /// ``` pub fn push_back(&mut self, value: T) -> usize { let element = LinkedListNode::back(self.last_index, value); let prev_index = self.insert_free_element(element); *self.next_of_prev(self.last_index, true) = prev_index; self.last_index = prev_index; self.count += 1; prev_index - 1 } fn insert_between(&mut self, prev_index: usize, next_index: usize, value: T) -> usize { let element = LinkedListNode::new(prev_index, next_index, value); let index = self.insert_free_element(element); *self.next_of_prev(prev_index, true) = index; *self.prev_of_next(next_index, true) = index; self.count += 1; index - 1 } /// Inserts an element after the element at the specified index. /// Returns the index of the inserted element on success. /// If no element was found at the specified index, `None` is returned. /// /// # Panics /// Panics if prev_index >= capacity /// /// # Examples /// /// ``` /// use array_linked_list::ArrayLinkedList; /// /// let mut array = ArrayLinkedList::new(); /// /// let first = array.push_back(1); /// let second = array.push_back(2); /// let third = array.push_back(3); /// /// array.insert_after(second, 100); /// /// assert_eq!(array.pop_front(), Some(1)); /// assert_eq!(array.pop_front(), Some(2)); /// assert_eq!(array.pop_front(), Some(100)); /// assert_eq!(array.pop_front(), Some(3)); /// assert_eq!(array.pop_front(), None); /// ``` pub fn insert_after(&mut self, prev_index: usize, value: T) -> Option<usize> { let LinkedListNode { next_index, data, .. } = &self.elements[prev_index]; if data.is_some() { let next_index = *next_index; Some(self.insert_between(prev_index + 1, next_index, value)) } else { None } } /// Inserts an element before the element at the specified index. /// Returns the index of the inserted element on success. /// If no element was found at the specified index, `None` is returned. /// /// # Panics /// Panics if next_index >= capacity /// /// # Examples /// /// ``` /// use array_linked_list::ArrayLinkedList; /// /// let mut array = ArrayLinkedList::new(); /// /// let first = array.push_back(1); /// let second = array.push_back(2); /// let third = array.push_back(3); /// /// array.insert_before(second, 100); /// /// assert_eq!(array.pop_front(), Some(1)); /// assert_eq!(array.pop_front(), Some(100)); /// assert_eq!(array.pop_front(), Some(2)); /// assert_eq!(array.pop_front(), Some(3)); /// assert_eq!(array.pop_front(), None); /// ``` pub fn insert_before(&mut self, next_index: usize, value: T) -> Option<usize> { let LinkedListNode { prev_index, data, .. } = &self.elements[next_index]; if data.is_some() { let prev_index = *prev_index; Some(self.insert_between(prev_index, next_index + 1, value)) } else { None } } #[inline] fn prev_of_next(&mut self, index: usize, active: bool) -> &mut usize { if index > 0 { &mut self.elements[index - 1].prev_index } else if active { &mut self.last_index } else { &mut self.end_index } } #[inline] fn next_of_prev(&mut self, index: usize, active: bool) -> &mut usize { if index > 0 { &mut self.elements[index - 1].next_index } else if active { &mut self.first_index } else { &mut self.free_index } } fn connect_indices(&mut self, prev_index: usize, next_index: usize, active: bool) { *self.prev_of_next(next_index, active) = prev_index; *self.next_of_prev(prev_index, active) = next_index; } /// Removes the element at the given index and returns it, or `None` if it is empty. /// The indices of other items are not changed. /// Indices, which have never been used (see `capacity`), will not be available, but panic instead. /// /// Indices are not the position they appear in, when iterating over them. /// So you can't use enumerate to get the index to delete. /// But the iteration order of the elements (in both directions) is preserved. /// See the module description for more information. /// /// This operation should compute in *O*(1) time. /// /// # Panics /// Panics if index >= capacity /// /// # Examples /// /// ``` /// use array_linked_list::ArrayLinkedList; /// /// let mut array = ArrayLinkedList::new(); /// /// let first = array.push_front(1); /// let second = array.push_back(2); /// let third = array.push_front(3); /// /// /// assert_eq!(array.len(), 3); /// /// assert_eq!(array.remove(second).unwrap(), 2); /// assert_eq!(array[second], None); /// assert_eq!(array.len(), 2); /// assert_eq!(array.remove(second), None); /// assert_eq!(array.len(), 2); /// /// assert_eq!(array.remove(first).unwrap(), 1); /// assert_eq!(array.len(), 1); /// assert_eq!(array.remove(third).unwrap(), 3); /// assert_eq!(array.len(), 0); /// assert!(array.is_empty()); /// ``` pub fn remove(&mut self, index: usize) -> Option<T> { let LinkedListNode { next_index, prev_index, data, } = mem::replace( &mut self.elements[index], LinkedListNode::deleted(self.free_index), ); let removed = data.is_some(); self.connect_indices(prev_index, next_index, removed); if removed { self.count -= 1; } if self.free_index > 0 { self.elements[self.free_index - 1].prev_index = index + 1; } self.free_index = index + 1; data } /// Adds element at specified index at the front of the list. /// Useful for updating contents. /// /// It basically does the same as `remove` and `push_back`, even if the specified index is already removed. /// /// # Panics /// Panics if index >= capacity /// /// # Examples /// /// ``` /// use array_linked_list::ArrayLinkedList; /// /// let mut array = ArrayLinkedList::new(); /// /// array.push_front(1); /// let first_index = array.push_back(2); /// array.push_front(3); /// let second_index = array.push_front(4); /// array.push_back(5); /// /// let mut array2 = array.clone(); /// assert_eq!(array, array2); /// /// let first_element = array.replace_front(first_index, 100); /// let first_element2 = array2.remove(first_index); /// array2.push_front(100); /// assert_eq!(first_element, first_element2); /// assert_eq!(array, array2); /// /// let second_element = array.replace_front(first_index, 0); /// let second_element2 = array2.remove(first_index); /// array2.push_back(0); /// assert_eq!(second_element, second_element2); /// assert_ne!(array, array2); /// /// assert_eq!(array.len(), 5); /// assert_eq!(array2.len(), 5); /// ``` pub fn replace_front(&mut self, index: usize, value: T) -> Option<T> { let LinkedListNode { next_index, prev_index, data, } = mem::replace( &mut self.elements[index], LinkedListNode::front(self.first_index, value), ); let removed = data.is_some(); self.connect_indices(prev_index, next_index, removed); if !removed { self.count += 1; } if self.first_index > 0 { self.elements[self.first_index - 1].prev_index = index + 1; } self.first_index = index + 1; data } /// Adds element at specified index at the front of the list. /// Useful for updating contents. /// /// It basically does the same as `remove` and `push_back`, even if the specified index is already removed. /// /// # Panics /// Panics if index >= capacity /// /// # Examples /// /// ``` /// use array_linked_list::ArrayLinkedList; /// /// let mut array = ArrayLinkedList::new(); /// /// array.push_front(1); /// array.push_back(2); /// let middle_index = array.push_back(3); /// array.push_front(4); /// array.push_back(5); /// /// let mut array2 = array.clone(); /// assert_eq!(array, array2); /// /// let element = array.replace_back(middle_index, 100); /// let element2 = array2.remove(middle_index); /// array2.push_back(100); /// assert_eq!(element, element2); /// assert_eq!(array, array2); /// /// assert_eq!(array.len(), 5); /// assert_eq!(array2.len(), 5); /// ``` pub fn replace_back(&mut self, index: usize, value: T) -> Option<T> { let LinkedListNode { next_index, prev_index, data, } = mem::replace( &mut self.elements[index], LinkedListNode::back(self.last_index, value), ); let removed = data.is_some(); self.connect_indices(prev_index, next_index, removed); if !removed { self.count += 1; } if self.last_index > 0 { self.elements[self.last_index - 1].next_index = index + 1; } self.last_index = index + 1; data } /// Removes the first element from the array and returns it, or `None` if it is empty. /// /// This operation should compute in *O*(1) time. /// /// # Examples /// /// ``` /// use array_linked_list::ArrayLinkedList; /// /// let mut array = ArrayLinkedList::new(); /// assert_eq!(array.pop_front(), None); /// array.push_back(1); /// array.push_back(3); /// assert_eq!(array.pop_front(), Some(1)); /// ``` pub fn pop_front(&mut self) -> Option<T> { if self.first_index == 0 { return None; } let index = self.first_index - 1; let LinkedListNode { next_index, data, .. } = mem::replace( &mut self.elements[index], LinkedListNode::deleted(self.free_index), ); *self.prev_of_next(next_index, true) = 0; self.first_index = next_index; self.count -= 1; if self.free_index > 0 { self.elements[self.free_index - 1].prev_index = index; } self.free_index = index; Some(data.unwrap_or_else(|| unsafe { hint::unreachable_unchecked() })) } /// Removes the last element from the array and returns it, or `None` if it is empty. /// /// This operation should compute in *O*(1) time. /// /// # Examples /// /// ``` /// use array_linked_list::ArrayLinkedList; /// /// let mut array = ArrayLinkedList::new(); /// assert_eq!(array.pop_back(), None); /// array.push_back(1); /// array.push_back(3); /// assert_eq!(array.pop_back(), Some(3)); /// ``` pub fn pop_back(&mut self) -> Option<T> { if self.last_index == 0 { return None; } let index = self.last_index - 1; let LinkedListNode { prev_index, data, .. } = mem::replace( &mut self.elements[index], LinkedListNode::deleted(self.free_index), ); self.last_index = prev_index; *self.next_of_prev(prev_index, true) = 0; self.count -= 1; if self.free_index > 0 { self.elements[self.free_index - 1].prev_index = index; } self.free_index = index; Some(data.unwrap_or_else(|| unsafe { hint::unreachable_unchecked() })) } /// The index of the first list element. /// Returns `None` if array is empty. pub fn front_index(&self) -> Option<usize> { if self.first_index > 0 { Some(self.first_index - 1) } else { None } } /// The index of the last list element. /// Returns `None` if array is empty. pub fn back_index(&self) -> Option<usize> { if self.last_index > 0 { Some(self.last_index - 1) } else { None } } /// The first list element. /// Returns `None` if array is empty. pub fn front(&self) -> Option<&T> { if self.first_index > 0 { Some( self.elements[self.first_index - 1] .data .as_ref() .unwrap_or_else(|| unsafe { hint::unreachable_unchecked() }), ) } else { None } } /// The last list element. /// Returns `None` if array is empty. pub fn back(&self) -> Option<&T> { if self.last_index > 0 { Some( self.elements[self.last_index - 1] .data .as_ref() .unwrap_or_else(|| unsafe { hint::unreachable_unchecked() }), ) } else { None } } /// The first list element as a mutable reference. /// Returns `None` if array is empty. pub fn front_mut(&mut self) -> Option<&mut T> { if self.first_index > 0 { Some( self.elements[self.first_index - 1] .data .as_mut() .unwrap_or_else(|| unsafe { hint::unreachable_unchecked() }), ) } else { None } } /// The last list element as a mutable reference. /// Returns `None` if array is empty. pub fn back_mut(&mut self) -> Option<&mut T> { if self.last_index > 0 { Some( self.elements[self.last_index - 1] .data .as_mut() .unwrap_or_else(|| unsafe { hint::unreachable_unchecked() }), ) } else { None } } /// Checks if the list is empty. pub fn is_empty(&self) -> bool { self.first_index == 0 && self.last_index == 0 } /// Clears the linked array, removing all values. /// /// Note that this method has no effect on the allocated capacity of the array. /// So all indices, which have already been used (see `capacity`), are still available. pub fn clear(&mut self) { self.count = 0; self.first_index = 0; self.last_index = 0; self.free_index = 0; self.end_index = 0; let capacity = self.elements.len(); self.elements.clear(); self.fill_elements(capacity); } /// Returns the number of elements in the linked array. pub fn len(&self) -> usize { self.count } /// Returns the number of elements the vector can hold without reallocating. /// /// Methods, which take indices, require the specified index to be below the capacity. /// /// All the following methods require indices: /// /// * `insert_before` /// * `insert_after` /// * `remove` /// * `replace_front` /// * `replace_back` /// /// Besides that, some of the iterators are constructed using indices in the same range. pub fn capacity(&self) -> usize { self.elements.len() } /// Returns a borrowing iterator over its elements. pub fn iter<'a>(&'a self) -> impl Iterator<Item = &'a T> + DoubleEndedIterator { Values(Indexed::new(self)) } /// Returns a borrowing iterator over its indexed elements. pub fn indexed<'a>(&'a self) -> impl Iterator<Item = (usize, &'a T)> + DoubleEndedIterator { Indexed::new(self) } /// Returns a borrowing iterator over its indices. pub fn indices<'a>(&'a self) -> impl Iterator<Item = usize> + DoubleEndedIterator + 'a { Indices(Indexed::new(self)) } /// Returns a borrowing iterator over its elements, starting after the element at the specified index. /// /// # Panics /// Panics if index >= capacity pub fn iter_after<'a>( &'a self, index: usize, ) -> impl Iterator<Item = &'a T> + DoubleEndedIterator { Values(Indexed::after(self, index)) } /// Returns a borrowing iterator over its indexed elements, starting after the element at the specified index. /// /// # Panics /// Panics if index >= capacity pub fn indexed_after<'a>( &'a self, index: usize, ) -> impl Iterator<Item = (usize, &'a T)> + DoubleEndedIterator { Indexed::after(self, index) } /// Returns a borrowing iterator over its indices, starting after the element at the specified index. /// /// # Panics /// Panics if index >= capacity pub fn indices_after<'a>( &'a self, index: usize, ) -> impl Iterator<Item = usize> + DoubleEndedIterator + 'a { Indices(Indexed::after(self, index)) } /// Returns a borrowing iterator over its elements, ending before the element at the specified index. /// /// # Panics /// Panics if index >= capacity pub fn iter_before<'a>( &'a self, index: usize, ) -> impl Iterator<Item = &'a T> + DoubleEndedIterator { Values(Indexed::before(self, index)) } /// Returns a borrowing iterator over its indexed elements, ending before the element at the specified index. /// /// # Panics /// Panics if index >= capacity pub fn indexed_before<'a>( &'a self, index: usize, ) -> impl Iterator<Item = (usize, &'a T)> + DoubleEndedIterator { Indexed::before(self, index) } /// Returns a borrowing iterator over its indices, ending before the element at the specified index. /// /// # Panics /// Panics if index >= capacity pub fn indices_before<'a>( &'a self, index: usize, ) -> impl Iterator<Item = usize> + DoubleEndedIterator + 'a { Indices(Indexed::before(self, index)) } /// Returns an owning iterator returning its indexed elements. pub fn into_indexed(self) -> impl Iterator<Item = (usize, T)> + DoubleEndedIterator { IntoIndexed(self) } /// Returns an owning iterator returning its indices. pub fn into_indices(self) -> impl Iterator<Item = usize> + DoubleEndedIterator { IntoIndices(IntoIndexed(self)) } } impl<T> Index<usize> for ArrayLinkedList<T> { type Output = Option<T>; fn index(&self, index: usize) -> &Option<T> { &self.elements[index].data } } impl<T> IndexMut<usize> for ArrayLinkedList<T> { fn index_mut(&mut self, index: usize) -> &mut Option<T> { &mut self.elements[index].data } } struct Indexed<'a, T> { front_index: usize, back_index: usize, array: &'a ArrayLinkedList<T>, } impl<'a, T> Indexed<'a, T> { fn empty(array: &'a ArrayLinkedList<T>) -> Self { Self { front_index: 0, back_index: 0, array, } } fn new(array: &'a ArrayLinkedList<T>) -> Self { Self { front_index: array.first_index, back_index: array.last_index, array, } } fn after(array: &'a ArrayLinkedList<T>, prev_index: usize) -> Self { let element = &array.elements[prev_index]; if element.data.is_some() { Self { front_index: element.next_index, back_index: array.last_index, array, } } else { Self::empty(array) } } fn before(array: &'a ArrayLinkedList<T>, next_index: usize) -> Self { let element = &array.elements[next_index]; if element.data.is_some() { Self { front_index: array.first_index, back_index: element.prev_index, array, } } else { Self::empty(array) } } } struct Indices<'a, T>(Indexed<'a, T>); /// Borrowing iterator over values of the linked array. pub struct Values<'a, T>(Indexed<'a, T>); impl<'a, T> Iterator for Indexed<'a, T> { type Item = (usize, &'a T); #[inline] fn next(&mut self) -> Option<Self::Item> { if self.front_index > 0 { let index = self.front_index - 1; let element = &self.array.elements[index]; if self.front_index == self.back_index { self.front_index = 0; self.back_index = 0; } else { self.front_index = element.next_index; } Some(( index, element .data .as_ref() .unwrap_or_else(|| unsafe { hint::unreachable_unchecked() }), )) } else { None } } } impl<'a, T> DoubleEndedIterator for Indexed<'a, T> { #[inline] fn next_back(&mut self) -> Option<Self::Item> { if self.back_index > 0 { let index = self.back_index - 1; let element = &self.array.elements[index]; if self.front_index == self.back_index { self.front_index = 0; self.back_index = 0; } else { self.back_index = element.prev_index; } Some(( index, element .data .as_ref() .unwrap_or_else(|| unsafe { hint::unreachable_unchecked() }), )) } else { None } } } impl<'a, T> Iterator for Indices<'a, T> { type Item = usize; fn next(&mut self) -> Option<Self::Item> { if let Some((index, _)) = self.0.next() { Some(index) } else { None } } } impl<'a, T> DoubleEndedIterator for Indices<'a, T> { fn next_back(&mut self) -> Option<Self::Item> { if let Some((index, _)) = self.0.next_back() { Some(index) } else { None } } } impl<'a, T> Iterator for Values<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { if let Some((_, value)) = self.0.next() { Some(value) } else { None } } } impl<'a, T> DoubleEndedIterator for Values<'a, T> { fn next_back(&mut self) -> Option<Self::Item> { if let Some((_, value)) = self.0.next_back() { Some(value) } else { None } } } impl<'a, T> IntoIterator for &'a ArrayLinkedList<T> { type Item = &'a T; type IntoIter = Values<'a, T>; #[inline] fn into_iter(self) -> Self::IntoIter { Values(Indexed::new(self)) } } struct IntoIndexed<T>(ArrayLinkedList<T>); struct IntoIndices<T>(IntoIndexed<T>); /// Owning iterator over values of the linked array. pub struct IntoValues<T>(IntoIndexed<T>); impl<T> Iterator for IntoIndexed<T> { type Item = (usize, T); #[inline] fn next(&mut self) -> Option<Self::Item> { if self.0.first_index > 0 { let index = self.0.first_index - 1; let element = &mut self.0.elements[index]; if self.0.first_index == self.0.last_index { self.0.first_index = 0; self.0.last_index = 0; } else { self.0.first_index = element.next_index; } Some(( index, element .data .take() .unwrap_or_else(|| unsafe { hint::unreachable_unchecked() }), )) } else { None } } } impl<T> DoubleEndedIterator for IntoIndexed<T> { fn next_back(&mut self) -> Option<Self::Item> { if self.0.first_index > 0 { let index = self.0.first_index - 1; let element = &mut self.0.elements[index]; if self.0.first_index == self.0.last_index { self.0.first_index = 0; self.0.last_index = 0; } else { self.0.first_index = element.next_index; } Some(( index, element .data .take() .unwrap_or_else(|| unsafe { hint::unreachable_unchecked() }), )) } else { None } } } impl<T> Iterator for IntoIndices<T> { type Item = usize; fn next(&mut self) -> Option<Self::Item> { if let Some((index, _)) = self.0.next() { Some(index) } else { None } } } impl<T> DoubleEndedIterator for IntoIndices<T> { fn next_back(&mut self) -> Option<Self::Item> { if let Some((index, _)) = self.0.next_back() { Some(index) } else { None } } } impl<T> Iterator for IntoValues<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { if let Some((_, value)) = self.0.next() { Some(value) } else { None } } } impl<T> DoubleEndedIterator for IntoValues<T> { fn next_back(&mut self) -> Option<Self::Item> { if let Some((_, value)) = self.0.next_back() { Some(value) } else { None } } } impl<T> IntoIterator for ArrayLinkedList<T> { type Item = T; type IntoIter = IntoValues<T>; fn into_iter(self) -> Self::IntoIter { IntoValues(IntoIndexed(self)) } }