|
| 1 | +// cow1.rs |
| 2 | + |
| 3 | +// This exercise explores the Cow, or Clone-On-Write type. |
| 4 | +// Cow is a clone-on-write smart pointer. |
| 5 | +// It can enclose and provide immutable access to borrowed data, and clone the data lazily when mutation or ownership is required. |
| 6 | +// The type is designed to work with general borrowed data via the Borrow trait. |
| 7 | + |
| 8 | +// I AM NOT DONE |
| 9 | + |
| 10 | +use std::borrow::Cow; |
| 11 | + |
| 12 | +fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> { |
| 13 | + for i in 0..input.len() { |
| 14 | + let v = input[i]; |
| 15 | + if v < 0 { |
| 16 | + // Clones into a vector if not already owned. |
| 17 | + input.to_mut()[i] = -v; |
| 18 | + } |
| 19 | + } |
| 20 | + input |
| 21 | +} |
| 22 | + |
| 23 | +fn main() { |
| 24 | + // No clone occurs because `input` doesn't need to be mutated. |
| 25 | + let slice = [0, 1, 2]; |
| 26 | + let mut input = Cow::from(&slice[..]); |
| 27 | + match abs_all(&mut input) { |
| 28 | + Cow::Borrowed(_) => println!("I borrowed the slice!"), |
| 29 | + _ => panic!("expected borrowed value"), |
| 30 | + } |
| 31 | + |
| 32 | + // Clone occurs because `input` needs to be mutated. |
| 33 | + let slice = [-1, 0, 1]; |
| 34 | + let mut input = Cow::from(&slice[..]); |
| 35 | + match abs_all(&mut input) { |
| 36 | + Cow::Owned(_) => println!("I modified the slice and now own it!"), |
| 37 | + _ => panic!("expected owned value"), |
| 38 | + } |
| 39 | + |
| 40 | + // No clone occurs because `input` is already owned. |
| 41 | + let slice = vec![-1, 0, 1]; |
| 42 | + let mut input = Cow::from(slice); |
| 43 | + match abs_all(&mut input) { |
| 44 | + // TODO |
| 45 | + Cow::Borrowed(_) => println!("I own this slice!"), |
| 46 | + _ => panic!("expected borrowed value"), |
| 47 | + } |
| 48 | +} |
0 commit comments