summaryrefslogtreecommitdiff
path: root/solutions/19_smart_pointers/cow1.rs
diff options
context:
space:
mode:
authormo8it <mo8it@proton.me>2024-07-05 13:39:50 +0200
committermo8it <mo8it@proton.me>2024-07-05 13:39:50 +0200
commit7123c7ae3a9605fbe962e4ef0a0f1424cd16fef8 (patch)
treec67f7e62bb9a179ae4fdbab492501cb6847e64c7 /solutions/19_smart_pointers/cow1.rs
parent77b687d501771c24bd83294d97b8e6f9ffa92d6b (diff)
parent4d9c346a173bb722b929f3ea3c00f84954483e24 (diff)
Merge remote-tracking branch 'upstream/main' into fix-enum-variant-inconsistency
Diffstat (limited to 'solutions/19_smart_pointers/cow1.rs')
-rw-r--r--solutions/19_smart_pointers/cow1.rs68
1 files changed, 68 insertions, 0 deletions
diff --git a/solutions/19_smart_pointers/cow1.rs b/solutions/19_smart_pointers/cow1.rs
new file mode 100644
index 0000000..0a21a91
--- /dev/null
+++ b/solutions/19_smart_pointers/cow1.rs
@@ -0,0 +1,68 @@
+// This exercise explores the `Cow` (Clone-On-Write) smart pointer. It can
+// enclose and provide immutable access to borrowed data and clone the data
+// lazily when mutation or ownership is required. The type is designed to work
+// with general borrowed data via the `Borrow` trait.
+
+use std::borrow::Cow;
+
+fn abs_all(input: &mut Cow<[i32]>) {
+ for ind in 0..input.len() {
+ let value = input[ind];
+ if value < 0 {
+ // Clones into a vector if not already owned.
+ input.to_mut()[ind] = -value;
+ }
+ }
+}
+
+fn main() {
+ // You can optionally experiment here.
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reference_mutation() {
+ // Clone occurs because `input` needs to be mutated.
+ let vec = vec![-1, 0, 1];
+ let mut input = Cow::from(&vec);
+ abs_all(&mut input);
+ assert!(matches!(input, Cow::Owned(_)));
+ }
+
+ #[test]
+ fn reference_no_mutation() {
+ // No clone occurs because `input` doesn't need to be mutated.
+ let vec = vec![0, 1, 2];
+ let mut input = Cow::from(&vec);
+ abs_all(&mut input);
+ assert!(matches!(input, Cow::Borrowed(_)));
+ // ^^^^^^^^^^^^^^^^
+ }
+
+ #[test]
+ fn owned_no_mutation() {
+ // We can also pass `vec` without `&` so `Cow` owns it directly. In this
+ // case, no mutation occurs and thus also no clone. But the result is
+ // still owned because it was never borrowed or mutated.
+ let vec = vec![0, 1, 2];
+ let mut input = Cow::from(vec);
+ abs_all(&mut input);
+ assert!(matches!(input, Cow::Owned(_)));
+ // ^^^^^^^^^^^^^
+ }
+
+ #[test]
+ fn owned_mutation() {
+ // Of course this is also the case if a mutation does occur. In this
+ // case, the call to `to_mut()` in the `abs_all` function returns a
+ // reference to the same data as before.
+ let vec = vec![-1, 0, 1];
+ let mut input = Cow::from(vec);
+ abs_all(&mut input);
+ assert!(matches!(input, Cow::Owned(_)));
+ // ^^^^^^^^^^^^^
+ }
+}