Skip to content

Commit 6e299c5

Browse files
committed
Implement IDCollection for IndexMap
1 parent c6c65e0 commit 6e299c5

3 files changed

Lines changed: 14 additions & 10 deletions

File tree

src/id.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Code for handling IDs
22
use anyhow::{Context, Result};
3-
use indexmap::IndexSet;
3+
use indexmap::{IndexMap, IndexSet};
44
use std::borrow::Borrow;
55
use std::collections::HashSet;
66
use std::fmt::Display;
@@ -105,3 +105,12 @@ impl<ID: IDLike> IDCollection<ID> for HashSet<ID> {
105105
impl<ID: IDLike> IDCollection<ID> for IndexSet<ID> {
106106
define_id_methods!();
107107
}
108+
109+
impl<ID: IDLike, V> IDCollection<ID> for IndexMap<ID, V> {
110+
fn get_id<T: Borrow<str> + Display + ?Sized>(&self, id: &T) -> Result<&ID> {
111+
let (found, _) = self
112+
.get_key_value(id.borrow())
113+
.with_context(|| format!("Unknown ID {id} found"))?;
114+
Ok(found)
115+
}
116+
}

src/input/agent/commodity_portion.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
use super::super::*;
33
use crate::agent::{AgentCommodityPortionsMap, AgentID, AgentMap};
44
use crate::commodity::{CommodityID, CommodityMap, CommodityType};
5+
use crate::id::IDCollection;
56
use crate::region::RegionID;
67
use crate::year::parse_year_str;
78
use anyhow::{ensure, Context, Result};
@@ -66,9 +67,7 @@ where
6667
for agent_commodity_portion_raw in iter {
6768
// Get agent ID
6869
let agent_id_raw = agent_commodity_portion_raw.agent_id.as_str();
69-
let (id, _agent) = agents
70-
.get_key_value(agent_id_raw)
71-
.with_context(|| format!("Invalid agent ID {agent_id_raw}"))?;
70+
let id = agents.get_id(agent_id_raw)?;
7271

7372
// Get/create entry for agent
7473
let entry = agent_commodity_portions
@@ -77,9 +76,7 @@ where
7776

7877
// Insert portion for the commodity/year(s)
7978
let commodity_id_raw = agent_commodity_portion_raw.commodity_id.as_str();
80-
let (commodity_id, _commodity) = commodities
81-
.get_key_value(commodity_id_raw)
82-
.with_context(|| format!("Invalid commodity ID {commodity_id_raw}"))?;
79+
let commodity_id = commodities.get_id(commodity_id_raw)?;
8380
let years = parse_year_str(&agent_commodity_portion_raw.years, milestone_years)?;
8481
for year in years {
8582
try_insert(

src/input/agent/search_space.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,7 @@ impl AgentSearchSpaceRaw {
5757
// Check that the year is a valid milestone year
5858
let year = parse_year_str(&self.years, milestone_years)?;
5959

60-
let (agent_id, _) = agents
61-
.get_key_value(self.agent_id.as_str())
62-
.context("Invalid agent ID")?;
60+
let agent_id = agents.get_id(&self.agent_id)?;
6361

6462
Ok(AgentSearchSpace {
6563
agent_id: agent_id.clone(),

0 commit comments

Comments
 (0)