microstack/
clone.rs

1// Copyright (c) 2023 Yegor Bugayenko
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included
11// in all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21use crate::Stack;
22use std::ptr;
23
24impl<V: Copy, const N: usize> Clone for Stack<V, N> {
25    /// Clone it.
26    #[must_use]
27    fn clone(&self) -> Self {
28        let mut s: Self = Self::new();
29        s.next = self.next;
30        unsafe { ptr::copy::<V>(self.items.as_ptr(), s.items.as_mut_ptr(), s.next) };
31        s
32    }
33}
34
35#[test]
36fn stack_can_be_cloned() {
37    let mut s: Stack<u8, 16> = Stack::new();
38    unsafe { s.push_unchecked(42) };
39    assert_eq!(42, s.clone().pop());
40}
41
42#[test]
43fn full_stack_can_be_cloned() {
44    let mut s: Stack<usize, 16> = Stack::new();
45    for i in 0..s.capacity() {
46        unsafe { s.push_unchecked(i) };
47    }
48    assert_eq!(s.capacity() - 1, s.clone().pop());
49}
50
51#[test]
52fn empty_stack_can_be_cloned() {
53    let m: Stack<u8, 0> = Stack::new();
54    assert!(m.clone().is_empty());
55}