Skip to content

Commit 1336836

Browse files
committed
added stacks example
1 parent 88fbfa1 commit 1336836

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ in a controlled repository now.
2626
* `addy.rs`: trait def/impl example
2727
* `bno-salad.rs`: trait salad example from Blandy and Orendorff
2828
* `matmul.rs`: example of overloading multiplication for matrices
29+
* `stacks.rs`: example defining a stack trait
2930
* `phantom.rs`: phantom type example
3031
* `deref.rs`: deref trait example
3132
* `from.rs`: from / try_from trait example

stacks.rs

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
use std::collections::LinkedList;
2+
3+
pub trait Stack<T> {
4+
fn spush(&mut self, v: T);
5+
fn spop(&mut self) -> Option<T>;
6+
}
7+
8+
impl<'a, T: ?Sized> Stack<&'a T> for Vec<&'a T> {
9+
fn spush(&mut self, v: &'a T) {
10+
self.push(v);
11+
}
12+
13+
fn spop(&mut self) -> Option<&'a T> {
14+
self.pop()
15+
}
16+
}
17+
18+
impl<'a, T: ?Sized> Stack<&'a T> for LinkedList<&'a T> {
19+
fn spush(&mut self, v: &'a T) {
20+
self.push_front(v);
21+
}
22+
23+
fn spop(&mut self) -> Option<&'a T> {
24+
self.pop_front()
25+
}
26+
}
27+
28+
pub fn dup<'a, 'b: 'a, S, T>(stack: &mut S)
29+
where S: Stack<&'b T> + 'a, T: 'b + ?Sized
30+
{
31+
let v = stack.spop().unwrap();
32+
stack.spush(v);
33+
stack.spush(v);
34+
}
35+
36+
#[cfg(test)]
37+
mod test {
38+
use crate::*;
39+
40+
fn test<S>(mut s: S) where S: Stack<&'static str> {
41+
s.spush("hello");
42+
dup(&mut s);
43+
assert_eq!(s.spop().unwrap(), "hello");
44+
assert_eq!(s.spop().unwrap(), "hello");
45+
assert_eq!(s.spop(), None);
46+
}
47+
48+
#[test]
49+
fn test_impls() {
50+
test(Vec::new());
51+
test(LinkedList::new());
52+
}
53+
}

0 commit comments

Comments
 (0)