oxedyne/fe2o3/fe2o3_data/src/map3.rs
1.9 KiB, 1 run
created by r1870400018:76451, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! The three-way merge of two keyed maps against their common base. |
| 2 | //! |
| 3 | //! Each side is compared with the base key by key, a key absent from a map |
| 4 | //! reading as deleted there. The answer names, for every key either side |
| 5 | //! touched, whether to take `theirs`, keep `ours`, or report a conflict; what to |
| 6 | //! do with a conflict is the caller's policy, not this module's. |
| 7 | //! |
| 8 | //! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\ |
| 9 | //! Anthropic Claude |
| 10 | |
| 11 | use std::collections::{ |
| 12 | BTreeMap, |
| 13 | BTreeSet, |
| 14 | }; |
| 15 | |
| 16 | |
| 17 | /// The keys a three-way merge sorts into each outcome. A key in none of the |
| 18 | /// sets is unchanged on both sides. |
| 19 | #[derive(Clone, Debug, Default, Eq, PartialEq)] |
| 20 | pub struct Merge3<K: Ord> { |
| 21 | pub take: BTreeSet<K>, // theirs changed, ours did not: take theirs (absent means delete) |
| 22 | pub keep: BTreeSet<K>, // ours changed, theirs did not, or both made the same change |
| 23 | pub conflict: BTreeSet<K>, // both changed, differently |
| 24 | } |
| 25 | |
| 26 | impl<K: Ord> Merge3<K> { |
| 27 | /// Did the merge finish without a conflict? |
| 28 | pub fn is_clean(&self) -> bool { |
| 29 | self.conflict.is_empty() |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | /// Sorts every key `ours` or `theirs` changed from `base` into take, keep |
| 34 | /// or conflict. |
| 35 | pub fn merge3<K: Ord + Clone, V: PartialEq>( |
| 36 | base: &BTreeMap<K, V>, |
| 37 | ours: &BTreeMap<K, V>, |
| 38 | theirs: &BTreeMap<K, V>, |
| 39 | ) |
| 40 | -> Merge3<K> |
| 41 | { |
| 42 | let mut out = Merge3 { |
| 43 | take: BTreeSet::new(), |
| 44 | keep: BTreeSet::new(), |
| 45 | conflict: BTreeSet::new(), |
| 46 | }; |
| 47 | let keys: BTreeSet<&K> = base.keys() |
| 48 | .chain(ours.keys()) |
| 49 | .chain(theirs.keys()) |
| 50 | .collect(); |
| 51 | for k in keys { |
| 52 | let (b, o, t) = (base.get(k), ours.get(k), theirs.get(k)); |
| 53 | match (o != b, t != b) { |
| 54 | (false, false) => {} |
| 55 | (false, true) => { out.take.insert(k.clone()); } |
| 56 | (true, false) => { out.keep.insert(k.clone()); } |
| 57 | // Both deleting, or both writing the same value, agree. |
| 58 | (true, true) if o == t => { out.keep.insert(k.clone()); } |
| 59 | (true, true) => { out.conflict.insert(k.clone()); } |
| 60 | } |
| 61 | } |
| 62 | out |
| 63 | } |