Skip to content

Commit

Permalink
refactor: use IntoIterator instead of Deref for builder API. (#319)
Browse files Browse the repository at this point in the history
Greatly generalizes the types of inputs allowed.
  • Loading branch information
molpopgen authored Sep 20, 2023
1 parent 237fa9a commit d3099cc
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 14 deletions.
19 changes: 8 additions & 11 deletions demes/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,15 @@ impl GraphBuilder {
/// ```
///
/// # Notes
pub fn add_deme<D: std::ops::Deref<Target = [UnresolvedEpoch]>>(
pub fn add_deme<I: IntoIterator<Item = UnresolvedEpoch>>(
&mut self,
name: &str,
epochs: D,
epochs: I,
history: UnresolvedDemeHistory,
description: Option<&str>,
) {
let ptr = UnresolvedDeme::new_via_builder(name, epochs.to_owned(), history, description);
let epochs = epochs.into_iter().collect::<Vec<_>>();
let ptr = UnresolvedDeme::new_via_builder(name, epochs, history, description);
self.graph.add_deme(ptr);
}

Expand Down Expand Up @@ -160,23 +161,19 @@ impl GraphBuilder {
/// Some([0.5].as_slice()));
/// b.resolve().unwrap();
/// ```
pub fn add_pulse<
T: Into<InputTime>,
P: Into<InputProportion> + Copy,
D: std::ops::Deref<Target = [P]>,
>(
pub fn add_pulse<T: Into<InputTime>, P: Into<InputProportion>, I: IntoIterator<Item = P>>(
&mut self,
sources: Option<&[&str]>,
dest: Option<&str>,
time: Option<T>,
proportions: Option<D>,
proportions: Option<I>,
) {
let sources = sources.map(|value| value.iter().map(|v| v.to_string()).collect::<Vec<_>>());
let dest = dest.map(|value| value.to_string());
let time = time.map(|t| t.into());
let proportions = proportions.map(|s| {
s.iter()
.map(|p| (*p).into())
s.into_iter()
.map(|p| p.into())
.collect::<Vec<InputProportion>>()
});
self.graph.add_pulse(sources, dest, time, proportions);
Expand Down
6 changes: 6 additions & 0 deletions demes/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,12 @@ macro_rules! impl_input_newtype_traits {
}
}

impl From<&f64> for $type {
fn from(value: &f64) -> Self {
Self(*value)
}
}

impl From<$type> for f64 {
fn from(value: $type) -> Self {
value.0
Expand Down
10 changes: 7 additions & 3 deletions demes/src/specification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,13 +283,17 @@ impl UnresolvedMigration {
/// ```
/// let _ = demes::UnresolvedMigration::default().set_demes(["A", "B"].as_slice());
/// ```
pub fn set_demes<D, A>(self, d: D) -> Self
pub fn set_demes<I, A>(self, d: I) -> Self
where
D: std::ops::Deref<Target = [A]>,
I: IntoIterator<Item = A>,
A: AsRef<str>,
{
Self {
demes: Some(d.iter().map(|a| a.as_ref().to_owned()).collect::<Vec<_>>()),
demes: Some(
d.into_iter()
.map(|a| a.as_ref().to_owned())
.collect::<Vec<_>>(),
),
..self
}
}
Expand Down

0 comments on commit d3099cc

Please sign in to comment.