Skip to main content

kvbm_config/
rayon.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Rayon thread pool configuration.
5
6use serde::{Deserialize, Serialize};
7use validator::Validate;
8
9/// Rayon thread pool configuration.
10#[derive(Debug, Clone, Default, Serialize, Deserialize, Validate)]
11pub struct RayonConfig {
12    /// Number of threads in the Rayon thread pool.
13    /// If None, uses the number of logical CPUs.
14    #[validate(range(min = 1))]
15    pub num_threads: Option<usize>,
16}
17
18#[cfg(feature = "rayon")]
19impl RayonConfig {
20    /// Build a Rayon thread pool from this configuration.
21    pub fn build_pool(&self) -> Result<::rayon::ThreadPool, ::rayon::ThreadPoolBuildError> {
22        let mut builder = ::rayon::ThreadPoolBuilder::new();
23
24        if let Some(threads) = self.num_threads {
25            builder = builder.num_threads(threads);
26        }
27
28        builder.build()
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35
36    #[test]
37    fn test_default_config() {
38        let config = RayonConfig::default();
39        assert!(config.num_threads.is_none());
40    }
41
42    #[cfg(feature = "rayon")]
43    #[test]
44    fn test_build_pool() {
45        let config = RayonConfig {
46            num_threads: Some(2),
47        };
48        let pool = config.build_pool().expect("Failed to build pool");
49        assert_eq!(pool.current_num_threads(), 2);
50    }
51}