Skip to content

Commit 72e21a2

Browse files
committed
feat: add cow1.rs exercise
1 parent 3a32709 commit 72e21a2

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
}

info.toml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -932,6 +932,17 @@ is too much of a struggle, consider reading through all of Chapter 16 in the boo
932932
https://doc.rust-lang.org/stable/book/ch16-00-concurrency.html
933933
"""
934934

935+
[[exercises]]
936+
name = "cow1"
937+
path = "exercises/standard_library_types/cow1.rs"
938+
mode = "compile"
939+
hint = """
940+
Since the vector is already owned, the `Cow` type doesn't need to clone it.
941+
942+
Checkout https://doc.rust-lang.org/std/borrow/enum.Cow.html for documentation
943+
on the `Cow` type.
944+
"""
945+
935946
# THREADS
936947

937948
[[exercises]]

0 commit comments

Comments
 (0)