summaryrefslogtreecommitdiff
path: root/exercises
diff options
context:
space:
mode:
authorDenton24646 <Denton24646@gmail.com>2022-07-23 17:57:03 -0400
committerDenton24646 <Denton24646@gmail.com>2022-07-23 17:59:53 -0400
commit72e21a2a6c2654cb1d2e292291e2e40914957776 (patch)
treec84cc39c296bb26bb021b981468b5a60ae91dff5 /exercises
parent3a327096c6d6f8badc066a31f75e7f10468cf9fd (diff)
feat: add cow1.rs exercise
Diffstat (limited to 'exercises')
-rw-r--r--exercises/standard_library_types/cow1.rs48
1 files changed, 48 insertions, 0 deletions
diff --git a/exercises/standard_library_types/cow1.rs b/exercises/standard_library_types/cow1.rs
new file mode 100644
index 0000000..5fba251
--- /dev/null
+++ b/exercises/standard_library_types/cow1.rs
@@ -0,0 +1,48 @@
+// cow1.rs
+
+// This exercise explores the Cow, or Clone-On-Write type.
+// Cow is a 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.
+
+// I AM NOT DONE
+
+use std::borrow::Cow;
+
+fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> {
+ for i in 0..input.len() {
+ let v = input[i];
+ if v < 0 {
+ // Clones into a vector if not already owned.
+ input.to_mut()[i] = -v;
+ }
+ }
+ input
+}
+
+fn main() {
+ // No clone occurs because `input` doesn't need to be mutated.
+ let slice = [0, 1, 2];
+ let mut input = Cow::from(&slice[..]);
+ match abs_all(&mut input) {
+ Cow::Borrowed(_) => println!("I borrowed the slice!"),
+ _ => panic!("expected borrowed value"),
+ }
+
+ // Clone occurs because `input` needs to be mutated.
+ let slice = [-1, 0, 1];
+ let mut input = Cow::from(&slice[..]);
+ match abs_all(&mut input) {
+ Cow::Owned(_) => println!("I modified the slice and now own it!"),
+ _ => panic!("expected owned value"),
+ }
+
+ // No clone occurs because `input` is already owned.
+ let slice = vec![-1, 0, 1];
+ let mut input = Cow::from(slice);
+ match abs_all(&mut input) {
+ // TODO
+ Cow::Borrowed(_) => println!("I own this slice!"),
+ _ => panic!("expected borrowed value"),
+ }
+}