Skip to content

[Merged by Bors] - Added config::merge::chainable_merge() #397

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.

## [Unreleased]

### Added

- Added `config::merge::chainable_merge()` ([#397]).

[#397]: https://github.com/stackabletech/operator-rs/pull/397

## [0.19.0] - 2022-05-05

### Changed
Expand Down
41 changes: 34 additions & 7 deletions src/config/merge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,39 @@ impl<K: Hash + Eq + Clone, V: Merge + Clone> Merge for HashMap<K, V> {
}
}

/// Moving version of [`Merge::merge`], to produce slightly nicer test output
pub fn merge<T: Merge>(mut overrides: T, defaults: &T) -> T {
overrides.merge(defaults);
overrides
}

/// Composable version of [`Merge::merge`] that allows reducing a sequence of `Option<mut& T>`.
///
/// Example:
///
/// ```
/// use stackable_operator::config::merge::{Merge, chainable_merge};
/// #[derive(Clone, Default, Merge, PartialEq)]
/// struct MyConfig {
/// field: Option<i32>,
/// }
///
/// let mut c0 = None;
/// let mut c1 = Some(MyConfig { field: Some(23) });
/// let mut c2 = Some(MyConfig { field: Some(7) });
///
/// let merged = [c0.as_mut(), c1.as_mut(), c2.as_mut()]
/// .into_iter()
/// .flatten()
/// .reduce(|old, new| chainable_merge(new, old));
///
/// assert_eq!(7, merged.unwrap().field.unwrap());
/// ```
pub fn chainable_merge<'a, T: Merge + Clone>(this: &'a mut T, defaults: &T) -> &'a mut T {
this.merge(defaults);
this
}

/// A marker trait for types that are merged atomically (as one single value) rather than
/// trying to merge each field individually
pub trait Atomic: Clone {}
Expand Down Expand Up @@ -113,13 +146,7 @@ impl<T: Atomic> Merge for Option<T> {
mod tests {
use std::collections::{BTreeMap, HashMap};

use super::Merge;

/// Moving version of [`Merge::merge`], to produce slightly nicer test output
fn merge<T: Merge>(mut overrides: T, defaults: &T) -> T {
overrides.merge(defaults);
overrides
}
use super::{merge, Merge};

#[derive(Debug, PartialEq, Eq, Clone)]
struct Accumulator(u8);
Expand Down