1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 use std::collections::{HashMap, HashSet};
15
16 /// SDV test cases for par_iter
17 ///
18 /// # Brief
19 /// 1. Creates a parallel iterator and adds elements together.
20 /// 2. Checks the correctness of the answer.
21 use ylong_runtime::iter::prelude::*;
22 #[test]
sdv_par_iter_test()23 fn sdv_par_iter_test() {
24 let fut = async {
25 let a = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
26 let b = vec![2, 3, 4, 5];
27
28 let sum = a
29 .par_iter()
30 .map(|x| *x + 1)
31 .filter(|x| *x < 5)
32 .zip(b.par_iter())
33 .map(|x| x.0 * (*x.1))
34 .sum()
35 .await
36 .unwrap();
37 assert_eq!(sum, 29);
38
39 let s = a.iter().copied().collect::<HashSet<i32>>();
40 let sum = s.into_par_iter().sum().await.unwrap();
41 assert_eq!(sum, 55);
42
43 let m = a
44 .iter()
45 .zip(b.iter())
46 .map(|x| (*x.0, *x.1))
47 .collect::<HashMap<i32, i32>>();
48 let sum = m.into_par_iter().map(|x| x.0 * x.1).sum().await.unwrap();
49 assert_eq!(sum, 40);
50
51 let sum = a
52 .into_par_iter()
53 .map(|x| x + 1)
54 .filter(|x| *x < 5)
55 .zip(b.into_par_iter())
56 .map(|x| x.0 * x.1)
57 .sum()
58 .await
59 .unwrap();
60 assert_eq!(sum, 29);
61 };
62 ylong_runtime::block_on(fut);
63 }
64