From dce37b4c583bdb31a3b5e33f7d2238677e887e83 Mon Sep 17 00:00:00 2001 From: Alexander Baranov Date: Fri, 23 Jan 2026 16:43:54 +0300 Subject: [PATCH] homework: dynamic insert / remove in devices and rooms --- smart-house/README.md | 4 ++-- smart-house/src/house.rs | 22 ++++++++++++++++++++++ smart-house/src/room.rs | 29 +++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/smart-house/README.md b/smart-house/README.md index 822d6fc..1324022 100644 --- a/smart-house/README.md +++ b/smart-house/README.md @@ -77,8 +77,8 @@ Доработать хранение объектов: - [x] Заменить массивы устройств и комнат на ассоциативные коллекции из std. В качестве ключей использовать строки. - [x] Реализовать трейт Debug на всех типах. -- [ ] Добавить возможность динамически добавлять/удалять устройства в комнату. -- [ ] Добавить возможность динамически добавлять/удалять комнату в дом. +- [x] Добавить возможность динамически добавлять/удалять устройства в комнату. +- [x] Добавить возможность динамически добавлять/удалять комнату в дом. - [ ] Добавить в тип умного дома метод, позволяющий сразу получить ссылку на умное устройство. Метод принимает имя комнаты и имя устройства. В случае, если устройство или комната не найдены, возвращать тип ошибки, сообщающий, что именно произошло. Тип ошибки должен реализовывать трейт `std::error::Error`. diff --git a/smart-house/src/house.rs b/smart-house/src/house.rs index b35ec07..2154434 100644 --- a/smart-house/src/house.rs +++ b/smart-house/src/house.rs @@ -28,6 +28,14 @@ impl House { self.rooms.get_mut(key) } + pub fn insert_room(&mut self, room: Room) -> Option { + self.rooms.insert(room.get_name().to_string(), room) + } + + pub fn remove_room(&mut self, key: &str) -> Option { + self.rooms.remove(key) + } + pub fn print_status(&self) { println!("HOUSE '{}':", self.address); println!("{}", "=".repeat(32)); @@ -102,4 +110,18 @@ mod tests { let house = create_test_house(); assert!(house.get_room("absent").is_none()); } + + #[test] + fn test_add_remove() { + let mut house = create_test_house(); + let room = Room::new("empty", Box::new([])); + + let result = house.insert_room(room); + assert!(result.is_none()); + assert_eq!(house.rooms.len(), 3); + + let Some(result) = house.remove_room("bedroom") else { unreachable!() }; + assert_eq!(result.get_name(), "bedroom"); + assert_eq!(house.rooms.len(), 2); + } } diff --git a/smart-house/src/room.rs b/smart-house/src/room.rs index 61f79cc..dfde819 100644 --- a/smart-house/src/room.rs +++ b/smart-house/src/room.rs @@ -28,6 +28,14 @@ impl Room { self.devices.get_mut(key) } + pub fn insert_device(&mut self, device: Device) -> Option { + self.devices.insert(device.get_name().to_string(), device) + } + + pub fn remove_device(&mut self, key: &str) -> Option { + self.devices.remove(key) + } + pub fn print_status(&self) { println!("ROOM '{}':", self.name); println!("{}", "-".repeat(24)); @@ -76,4 +84,25 @@ mod tests { ); assert!(room.get_device("dummy").is_none()); } + + #[test] + fn test_add_remove() { + let mut room = Room::new( + "test_room", + Box::new([ + Device::PowerSocket(PowerSocket::new("PSoc", 12.34, false)), + Device::Thermometer(Thermometer::new("Therm", 21.56)), + ]), + ); + let result = room.insert_device(Device::Thermometer(Thermometer::new("NewTerm", 20.0))); + assert!(result.is_none()); + assert_eq!(room.devices.len(), 3); + + let Some(Device::Thermometer(removed)) = room.remove_device("Therm") else { + unreachable!() + }; + assert_eq!(removed.get_name(), "Therm"); + assert_eq!(removed.get_temperature(), 21.56); + assert_eq!(room.devices.len(), 2); + } }