a bad linked list (chapter 1)
This commit is contained in:
parent
05c7445d04
commit
5dbb93455c
72
src/bad.rs
Normal file
72
src/bad.rs
Normal file
@ -0,0 +1,72 @@
|
||||
|
||||
pub struct List {
|
||||
head: Link
|
||||
}
|
||||
|
||||
enum Link {
|
||||
Empty,
|
||||
More (Box<Node>)
|
||||
}
|
||||
|
||||
struct Node {
|
||||
val: i32,
|
||||
next: List
|
||||
}
|
||||
|
||||
|
||||
impl List {
|
||||
fn new () -> Self {
|
||||
List { head: Link::Empty }
|
||||
}
|
||||
|
||||
fn push (&mut self, val: i32) {
|
||||
let new_node = Box::new(Node { val, next: List { head: std::mem::replace(&mut self.head, Link::Empty) } });
|
||||
self.head = Link::More(new_node);
|
||||
}
|
||||
|
||||
fn pop (&mut self) -> Option<i32> {
|
||||
match std::mem::replace(&mut self.head, Link::Empty) {
|
||||
Link::Empty => None,
|
||||
Link::More(v) => {
|
||||
self.head = v.next.head;
|
||||
Some(v.val)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::List;
|
||||
|
||||
#[test]
|
||||
fn basics () {
|
||||
let mut list = List::new();
|
||||
|
||||
// Check empty list behaves right
|
||||
assert_eq!(list.pop(), None);
|
||||
|
||||
// Populate list
|
||||
list.push(1);
|
||||
list.push(2);
|
||||
list.push(3);
|
||||
|
||||
// Check normal removal
|
||||
assert_eq!(list.pop(), Some(3));
|
||||
assert_eq!(list.pop(), Some(2));
|
||||
|
||||
// Push some more just to make sure nothing's corrupted
|
||||
list.push(4);
|
||||
list.push(5);
|
||||
|
||||
// Check normal removal
|
||||
assert_eq!(list.pop(), Some(5));
|
||||
assert_eq!(list.pop(), Some(4));
|
||||
|
||||
// Check exhaustion
|
||||
assert_eq!(list.pop(), Some(1));
|
||||
assert_eq!(list.pop(), None);
|
||||
|
||||
}
|
||||
}
|
||||
15
src/lib.rs
15
src/lib.rs
@ -1,14 +1 @@
|
||||
pub fn add(left: u64, right: u64) -> u64 {
|
||||
left + right
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let result = add(2, 2);
|
||||
assert_eq!(result, 4);
|
||||
}
|
||||
}
|
||||
pub mod bad;
|
||||
|
||||
Loading…
Reference in New Issue
Block a user