summaryrefslogtreecommitdiff
path: root/learn_2/src
diff options
context:
space:
mode:
authorBrad Clawsie <brad@b7j0c.org>2026-11-12 16:22:58 -0600
committerBrad Clawsie <brad@b7j0c.org>2026-11-12 16:22:58 -0600
commit07223059ff5bb21458d791664b4e8ed857593e8a (patch)
tree7c22aabfe2a745568f53fe6385b0cb9abb3704be /learn_2/src
parent5a39e24beb4b90fe17ce7b698ad353eb16d974df (diff)
feat: learn_2
commit 6e217fcc38d71b296c6b1d42f16ae27ed65bc67c Author: Brad Clawsie <brad@b7j0c.org> Date: Thu Nov 12 16:22:41 2026 -0600 feat: learn_2
Diffstat (limited to 'learn_2/src')
-rw-r--r--learn_2/src/main.rs100
1 files changed, 100 insertions, 0 deletions
diff --git a/learn_2/src/main.rs b/learn_2/src/main.rs
new file mode 100644
index 0000000..7191e40
--- /dev/null
+++ b/learn_2/src/main.rs
@@ -0,0 +1,100 @@
+struct Library {
+ books: Vec<Book>,
+}
+
+struct Book {
+ title: String,
+ author: String,
+}
+
+impl Library {
+ fn new() -> Self {
+ Self{
+ books: Vec::new(),
+ }
+ }
+
+ fn add(&mut self, book: Book) {
+ // libraries are allowed to have copies of the same book
+ self.books.push(book)
+ }
+
+ fn find(&self, title: &str) -> Option<&Book> {
+ self.books.iter().find(|&x| x.title == title)
+ }
+
+ fn take(&mut self, title: &str) -> Option<Book> {
+ let index = self.books.iter().position(|x| x.title == title)?;
+ Some(self.books.remove(index))
+ }
+
+ fn transfer(&mut self, destination: &mut Library, title: &str) -> bool {
+ if let Some(book) = self.take(title) {
+ destination.add(book);
+ return true;
+ }
+ false
+ }
+}
+
+fn main() {
+ ()
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::*;
+
+ #[test]
+ fn test_new() {
+ let library = Library::new();
+ assert_eq!(library.books.len(), 0);
+ }
+
+ #[test]
+ fn test_add() {
+ let mut library = Library::new();
+ assert_eq!(library.books.len(), 0);
+ library.add(Book{
+ title: String::from("some book"),
+ author: String::from("some author"),
+ });
+ assert_eq!(library.books.len(), 1);
+ }
+
+ #[test]
+ fn test_find() {
+ let mut library = Library::new();
+ library.add(Book{
+ title: String::from("some book"),
+ author: String::from("some author"),
+ });
+ assert!(library.find("some book").is_some());
+ assert!(library.find("other book").is_none());
+ }
+
+ #[test]
+ fn test_take() {
+ let mut library = Library::new();
+ library.add(Book{
+ title: String::from("some book"),
+ author: String::from("some author"),
+ });
+ assert!(library.take("some book").is_some());
+ assert!(library.take("other book").is_none());
+ }
+
+ #[test]
+ fn test_transfer() {
+ let mut library = Library::new();
+ library.add(Book{
+ title: String::from("some book"),
+ author: String::from("some author"),
+ });
+ let mut destination = Library::new();
+ assert!(library.transfer(&mut destination, "some book"));
+ assert!(destination.find("some book").is_some());
+ assert!(library.find("some book").is_none());
+ }
+
+}