[−][src]Crate complexity
Calculate cognitive complexity of Rust code.
Based on Cognitive Complexity by G. Ann Campbell.
Examples
Loops and branching increment the complexity by one each. Additionally,
continue
and break
statements increment the complexity by one.
use complexity::Complexity; use syn::{ItemFn, parse_str}; let code = r#" fn sum_of_primes(max: u64) -> u64 { let mut total = 0; 'outer: for i in 1..=max { for j in 2..i { if i % j == 0 { continue 'outer; } } total += i; } }"#; let func: ItemFn = parse_str(code)?; assert_eq!(func.complexity(), 7);
However, a match
only increases the complexity by one no matter how many
branches there are.
use complexity::Complexity; use syn::{ItemFn, parse_str}; let code = r#" fn get_words(number: u64) -> &'static str { match number { 1 => "one", 2 => "a couple", 3 => "a few", _ => "lots", } }"#; let func: ItemFn = parse_str(code)?; assert_eq!(func.complexity(), 1);
Traits
Complexity | A trait for calculating the cognitive complexity of a Rust type. |