|
| 1 | +use num_cpus; |
| 2 | + |
| 3 | +/// Gets the number of threads the extractor should use. |
| 4 | +/// This is controlled by the CODEQL_THREADS environment variable. |
| 5 | +pub fn num_threads() -> Result<usize, String> { |
| 6 | + let threads_str = std::env::var("CODEQL_THREADS").unwrap_or_else(|_| "-1".into()); |
| 7 | + let num_cpus = num_cpus::get(); |
| 8 | + parse_codeql_threads(&threads_str, num_cpus) |
| 9 | + .ok_or_else(|| format!("Unable to parse CODEQL_THREADS value '{}'", &threads_str)) |
| 10 | +} |
| 11 | + |
| 12 | +/// Parses the given string to determine the number of threads the extractor |
| 13 | +/// should use, as described in the extractor spec: |
| 14 | +/// |
| 15 | +/// "If the number is positive, it indicates the number of threads that should |
| 16 | +/// be used. If the number is negative or zero, it should be added to the number |
| 17 | +/// of cores available on the machine to determine how many threads to use |
| 18 | +/// (minimum of 1). If unspecified, should be considered as set to -1." |
| 19 | +/// |
| 20 | +/// # Examples |
| 21 | +/// |
| 22 | +/// ``` |
| 23 | +/// use codeql_extractor::options::parse_codeql_threads; |
| 24 | +/// |
| 25 | +/// assert_eq!(parse_codeql_threads("1", 4), Some(1)); |
| 26 | +/// assert_eq!(parse_codeql_threads("5", 4), Some(5)); |
| 27 | +/// assert_eq!(parse_codeql_threads("0", 4), Some(4)); |
| 28 | +/// assert_eq!(parse_codeql_threads("-1", 4), Some(3)); |
| 29 | +/// assert_eq!(parse_codeql_threads("-3", 4), Some(1)); |
| 30 | +/// assert_eq!(parse_codeql_threads("-4", 4), Some(1)); |
| 31 | +/// assert_eq!(parse_codeql_threads("-5", 4), Some(1)); |
| 32 | +/// assert_eq!(parse_codeql_threads("nope", 4), None); |
| 33 | +/// ``` |
| 34 | +pub fn parse_codeql_threads(threads_str: &str, num_cpus: usize) -> Option<usize> { |
| 35 | + match threads_str.parse::<i32>() { |
| 36 | + Ok(num) if num <= 0 => { |
| 37 | + let reduction = num.abs_diff(0) as usize; |
| 38 | + Some(std::cmp::max(1, num_cpus.saturating_sub(reduction))) |
| 39 | + } |
| 40 | + Ok(num) => Some(num as usize), |
| 41 | + |
| 42 | + Err(_) => None, |
| 43 | + } |
| 44 | +} |
0 commit comments