From a6afa81d1d9f2dd7d10fe7c0555ae8a8a6d84867 Mon Sep 17 00:00:00 2001 From: Daniel Schadt Date: Thu, 12 Dec 2019 01:25:28 +0100 Subject: use helper traits for better code --- src/main.rs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index d3839b2..181d64a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -83,6 +83,19 @@ impl StdError for NotFound {} /// 2. We don't want yet another error kind with a lot of kinds. type MainResult = Result>; +/// A trait for containers that only contain a single item. +trait SingleContainer { + /// Extract the single element by consuming the container. + fn single(self) -> T; +} + +impl SingleContainer for Vec { + fn single(self) -> T { + assert_eq!(self.len(), 1, "this container must have exactly 1 element."); + self.into_iter().next().unwrap() + } +} + /// Find the profession by the given name. fn find_profession(api: &mut Api, name: &str) -> MainResult { let profession_ids = api.get_profession_ids()?; @@ -93,7 +106,7 @@ fn find_profession(api: &mut Api, name: &str) -> MainResult { .ok_or_else(|| NotFound::Profession(name.to_owned()))? .clone(); - Ok(api.get_professions(&[profession_id])?.remove(0)) + Ok(api.get_professions(&[profession_id])?.single()) } /// Resolve a skill. @@ -106,7 +119,7 @@ fn resolve_skill(api: &mut Api, profession: &Profession, text: &str) -> MainResu if let Ok(num_id) = numeric { let exists = profession.skills.iter().any(|s| s.id == num_id); if exists { - return Ok(api.get_skills(&[num_id])?.remove(0)); + return Ok(api.get_skills(&[num_id])?.single()); } else { return Err(NotFound::SkillId(num_id).into()); } @@ -191,10 +204,10 @@ fn run_searching(api: &mut Api, matches: &ArgMatches) -> MainResult, _>>()? } else if let Some(l) = legends.first() { - let l = api.get_legends(&[l.get_api_id().unwrap()])?.remove(0); + let l = api.get_legends(&[l.api_id().unwrap()])?.single(); let mut result = Vec::new(); for skill_id in (&[l.heal]).iter().chain(&l.utilities).chain(&[l.elite]) { - let skill = api.get_skills(&[*skill_id])?.remove(0); + let skill = api.get_skills(&[*skill_id])?.single(); result.push(skill); } result -- cgit v1.2.3