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
use super::{helper_traits::HasDoublyEnds, List};
use crate::{
type_aliases::{DoublyIdx, BACK_IDX, FRONT_IDX},
variant::Doubly,
ListSliceMut,
};
use core::ops::RangeBounds;
use orx_selfref_col::{MemoryPolicy, NodeIdx, Refs};
impl<T, M> List<Doubly<T>, M>
where
M: MemoryPolicy<Doubly<T>>,
{
/// ***O(1)*** Sets value of `front` of the list as `new_front` and:
/// * returns value of the front element;
/// * returns None if the list was empty.
///
/// # Examples
///
/// ```rust
/// use orx_linked_list::*;
///
/// let mut list = DoublyList::new();
///
/// assert_eq!(0, list.len());
///
/// let prior_front = list.swap_front('a');
/// assert!(prior_front.is_none());
/// assert_eq!(Some(&'a'), list.front());
///
/// let prior_front = list.swap_front('z');
/// assert_eq!(Some('a'), prior_front);
/// assert_eq!(Some(&'z'), list.front());
/// ```
pub fn swap_front(&mut self, new_front: T) -> Option<T> {
match self.0.ends().get(FRONT_IDX) {
Some(p) => Some(self.0.swap_data(&p, new_front)),
None => {
self.push_front(new_front);
None
}
}
}
/// ***O(1)*** Sets value of `back` of the list as `new_back` and:
/// * returns value of the back element;
/// * returns None if the list was empty.
///
/// # Examples
///
/// ```rust
/// use orx_linked_list::*;
///
/// let mut list = DoublyList::new();
///
/// assert_eq!(0, list.len());
///
/// let prior_back = list.swap_back('a');
/// assert!(prior_back.is_none());
/// assert_eq!(Some(&'a'), list.back());
///
/// let prior_back = list.swap_back('z');
/// assert_eq!(Some('a'), prior_back);
/// assert_eq!(Some(&'z'), list.back());
/// ```
pub fn swap_back(&mut self, new_back: T) -> Option<T> {
match self.0.ends().get(BACK_IDX) {
Some(p) => Some(self.0.swap_data(&p, new_back)),
None => {
self.push_back(new_back);
None
}
}
}
/// ***O(1)*** Pushes the `value` to the `front` of the list.
///
/// # Examples
///
/// ```rust
/// use orx_linked_list::*;
///
/// let mut list = DoublyList::new();
///
/// list.push_front('a');
/// list.push_front('b');
///
/// assert_eq!(Some(&'b'), list.front());
/// assert_eq!(Some(&'a'), list.back());
///
/// let popped = list.pop_front();
/// assert_eq!(Some('b'), popped);
/// ```
pub fn push_front(&mut self, value: T) -> DoublyIdx<T> {
let idx = self.0.push(value);
match self.0.ends().get(FRONT_IDX) {
Some(front) => {
self.0.node_mut(&front).prev_mut().set_some(&idx);
self.0.node_mut(&idx).next_mut().set_some(&front);
self.0.ends_mut().set_some(FRONT_IDX, &idx);
}
None => {
self.0.ends_mut().set_some(FRONT_IDX, &idx);
self.0.ends_mut().set_some(BACK_IDX, &idx);
}
}
NodeIdx::new(self.0.memory_state(), &idx)
}
/// ***O(1)*** Pushes the `value` to the `back` of the list.
///
/// # Examples
///
/// ```rust
/// use orx_linked_list::*;
///
/// let mut list = DoublyList::new();
///
/// list.push_back('a');
/// list.push_back('b');
///
/// assert_eq!(Some(&'b'), list.back());
/// assert_eq!(Some(&'a'), list.front());
///
/// let popped = list.pop_back();
/// assert_eq!(Some('b'), popped);
/// ```
pub fn push_back(&mut self, value: T) -> DoublyIdx<T> {
let idx = self.0.push(value);
match self.0.ends().get(BACK_IDX) {
Some(back) => {
self.0.node_mut(&back).next_mut().set_some(&idx);
self.0.node_mut(&idx).prev_mut().set_some(&back);
self.0.ends_mut().set_some(BACK_IDX, &idx);
}
None => {
self.0.ends_mut().set_some(FRONT_IDX, &idx);
self.0.ends_mut().set_some(BACK_IDX, &idx);
}
}
NodeIdx::new(self.0.memory_state(), &idx)
}
/// ***O(1)*** Pops and returns the value at the `front` of the list; returns None if the list is empty.
///
/// # Examples
///
/// ```rust
/// use orx_linked_list::*;
///
/// let mut list = DoublyList::new();
///
/// let popped = list.pop_front();
/// assert!(popped.is_none());
///
/// list.push_front('a');
/// assert_eq!(Some(&'a'), list.front());
///
/// let popped = list.pop_front();
/// assert_eq!(Some('a'), popped);
/// assert!(list.is_empty());
/// ```
pub fn pop_front(&mut self) -> Option<T> {
self.0.ends().get(FRONT_IDX).map(|front| {
match self.0.node(&front).next().get() {
Some(new_front) => {
self.0.node_mut(&new_front).prev_mut().clear();
self.0.ends_mut().set_some(FRONT_IDX, &new_front);
}
None => self.0.ends_mut().clear(),
}
self.0.close_and_reclaim(&front)
})
}
/// ***O(1)*** Pops and returns the value at the `back` of the list; returns None if the list is empty.
///
/// # Examples
///
/// ```rust
/// use orx_linked_list::*;
///
/// let mut list = DoublyList::new();
///
/// let popped = list.pop_back();
/// assert!(popped.is_none());
///
/// list.push_front('a');
/// assert_eq!(Some(&'a'), list.front());
///
/// let popped = list.pop_back();
/// assert_eq!(Some('a'), popped);
/// assert!(list.is_empty());
/// ```
pub fn pop_back(&mut self) -> Option<T> {
self.0.ends().get(BACK_IDX).map(|back| {
match self.0.node(&back).prev().get() {
Some(new_back) => {
self.0.node_mut(&new_back).next_mut().clear();
self.0.ends_mut().set_some(BACK_IDX, &new_back);
}
None => self.0.ends_mut().clear(),
}
self.0.close_and_reclaim(&back)
})
}
/// ***O(1)*** Appends the `other` list to the `front` of this list.
///
/// Time complexity:
/// * ***O(1)*** gets `front` of this list, say a,
/// * ***O(1)*** gets `back` of the other list, say b,
/// * ***O(1)*** connects `b -> a`.
///
/// # Examples
///
/// ```rust
/// use orx_linked_list::*;
///
/// let mut list = DoublyList::new();
/// list.push_front('b');
/// list.push_front('a');
/// list.push_back('c');
///
/// let other = DoublyList::from_iter(['d', 'e'].into_iter());
///
/// list.append_front(other);
/// assert!(list.eq_to_iter_vals(['d', 'e', 'a', 'b', 'c']));
/// ```
#[allow(clippy::missing_panics_doc)]
pub fn append_front<M2: MemoryPolicy<Doubly<T>>>(&mut self, other: List<Doubly<T>, M2>) {
let (col, other_state) = other.0.into_inner();
let (nodes, ends, _len) = col.into_inner();
self.0.append_nodes(nodes);
let old_front_exists = !self.0.ends().is_empty();
let new_front_exists = !ends.is_empty();
match (old_front_exists, new_front_exists) {
(_, false) => { /* no update when new is empty */ }
(false, true) => {
let new_front = ends.get(FRONT_IDX).expect("exists");
self.0.ends_mut().set_some(FRONT_IDX, &new_front);
}
(true, true) => {
let new_front = ends.get(FRONT_IDX).expect("exists");
let new_back = ends.get(BACK_IDX).expect("exists");
let old_front = self.0.ends().get(FRONT_IDX).expect("exists");
self.0.node_mut(&old_front).prev_mut().set_some(&new_back);
self.0.node_mut(&new_back).next_mut().set_some(&old_front);
self.0.ends_mut().set_some(FRONT_IDX, &new_front);
}
}
// update state if necessary
if other_state != self.memory_state() {
self.0.update_state(true);
while self.memory_state() == other_state {
self.0.update_state(true);
}
}
}
/// ***O(1)*** Appends the `other` list to the `back` of this list.
///
/// Time complexity:
/// * ***O(1)*** gets `back` of this list, say a,
/// * ***O(1)*** gets `front` of the other list, say b,
/// * ***O(1)*** connects `a -> b`.
///
/// # Examples
///
/// ```rust
/// use orx_linked_list::*;
///
/// let mut list = DoublyList::new();
/// list.push_front('b');
/// list.push_front('a');
/// list.push_back('c');
///
/// let other = DoublyList::from_iter(['d', 'e'].into_iter());
///
/// list.append_back(other);
/// assert!(list.eq_to_iter_vals(['a', 'b', 'c', 'd', 'e']));
/// ```
#[allow(clippy::missing_panics_doc)]
pub fn append_back<M2: MemoryPolicy<Doubly<T>>>(&mut self, other: List<Doubly<T>, M2>) {
let (col, other_state) = other.0.into_inner();
let (nodes, ends, _len) = col.into_inner();
self.0.append_nodes(nodes);
let old_back_exists = !self.0.ends().is_empty();
let new_back_exists = !ends.is_empty();
match (old_back_exists, new_back_exists) {
(_, false) => { /* no update when new is empty */ }
(false, true) => {
let new_back = ends.get(BACK_IDX).expect("exists");
self.0.ends_mut().set_some(BACK_IDX, &new_back);
}
(true, true) => {
let new_front = ends.get(FRONT_IDX).expect("exists");
let new_back = ends.get(BACK_IDX).expect("exists");
let old_back = self.0.ends().get(BACK_IDX).expect("exists");
self.0.node_mut(&old_back).next_mut().set_some(&new_front);
self.0.node_mut(&new_front).prev_mut().set_some(&old_back);
self.0.ends_mut().set_some(BACK_IDX, &new_back);
}
}
// update state if necessary
if other_state != self.memory_state() {
self.0.update_state(true);
while self.memory_state() == other_state {
self.0.update_state(true);
}
}
}
/// Creates and returns a slice of the list between the given `range` of indices.
///
/// Note that a linked list slice itself also behaves like a linked list,
/// reflecting the recursive nature of the data type.
/// However, it does not own the data.
/// It is rather a view, like a slice is a view to a vec.
///
/// Note that slicing might be useful in various ways.
/// For instance, we can keep indices of several critical elements of the list.
/// We can then get all elements before, after or between any pair of these indices.
/// Or we can combine the list with an indices vector, which provides the linked list
/// a vec-like usage
/// * with the disadvantage of using more memory, and
/// * with the advantage of constant time insertions, removals or moves.
///
/// # Panics
///
/// Panics if any of indices of the range bounds is invalid.
///
/// # Example
///
/// ```rust
/// use orx_linked_list::*;
///
/// let mut list = DoublyList::new();
///
/// list.push_back(3);
/// list.push_front(1);
/// list.push_front(7);
/// list.push_back(4);
/// list.push_front(9);
///
/// let expected_values = vec![9, 7, 1, 3, 4];
///
/// assert!(list.eq_to_iter_refs(&expected_values));
/// assert!(list.slice(..).eq_to_iter_refs(&expected_values));
///
/// let idx: Vec<_> = list.indices().collect();
///
/// let slice = list.slice(&idx[1]..=&idx[3]);
/// assert_eq!(slice.front(), Some(&7));
/// assert_eq!(slice.back(), Some(&3));
/// assert!(slice.eq_to_iter_vals([7, 1, 3]));
///
/// let sum: usize = slice.iter().sum();
/// assert_eq!(sum, 11);
/// ```
///
/// Note that the linked list and its slices are directed.
/// In other words, it does not by default have a cyclic behavior.
/// Therefore, if the end of the `range` is before the beginning,
/// the slice will stop at the `back` of the list.
/// See the following example for clarification.
///
/// Currently, cyclic or ring behavior can be achieved by `ring_iter` method.
///
/// ```rust
/// use orx_linked_list::*;
///
/// let mut list: DoublyList<_> = (0..10).collect();
/// let idx: Vec<_> = list.indices().collect();
///
/// // a..b where b comes later, hence, we get the slice a..b
/// let slice = list.slice_mut(&idx[1]..&idx[4]);
/// assert!(slice.eq_to_iter_vals([1, 2, 3]));
///
/// // a..b where b comes earlier, then, we get the slice a..back
/// let slice = list.slice_mut(&idx[4]..&idx[1]);
/// assert!(slice.eq_to_iter_vals([4, 5, 6, 7, 8, 9]));
/// ```
pub fn slice_mut<'a, R>(&mut self, range: R) -> ListSliceMut<Doubly<T>, M>
where
R: RangeBounds<&'a DoublyIdx<T>>,
T: 'a,
{
let ends = self.slice_ends(range).expect("invalid indices in range");
ListSliceMut { list: self, ends }
}
}