forked from rust-lang/rustlings
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request rust-lang#1103 from exdx/feat/cow
feat: add cow1.rs exercise
- Loading branch information
Showing
2 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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"), | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters