variants.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //
  2. // imag - the personal information management suite for the commandline
  3. // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
  4. //
  5. // This library is free software; you can redistribute it and/or
  6. // modify it under the terms of the GNU Lesser General Public
  7. // License as published by the Free Software Foundation; version
  8. // 2.1 of the License.
  9. //
  10. // This library is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. // Lesser General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU Lesser General Public
  16. // License along with this library; if not, write to the Free Software
  17. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  18. //
  19. /**
  20. * Generate variants of a base value by applying parts
  21. *
  22. * Example:
  23. *
  24. * ```ignore
  25. * generate_variants(path, vec!["foo", "bar", "baz"], |b, v| {
  26. * let b = b.clone();
  27. * b.push(v);
  28. * b
  29. * })
  30. *
  31. * ```
  32. *
  33. */
  34. pub fn generate_variants<A, B, C, F>(base: A, modders: Vec<B>, f: &F)
  35. -> Vec<C>
  36. where
  37. F: Fn(&A, B) -> C
  38. {
  39. modders.into_iter().map(|m| f(&base, m)).collect()
  40. }
  41. #[cfg(test)]
  42. mod test {
  43. use super::generate_variants;
  44. #[test]
  45. fn test_variants_simple() {
  46. let base = 1;
  47. let vars = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  48. let res = generate_variants(base, vars, &|base, var| base + var);
  49. assert!(res.len() == 11, format!("Length is {} instead of 11", res.len()));
  50. assert!(res.iter().all(|i| *i > 0));
  51. assert!(res == vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  52. }
  53. #[test]
  54. fn test_variants_pathes() {
  55. use std::path::PathBuf;
  56. let base = PathBuf::from("/");
  57. let vars = vec!["foo", "bar", "baz"];
  58. let res = generate_variants(base, vars, &|base, var| {
  59. let mut base = base.clone();
  60. base.push(var);
  61. base
  62. });
  63. assert!(res.len() == 3, format!("Length is {} instead of 3", res.len()));
  64. let eq_vec = vec!["/foo", "/bar", "/baz"];
  65. let eq = eq_vec.iter().map(PathBuf::from);
  66. assert!(res.into_iter().zip(eq).all(|(orig, equi)| orig == equi));
  67. }
  68. }