Skip to content

parallel-letter-frequency: Use &str with lifetime, not String #239

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions exercises/parallel-letter-frequency/example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,18 @@ use std::sync::mpsc::channel;

/// Compute the frequency of each letter (technically of each unicode codepoint) using the given
/// number of worker threads.
pub fn frequency(texts: &[&str], num_workers: usize) -> HashMap<char, usize> {
pub fn frequency(texts: &[&'static str], num_workers: usize) -> HashMap<char, usize> {
assert!(num_workers > 0);
let part_size_floor = texts.len() / num_workers;
let rem = texts.len() % num_workers;
let part_size = if rem > 0 { part_size_floor + 1 } else { part_size_floor };
let mut parts: Vec<Vec<String>> = Vec::with_capacity(part_size);
let mut parts: Vec<Vec<&str>> = Vec::with_capacity(part_size);
for _ in 0 .. num_workers {
parts.push(Vec::with_capacity(part_size));
}
let mut i = 0;
for line in texts.iter() {
// We'll need to clone those strings in order to satisfy some lifetime guarantees. Basically
// it's hard for the system to be sure that the threads spawned don't outlive the strings.
parts[i].push(line.to_string());
for &line in texts.iter() {
parts[i].push(line);
i = (i + 1) % num_workers;
}

Expand All @@ -41,7 +39,7 @@ pub fn frequency(texts: &[&str], num_workers: usize) -> HashMap<char, usize> {
results
}

fn count(lines: Vec<String>) -> HashMap<char, usize> {
fn count(lines: Vec<&str>) -> HashMap<char, usize> {
let mut results: HashMap<char, usize> = HashMap::new();
for line in lines.iter() {
for c in line.chars() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ fn test_no_texts() {
assert_eq!(frequency::frequency(&[], 4), HashMap::new());
}

#[test]
#[ignore]
fn test_hello_world() {
let hi = format!("Hello, {}!", "world");
frequency::frequency(&[&hi], 4);
}

#[test]
#[ignore]
fn test_one_letter() {
Expand Down