stack_stack/lib.rs
1#![doc = include_str!("../README.md")]
2#![no_std]
3
4use core::iter::*;
5use core::mem::*;
6use core::ops::*;
7use core::slice::*;
8use core::borrow::*;
9use core::hash::*;
10use core::ptr::copy_nonoverlapping;
11use core::fmt::{Debug, Formatter, Result as FmtResult};
12
13///
14/// Utility macro for creating a stack from values
15///
16/// # Panics
17/// Panics if the capacity provided is less than the quantity of values
18///
19/// # Examples
20///
21/// ```rust
22/// # use stack_stack::{Stack, stack};
23/// let s1 = stack![6,2,8,3,1; 10];
24/// assert_eq!(s1, [6,2,8,3,1]);
25/// assert_eq!(s1.capacity(), 10);
26///
27/// let s2 = stack![3; 4; 5];
28/// assert_eq!(s2, [3,3,3,3]);
29/// assert_eq!(s2.capacity(), 5);
30///
31/// ```
32///
33#[macro_export]
34macro_rules! stack {
35
36 ($elem:expr; $n:expr; $cap:expr) => {
37 {
38 let mut stack = Stack::with_capacity::<$cap>();
39 stack.resize($n, $elem);
40 stack
41 }
42 };
43
44 ($($x:expr),+ $(,)?; $cap:expr) => {
45 {
46 let vals = [$($x),*];
47 let mut stack = Stack::with_capacity::<$cap>();
48 if stack.extend_from_slice(&vals).is_err() {
49 panic!(
50 "Attempted to create a stack of len {}, but the capacity was {}",
51 vals.len(), $cap
52 )
53 }
54 stack
55 }
56 }
57
58}
59
60///
61/// A basic fixed-capacity stack stored statically
62///
63/// The design of its methods is based pretty closely on `Vec`, with
64/// the primary difference being that [`push`](Self::push()) returns an [`Option`]
65/// containing the pushed value if `self` is at capacity.
66///
67pub struct Stack<T, const N:usize> {
68 len: usize,
69 data: [MaybeUninit<T>; N]
70}
71
72impl<T:Clone, const N:usize> Clone for Stack<T, N> {
73 fn clone(&self) -> Self {
74 let mut new = Stack::new();
75 while new.len() < self.len() {
76 new.push(self[new.len()].clone()).ok();
77 }
78 new
79 }
80}
81
82impl<T, const N:usize> Drop for Stack<T, N> {
83 fn drop(&mut self) {
84 self.clear();
85 }
86}
87
88impl<T, const N:usize> Deref for Stack<T,N> {
89 type Target = [T];
90 fn deref(&self) -> &[T] {
91 self.as_slice()
92 }
93}
94
95impl<T, const N:usize> DerefMut for Stack<T,N> {
96 fn deref_mut(&mut self) -> &mut [T] {
97 self.as_mut_slice()
98 }
99}
100
101impl<T, const N:usize> Default for Stack<T,N> {
102 fn default() -> Self { Self::new() }
103}
104
105impl<T, const N:usize> From<[T;N]> for Stack<T,N> {
106 fn from(array: [T;N]) -> Self { Self::from_array(array) }
107}
108
109impl<T, const N:usize> AsRef<[T]> for Stack<T,N> {
110 fn as_ref(&self) -> &[T] { self.as_slice() }
111}
112
113impl<T, const N:usize> AsMut<[T]> for Stack<T,N> {
114 fn as_mut(&mut self) -> &mut [T] { self.as_mut_slice() }
115}
116
117impl<T, const N:usize> Borrow<[T]> for Stack<T,N> {
118 fn borrow(&self) -> &[T] { self.as_slice() }
119}
120
121impl<T, const N:usize> BorrowMut<[T]> for Stack<T,N> {
122 fn borrow_mut(&mut self) -> &mut [T] { self.as_mut_slice() }
123}
124
125impl<T, I:SliceIndex<[T]>, const N:usize> Index<I> for Stack<T,N> {
126 type Output = I::Output;
127 fn index(&self, i:I) -> &Self::Output {
128 &self.as_slice()[i]
129 }
130}
131
132impl<T, I:SliceIndex<[T]>, const N:usize> IndexMut<I> for Stack<T,N> {
133 fn index_mut(&mut self, i:I) -> &mut Self::Output {
134 &mut self.as_mut_slice()[i]
135 }
136}
137
138impl<T:Eq, const N:usize> Eq for Stack<T,N> {}
139
140impl<T:PartialEq<U>, U, const N:usize, const M:usize> PartialEq<Stack<U,M>> for Stack<T,N> {
141 fn eq(&self, other: &Stack<U,M>) -> bool { self.as_slice().eq(other.as_slice()) }
142 fn ne(&self, other: &Stack<U,M>) -> bool { self.as_slice().ne(other.as_slice()) }
143}
144
145impl<T:PartialEq<U>, U, const N:usize, const M:usize> PartialEq<[U;M]> for Stack<T,N> {
146 fn eq(&self, other: &[U;M]) -> bool { self.as_slice().eq(other) }
147 fn ne(&self, other: &[U;M]) -> bool { self.as_slice().ne(other) }
148}
149
150impl<T:PartialEq<U>, U, const N:usize, const M:usize> PartialEq<Stack<U,M>> for [T;N] {
151 fn eq(&self, other: &Stack<U,M>) -> bool { self.eq(other.as_slice()) }
152 fn ne(&self, other: &Stack<U,M>) -> bool { self.ne(other.as_slice()) }
153}
154
155impl<T:PartialEq<U>, U, const N:usize> PartialEq<[U]> for Stack<T,N> {
156 fn eq(&self, other: &[U]) -> bool { self.as_slice().eq(other) }
157 fn ne(&self, other: &[U]) -> bool { self.as_slice().ne(other) }
158}
159
160impl<T:PartialEq<U>, U, const N:usize> PartialEq<&[U]> for Stack<T,N> {
161 fn eq(&self, other: &&[U]) -> bool { self.as_slice().eq(*other) }
162 fn ne(&self, other: &&[U]) -> bool { self.as_slice().ne(*other) }
163}
164
165impl<T:PartialEq<U>, U, const N:usize> PartialEq<&mut [U]> for Stack<T,N> {
166 fn eq(&self, other: &&mut [U]) -> bool { self.as_slice().eq(*other) }
167 fn ne(&self, other: &&mut [U]) -> bool { self.as_slice().ne(*other) }
168}
169
170impl<T:PartialEq<U>, U, const N:usize> PartialEq<Stack<U,N>> for [T] {
171 fn eq(&self, other: &Stack<U,N>) -> bool { self.eq(other.as_slice()) }
172 fn ne(&self, other: &Stack<U,N>) -> bool { self.ne(other.as_slice()) }
173}
174
175impl<T:PartialEq<U>, U, const N:usize> PartialEq<Stack<U,N>> for &[T] {
176 fn eq(&self, other: &Stack<U,N>) -> bool { (**self).eq(other) }
177 fn ne(&self, other: &Stack<U,N>) -> bool { (**self).ne(other) }
178}
179
180impl<T:PartialEq<U>, U, const N:usize> PartialEq<Stack<U,N>> for &mut[T] {
181 fn eq(&self, other: &Stack<U,N>) -> bool { (**self).eq(other) }
182 fn ne(&self, other: &Stack<U,N>) -> bool { (**self).ne(other) }
183}
184
185impl<T:Hash, const N:usize> Hash for Stack<T,N> {
186 fn hash<H: Hasher>(&self, state: &mut H) {
187 self.as_slice().hash(state);
188 }
189}
190
191impl<T:Debug, const N:usize> Debug for Stack<T,N> {
192 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
193 Debug::fmt(self.as_slice(), f)
194 }
195}
196
197impl<T> Stack<T, 0> {
198
199
200 ///
201 /// Creates a stack with a given capacity
202 ///
203 /// ```
204 /// # use stack_stack::Stack;
205 /// let mut s = Stack::with_capacity::<2>();
206 /// assert_eq!(s.len(), 0);
207 /// assert_eq!(s.capacity(), 2);
208 ///
209 /// assert!(!s.is_full());
210 /// s.push(1);
211 /// assert!(!s.is_full());
212 /// s.push(2);
213 /// assert!(s.is_full());
214 ///
215 /// ```
216 ///
217 pub const fn with_capacity<const N:usize>() -> Stack<T,N> {
218 Stack::new()
219 }
220}
221
222impl<T, const N:usize> Stack<T, N> {
223
224 ///
225 /// Creates an empty stack
226 ///
227 /// Tends to be more clunky to use than [`Self::with_capacity()`], as type
228 /// annotations are usually required in order to specify the capacity
229 ///
230 /// # Examples
231 /// ```
232 /// # use stack_stack::Stack;
233 /// let mut stack: Stack<i32, 10> = Stack::new();
234 /// ```
235 ///
236 pub const fn new() -> Self {
237 Self { len: 0, data: unsafe { MaybeUninit::uninit().assume_init() } }
238 }
239
240 ///
241 /// Creates a stack and fills it with the values of an array
242 ///
243 /// Note that this will set the capacity to the size of the array,
244 /// and thus the stack will be completely full once initialized
245 ///
246 /// # Examples
247 /// ```
248 /// # use stack_stack::Stack;
249 /// let mut s = Stack::from_array([6,2,8]);
250 /// assert_eq!(s, [6,2,8]);
251 ///
252 /// //the stack starts out full
253 /// assert_eq!(s.len(), s.capacity());
254 /// assert!(s.is_full());
255 /// ```
256 ///
257 pub fn from_array(array: [T;N]) -> Self {
258 Self { len:array.len(), data: array.map(|t| MaybeUninit::new(t)) }
259 }
260
261 ///
262 /// Creates a stack and initializes it to the values of an array up to the given length
263 ///
264 /// Useful for initializing a stack with values while still leaving some capacity
265 ///
266 /// # Panics
267 /// Panics if the length is greater than the size of the array
268 ///
269 /// # Examples
270 /// ```
271 /// # use stack_stack::Stack;
272 /// let s = Stack::using_array([6,2,8,3,1], 3);
273 /// assert_eq!(s, [6,2,8]);
274 /// assert_eq!(s.capacity(), 5);
275 /// ```
276 ///
277 pub fn using_array(array: [T;N], len: usize) -> Self {
278 if len > N {
279 panic!("Attempted to create stack with len {len}, but the capacity was {N}");
280 }
281 unsafe { Self::using_array_unchecked(array, len) }
282 }
283
284 ///
285 /// Same as [`Self::using_array()`] but doesn't check if `len` is greater than `N`
286 ///
287 /// # Safety
288 /// Caller must guarrantee that `len` is less than or equal to `N`
289 ///
290 pub unsafe fn using_array_unchecked(array: [T;N], len: usize) -> Self {
291 let mut array = Self::from_array(array);
292 array.truncate(len);
293 array
294 }
295
296 ///
297 /// Constructs a `Stack` using the given buffer and sets the length directly
298 ///
299 /// # Safety
300 /// Caller must guarrantee that the first `len` values in `buf` are properly
301 /// initialized and that `len` is less than or equal to `N`
302 ///
303 /// # Examples
304 /// ```
305 /// # use stack_stack::Stack;
306 /// use core::mem::MaybeUninit;
307 ///
308 /// let s = unsafe {
309 /// Stack::from_raw_parts(
310 /// [MaybeUninit::new(6), MaybeUninit::new(2), MaybeUninit::new(8),
311 /// MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit()], 3
312 /// )
313 /// };
314 ///
315 /// assert_eq!(s, [6,2,8]);
316 /// assert_eq!(s.capacity(), 6);
317 /// ```
318 ///
319 pub const unsafe fn from_raw_parts(buf: [MaybeUninit<T>; N], len: usize) -> Self {
320 Self { len, data: buf }
321 }
322
323 /// The quantity of values in the stack
324 pub const fn len(&self) -> usize { self.len }
325
326 /// The total quantity of values that this stack can hold.
327 /// Equivalent to `N`
328 pub const fn capacity(&self) -> usize { N }
329
330 /// `true` when this stack contains no elements
331 pub const fn is_empty(&self) -> bool { self.len() == 0 }
332
333 /// `true` when this stack contains as many elements as the capacity
334 pub const fn is_full(&self) -> bool { self.len() >= self.capacity() }
335
336 /// Returns a pointer to the data in the stack
337 pub const fn as_ptr(&self) -> *const T { self.data.as_ptr() as *const _ }
338
339 /// Returns a mutable pointer to the data in the stack
340 pub fn as_mut_ptr(&mut self) -> *mut T { self.data.as_mut_ptr() as *mut _ }
341
342 /// Returns a slice of the data in the stac
343 pub const fn as_slice(&self) -> &[T] {
344 unsafe { from_raw_parts(self.data.as_ptr() as *const _, self.len) }
345 }
346
347 /// Returns a mutable slice of the data in the stack
348 pub fn as_mut_slice(&mut self) -> &mut [T] {
349 unsafe { from_raw_parts_mut(self.data.as_mut_ptr() as *mut _, self.len) }
350 }
351
352 ///
353 /// Inserts an element to the end of the stack
354 ///
355 /// If this stack is full, it returns the function argument in a `Some()`
356 /// value and leaves the stack unchanged
357 ///
358 /// # Examples
359 /// ```
360 /// # use stack_stack::Stack;
361 /// let mut s = Stack::with_capacity::<3>();
362 ///
363 /// assert_eq!(s.push(6), Ok(()));
364 /// assert_eq!(s.push(2), Ok(()));
365 /// assert_eq!(s.push(8), Ok(()));
366 /// assert_eq!(s, [6, 2, 8]);
367 ///
368 /// assert_eq!(s.push(3), Err(3));
369 /// assert_eq!(s.push(1), Err(1));
370 /// assert_eq!(s, [6, 2, 8])
371 /// ```
372 ///
373 /// If confident that there will be no overflow, the `#[must_use]` warnings
374 /// can be ergonomically ignored by postfixing [`Result::ok()`]
375 ///
376 /// ```
377 /// # use stack_stack::Stack;
378 /// let mut s = Stack::with_capacity::<3>();
379 /// s.push(6).ok();
380 /// s.push(2).ok();
381 /// s.push(8).ok();
382 /// assert_eq!(s, [6, 2, 8]);
383 /// ```
384 ///
385 ///
386 pub fn push(&mut self, x:T) -> Result<(),T> {
387 if self.is_full() { return Err(x); }
388 self.data[self.len] = MaybeUninit::new(x);
389 self.len += 1;
390 Ok(())
391 }
392
393 ///
394 /// Removes the last element from the stack and returns it
395 ///
396 /// If this stack is empty, `None` is returned instead
397 ///
398 /// # Examples
399 /// ```
400 /// # use stack_stack::{Stack, stack};
401 /// let mut s = stack![6,2,8; 3];
402 ///
403 /// assert_eq!(s.pop(), Some(8));
404 /// assert_eq!(s, [6, 2]);
405 ///
406 /// assert_eq!(s.pop(), Some(2));
407 /// assert_eq!(s.pop(), Some(6));
408 /// assert_eq!(s.pop(), None);
409 ///
410 /// assert_eq!(s, []);
411 ///
412 /// ```
413 ///
414 pub fn pop(&mut self) -> Option<T> {
415 if self.is_empty() { return None; }
416 self.len -= 1;
417 unsafe { Some(self.data[self.len].assume_init_read()) }
418 }
419
420 ///
421 /// Copies the contents of this stack into another stack of a different
422 /// capacity
423 ///
424 /// If the new capacity is larger, then the resulting stack should
425 /// be equal to this one except with extra storage space.
426 ///
427 /// If the new capacity is smaller, then items will be truncated from
428 /// the end to fit the new size
429 ///
430 /// # Examples
431 /// ```
432 /// # use stack_stack::{Stack, stack};
433 /// let s1 = stack![6, 2, 8; 3];
434 /// let s2 = s1.clone().resize_capacity::<10>();
435 ///
436 /// assert_eq!(s1, s2);
437 /// assert_eq!(s1.capacity(), 3);
438 /// assert_eq!(s2.capacity(), 10);
439 ///
440 /// let s3 = s1.clone().resize_capacity::<2>();
441 /// assert_ne!(s1, s3);
442 /// assert_eq!(s3, [6, 2]);
443 /// assert_eq!(s3.capacity(), 2);
444 ///
445 /// ```
446 ///
447 pub fn resize_capacity<const M: usize>(self) -> Stack<T,M> {
448 let mut new = Stack::new();
449 for x in self {
450 if new.push(x).is_err() { break; } //stop early if M < N
451 }
452 new
453 }
454
455 // pub fn into_vec() ->
456 // pub fn into_boxed_slice()
457
458 ///
459 /// Removes all elements after the given length
460 ///
461 /// If `len` is greater than `Self::len()`, then the stack remains unchanged
462 ///
463 /// # Examples
464 /// ```
465 /// # use stack_stack::{Stack, stack};
466 /// let mut s1 = stack![6, 2, 8, 3, 1; 5];
467 /// s1.truncate(3);
468 /// assert_eq!(s1, [6, 2, 8]);
469 /// ```
470 ///
471 pub fn truncate(&mut self, len: usize) {
472 let target = self.len().min(len);
473 if needs_drop::<T>() {
474 while self.len() > target { self.pop(); }
475 } else {
476 unsafe { self.set_len(target) }
477 }
478 }
479
480 ///
481 /// Directly sets the length of the stack without changing the backing array
482 ///
483 /// # Safety
484 /// Caller must guarrantee the following:
485 /// - `len` is no greater than the capacity
486 /// - if `len` is larger than the current length, that any new elements are
487 /// properly initialized
488 /// - if `len` is smaller than the current length, that all elements after
489 /// the new length are either properly dropped or that leaks are acceptable
490 ///
491 /// # Examples
492 /// Useful to read data in from FFI apis. See `Vec::set_len()` for
493 /// examples
494 ///
495 pub unsafe fn set_len(&mut self, len: usize) {
496 self.len = len;
497 }
498
499 fn check_bounds(&self, index: usize, op:&str) {
500 //TODO: fill in error message
501 if index >= self.len() {
502 panic!("Attempted to {op} item at {index}, but the len was {}", self.len());
503 }
504 }
505
506 fn check_capacity(&self, size: usize, op:&str) {
507 if size > self.capacity() {
508 panic!("Attempted to {op} to {size}, but the capacity is {}", self.capacity())
509 }
510 }
511
512 ///
513 /// Quickly removes and returns the element at `index` by swapping it with
514 /// the last element in the stack
515 ///
516 /// This operation is quick and O(1), as it does not need to shift over any
517 /// other elements. However, it does change the ordering of the stack which
518 /// may be unacceptable for some applications.
519 ///
520 /// # Examples
521 /// ```
522 /// # use stack_stack::{Stack, stack};
523 /// let mut s1 = stack![1, 2, 3, 4, 5; 5];
524 /// s1.swap_remove(1);
525 /// assert_eq!(s1, [1, 5, 3, 4]);
526 /// ```
527 ///
528 pub fn swap_remove(&mut self, index: usize) -> T {
529 self.check_bounds(index, "remove");
530 unsafe {
531 let ret = self.data[index].assume_init_read();
532 self.len -= 1;
533 copy_nonoverlapping(
534 self.data[self.len].as_ptr(),
535 self.data[index].as_mut_ptr(),
536 1
537 );
538 ret
539 }
540 }
541
542 ///
543 /// Adds an element to the stack at an index
544 ///
545 /// If the stack is full, then the value is still inserted, but the last
546 /// element of the stack is removed and returned.
547 ///
548 /// # Examples
549 /// ```
550 /// # use stack_stack::{Stack, stack};
551 /// let mut s1 = stack![1, 2, 3, 4, 5; 6];
552 ///
553 /// s1.insert(2, 10);
554 /// assert_eq!(s1, [1, 2, 10, 3, 4, 5]);
555 ///
556 /// assert_eq!(s1.insert(2, 10), Some(5));
557 /// assert_eq!(s1, [1, 2, 10, 10, 3, 4]);
558 ///
559 /// ```
560 ///
561 pub fn insert(&mut self, index: usize, element: T) -> Option<T> {
562 self.check_bounds(index, "insert");
563 let mut temp = MaybeUninit::new(element);
564 for i in index..self.len() {
565 swap(&mut self.data[i], &mut temp);
566 }
567
568 if self.is_full() {
569 //return the overflow
570 Some(unsafe { temp.assume_init() })
571 } else {
572 self.data[self.len] = temp;
573 self.len += 1;
574 None
575 }
576
577 }
578
579 ///
580 /// Removes and returns the element at a given index
581 ///
582 /// # Panics
583 /// Panics if the index is greater than the size of the stack
584 ///
585 /// # Examples
586 /// ```
587 /// # use stack_stack::{Stack, stack};
588 /// let mut s1 = stack![1, 2, 3, 4, 5; 5];
589 /// assert_eq!(s1.remove(2), 3);
590 /// assert_eq!(s1, [1, 2, 4, 5]);
591 /// ```
592 ///
593 pub fn remove(&mut self, index: usize) -> T {
594 self.check_bounds(index, "remove");
595 unsafe {
596 let ret = self.data[index].assume_init_read();
597 for i in index+1..self.len() {
598 copy_nonoverlapping(
599 self.data[i].as_ptr(), self.data[i-1].as_mut_ptr(), 1
600 )
601 }
602 self.len -= 1;
603 ret
604 }
605 }
606
607 ///
608 /// Removes all elements from the stack
609 ///
610 /// # Examples
611 /// ```
612 /// # use stack_stack::{Stack, stack};
613 /// let mut s1 = stack![1, 2, 3, 4, 5; 5];
614 /// s1.clear();
615 /// assert_eq!(s1, []);
616 /// ```
617 ///
618 pub fn clear(&mut self) {
619 if needs_drop::<T>() {
620 for i in 0..self.len {
621 unsafe { self.data[i].assume_init_drop(); }
622 }
623 }
624 self.len = 0;
625 }
626
627 ///
628 /// Resizes the stack in place to the given length, filling with `x` when needed
629 ///
630 /// If the new length is less than the current one, the stack is truncated
631 /// to the new size, else, the stack is grown to the new size, cloning `x`
632 /// in to fill the new space as needed.
633 ///
634 /// # Panics
635 /// Panics if the new length is greater than the capacity
636 ///
637 /// # Examples
638 /// ```
639 /// # use stack_stack::{Stack, stack};
640 /// let mut s1 = stack![6, 2, 8; 5];
641 /// s1.resize(5, 10);
642 /// assert_eq!(s1, [6,2,8,10,10]);
643 ///
644 /// let mut s2 = stack![6, 2, 8, 3, 1; 5];
645 /// s2.resize(3, 10);
646 /// assert_eq!(s2, [6, 2, 8]);
647 ///
648 /// ```
649 pub fn resize(&mut self, new_len:usize, x:T) where T:Clone {
650 self.resize_with(new_len, || x.clone())
651 }
652
653 ///
654 /// Resizes the stack in place to the given length
655 ///
656 /// If the new length is less than the current one, the stack is truncated
657 /// to the new size, else, the stack is grown to the new size, using the
658 /// given function to create values to fill into the new space as needed.
659 ///
660 /// # Examples
661 /// ```
662 /// # use stack_stack::{Stack, stack};
663 /// let mut s1 = stack![6, 2, 8; 5];
664 /// s1.resize_with(5, || 10);
665 /// assert_eq!(s1, [6,2,8,10,10]);
666 ///
667 /// let mut s2 = stack![6, 2, 8, 3, 1; 5];
668 /// s2.resize_with(3, || 10);
669 /// assert_eq!(s2, [6, 2, 8]);
670 ///
671 /// ```
672 pub fn resize_with<F:FnMut()->T>(&mut self, new_len:usize, mut f:F) {
673 self.check_capacity(new_len, "resize");
674 if new_len < self.len() {
675 self.truncate(new_len);
676 } else {
677 while self.len() < new_len {
678 self.push(f()).ok();
679 }
680 }
681 }
682
683 ///
684 /// Appends the stack with values from a slice
685 ///
686 /// If extending would take the stack over-capacity, then
687 /// as many values as possible are pushed in and a sub-slice of
688 /// the remaining elements is returned.
689 ///
690 /// # Examples
691 /// ```
692 /// # use stack_stack::{Stack, stack};
693 /// let mut s1 = stack![6, 2, 8; 5];
694 /// assert_eq!(s1.extend_from_slice(&[3,1]), Ok(()));
695 /// assert_eq!(s1, [6,2,8,3,1]);
696 ///
697 ///
698 /// let mut s2 = stack![6, 2, 8; 5];
699 /// assert_eq!(s2.extend_from_slice(&[3,1,8,5]), Err(&[8,5] as &[_]));
700 /// assert_eq!(s2, [6,2,8,3,1]);
701 ///
702 /// ```
703 ///
704 pub fn extend_from_slice<'a>(&mut self, mut other:&'a[T]) -> Result<(),&'a[T]>
705 where T:Clone
706 {
707 while let Some((first, rest)) = other.split_first() {
708 self.push(first.clone()).map_err(|_| other)?;
709 other = rest;
710 }
711 Ok(())
712 }
713
714
715 ///
716 /// Appends the stack with values from an iterator
717 ///
718 /// If extending would take the stack over-capacity, then
719 /// as many values as possible are pushed in and the iterator
720 /// of the remaining elements is returned
721 ///
722 /// # Examples
723 /// ```
724 /// # use stack_stack::{Stack, stack};
725 /// let mut s1 = stack![9,9,9,9; 10];
726 /// assert_eq!(s1.extend_from_iter(0..3), Ok(()));
727 /// assert_eq!(s1, [9,9,9,9,0,1,2]);
728 ///
729 ///
730 /// let mut s1 = stack![9,9,9,9; 7];
731 /// assert_eq!(s1.extend_from_iter(0..10), Err(3..10)); //only 3 elements are appended
732 /// assert_eq!(s1, [9,9,9,9,0,1,2]);
733 ///
734 /// ```
735 ///
736 pub fn extend_from_iter<I:Iterator<Item=T>>(&mut self, mut iter:I) -> Result<(), I> {
737 loop {
738 if self.is_full() {
739 return Err(iter);
740 } else if let Some(x) = iter.next() {
741 self.push(x).ok();
742 } else {
743 return Ok(());
744 }
745 }
746 }
747
748}
749
750impl<T,const N:usize> IntoIterator for Stack<T,N> {
751 type Item = T;
752 type IntoIter = IntoIter<T,N>;
753 fn into_iter(self) -> Self::IntoIter {
754 IntoIter { index: 0, stack: self }
755 }
756}
757
758/// An iterator over the values of a [`Stack`]
759pub struct IntoIter<T, const N:usize> {
760 index: usize,
761 stack: Stack<T,N>
762}
763
764impl<T, const N:usize> IntoIter<T,N> {
765 fn remaining(&self) -> usize {
766 self.stack.len()-self.index
767 }
768}
769
770impl<T, const N:usize> Iterator for IntoIter<T,N> {
771 type Item = T;
772 fn next(&mut self) -> Option<Self::Item> {
773 if self.index >= self.stack.len() { return None; }
774 unsafe {
775 let i = self.index;
776 self.index += 1;
777 Some(self.stack.data[i].assume_init_read())
778 }
779 }
780
781 fn size_hint(&self) -> (usize, Option<usize>) {
782 let remaining = self.remaining();
783 (remaining, Some(remaining))
784 }
785
786 fn count(self) -> usize { self.remaining() }
787
788}
789
790impl<T, const N:usize> DoubleEndedIterator for IntoIter<T,N> {
791 fn next_back(&mut self) -> Option<Self::Item> {
792 self.stack.pop()
793 }
794}
795
796impl<T, const N:usize> ExactSizeIterator for IntoIter<T,N> {}
797// unsafe impl<T, const N:usize> TrustedLen for IntoIter<T,N> {}
798