meta_client/client/load_balance.rs
1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use rand::Rng;
16
17pub fn random_get<T, F>(len: usize, func: F) -> Option<T>
18where
19 F: FnOnce(usize) -> Option<T>,
20{
21 if len == 0 {
22 return None;
23 }
24
25 let mut rng = rand::rng();
26 let i = rng.random_range(0..len);
27
28 func(i)
29}
30
31#[cfg(test)]
32mod tests {
33 use super::*;
34
35 #[test]
36 fn test_random_get() {
37 for i in 1..100 {
38 let res = random_get(i, |index| Some(2 * index));
39 assert!(res.unwrap() < 2 * i);
40 }
41 }
42
43 #[test]
44 fn test_random_get_none() {
45 let res = random_get(0, |index| Some(2 * index));
46 assert!(res.is_none());
47 }
48}