簡體   English   中英

在 String 上使用 par_split,使用 rayon 處理並將結果收集到 Vector

[英]Use par_split on a String, process using rayon and collect result in a Vector

我正在嘗試將文件讀入第 14 行定義的字符串messages 該文件包含幾個塊,每個塊都以一個數字開頭。 在我將文件內容讀入字符串messahes ,每個塊由換行符分隔,塊中的每一行由__SEP__ 我想在字符串messages上使用 par_split() ,使用 rayon 處理每個塊並從每個塊收集 output 到向量vec_final例如通過調用第 54 行上的 collect() 或一些類似的機制來生成包含vec_local的向量每個區塊產生 53 個。 任何關於我如何實現這一目標的指示都受到高度贊賞。

我的代碼如下:

fn starts_with_digit_or_at_sign(inp: &str) -> bool {
    let mut at_sign_found = false;
    if inp.len() > 0 {
        let ch = inp.chars().next().unwrap();
        if ch.is_numeric() || ch == '@' {
            return true;
        }
    }
    return false;
}
fn main() {
    let filepath = "inp.log";
    let data = std::fs::read_to_string(filepath).expect("file not found!");
    let mut messages: String = String::from("");
    let separator_char = '\n';
    let separator: String = String::from("__SEP__");
    let mut found_first_message = false;
    let mut start_of_new_msg = false;
    let mut line_num = 0;
    for line in data.lines() {
        line_num += 1;
        if line.len() > 0 {
            if starts_with_digit_or_at_sign(line) {
                start_of_new_msg = true;
                if !found_first_message {
                    found_first_message = true;
                } else {
                    messages.push(separator_char);
                }
            }
            if found_first_message {
                if !start_of_new_msg {
                    messages.push_str(&separator);
                }
                messages.push_str(line);
                if start_of_new_msg {
                    start_of_new_msg = false;
                    let mut tmp = String::from("Lnumber ");
                    tmp.push_str(&line_num.to_string());
                    messages.push_str(&separator);
                    messages.push_str(&tmp);
                }
            }
        }
    }
    messages.par_split(separator_char).for_each(|l| {
        println!(
            "line: '{}' len: {}, {}",
            l,
            l.len(),
            rayon::current_num_threads()
        );
        let vec_local: Vec<i32> = vec![l.len() as i32];
    }); // <-- line 54
}

cide生產的Output如下:

line: '1__SEP__Lnumber 1__SEP__a__SEP__b__SEP__c' len: 41, 8
line: '3__SEP__Lnumber 9__SEP__g__SEP__h__SEP__i' len: 41, 8
line: '2__SEP__Lnumber 5__SEP__d__SEP__e__SEP__f' len: 41, 8
line: '4__SEP__Lnumber 13__SEP__j__SEP__k__SEP__l' len: 42, 8

文件 inp.log 如下:

1
a
b
c
2
d
e
f
3
g
h
i
4
j
k
l

我能夠通過使用 par_lines() 來解決問題,如下所示:

    let tmp: Vec<_> = messages.par_lines().map(|l| proc_len(l)).collect();
...
...
...

fn proc_len(inp: &str) -> Vec<usize> {
    let vec: Vec<usize> = vec![inp.len()];
    return vec;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM