Skip to main content

OptimizationLevel

Enum OptimizationLevel 

Source
pub enum OptimizationLevel {
    Reference,
    Basic,
    Advanced,
    Maximum,
}
Expand description

Platform-specific optimization selector

This enum allows runtime selection of the best available optimization while maintaining security guarantees.

Variants§

§

Reference

Reference implementation (always available)

§

Basic

Basic SIMD optimizations (AVX2, ARMv8)

§

Advanced

Advanced SIMD optimizations (AVX-512, parallel processing)

§

Maximum

Maximum performance (all available optimizations)

Implementations§

Source§

impl OptimizationLevel

Source

pub fn best_available() -> Self

Returns the best available optimization level for the current platform

Examples found in repository?
examples/optimization_usage.rs (line 38)
19fn main() {
20    println!("=== Keccak High-Impact Optimization Example ===\n");
21
22    // 1. Feature Detection
23    println!("1. Hardware Feature Detection:");
24    let report = detection::detect_available_features();
25    println!("   {}", report.summary());
26    println!(
27        "   Recommended optimization level: {:?}",
28        report.recommended_optimization_level()
29    );
30    println!();
31
32    // 2. Basic Usage with Automatic Optimization
33    println!("2. Basic Usage with Automatic Optimization:");
34    let mut state = [0u64; 25];
35    state[0] = 0x1234567890ABCDEF;
36
37    // Use the best available optimization automatically
38    let best_level = OptimizationLevel::best_available();
39    println!("   Using optimization level: {:?}", best_level);
40
41    p1600_optimized(&mut state, best_level);
42    println!("   State[0] after permutation: 0x{:016x}", state[0]);
43    println!();
44
45    // 3. Feature Configuration Examples
46    println!("3. Feature Configuration Examples:");
47
48    // Security-optimized configuration
49    let security_config = FeatureConfig::security_optimized();
50    println!("   Security-optimized: {}", security_config.description());
51
52    // Performance-optimized configuration
53    let performance_config = FeatureConfig::performance_optimized();
54    println!(
55        "   Performance-optimized: {}",
56        performance_config.description()
57    );
58
59    // Compatibility-optimized configuration
60    let compatibility_config = FeatureConfig::compatibility_optimized();
61    println!(
62        "   Compatibility-optimized: {}",
63        compatibility_config.description()
64    );
65    println!();
66
67    // 4. Global Configuration
68    println!("4. Global Configuration:");
69    set_global_config(FeatureConfig::performance_optimized());
70    let current_config = get_global_config();
71    println!("   Current global config: {}", current_config.description());
72    println!();
73
74    // 5. Fast Loop Absorption
75    println!("5. Fast Loop Absorption:");
76    let initial_state = [0u64; 25];
77    let data = b"This is a test message for fast loop absorption. It should be processed efficiently using optimized implementations.";
78
79    for level in [
80        OptimizationLevel::Reference,
81        OptimizationLevel::Basic,
82        OptimizationLevel::Advanced,
83        OptimizationLevel::Maximum,
84    ] {
85        if level.is_available() {
86            let mut test_state = initial_state;
87            let offset = fast_loop_absorb_optimized(&mut test_state, data, level);
88            println!(
89                "   {:?}: processed {} bytes, state[0] = 0x{:016x}",
90                level, offset, test_state[0]
91            );
92        } else {
93            println!("   {:?}: not available on this platform", level);
94        }
95    }
96    println!();
97
98    // 6. Parallel Processing (if available)
99    #[cfg(all(feature = "simd", keccak_portable_simd))]
100    {
101        println!("6. Parallel Processing:");
102        let mut states = vec![[0u64; 25]; 8];
103
104        // Initialize states with different values
105        for (i, state) in states.iter_mut().enumerate() {
106            state[0] = 0x1234567890ABCDEF + i as u64;
107        }
108
109        // Process in parallel
110        parallel::p1600_parallel(&mut states, OptimizationLevel::Advanced);
111
112        println!("   Processed {} states in parallel", states.len());
113        for (i, state) in states.iter().enumerate() {
114            println!("   State[{}][0] = 0x{:016x}", i, state[0]);
115        }
116        println!();
117    }
118
119    // 7. Performance Comparison
120    println!("7. Performance Comparison:");
121    let test_data = vec![0x42u8; 1024 * 1024]; // 1MB of data
122    let mut state = [0u64; 25];
123
124    for level in [
125        OptimizationLevel::Reference,
126        OptimizationLevel::Basic,
127        OptimizationLevel::Advanced,
128        OptimizationLevel::Maximum,
129    ] {
130        if level.is_available() {
131            let start = std::time::Instant::now();
132            let offset = fast_loop_absorb_optimized(&mut state, &test_data, level);
133            let duration = start.elapsed();
134
135            println!(
136                "   {:?}: processed {} bytes in {:?} ({:.2} MB/s)",
137                level,
138                offset,
139                duration,
140                (offset as f64 / 1024.0 / 1024.0) / duration.as_secs_f64()
141            );
142        }
143    }
144    println!();
145
146    // 8. Nightly Features Usage
147    println!("8. Nightly Features Usage:");
148
149    #[cfg(all(feature = "simd", keccak_portable_simd))]
150    {
151        println!("   SIMD features enabled: ✓");
152        println!("   Portable SIMD available: ✓");
153    }
154
155    #[cfg(all(feature = "simd", not(keccak_portable_simd)))]
156    {
157        println!(
158            "   SIMD feature enabled for linkage, but portable SIMD needs a nightly toolchain"
159        );
160    }
161
162    #[cfg(not(feature = "simd"))]
163    {
164        println!("   SIMD features disabled: use --features simd to enable");
165    }
166
167    #[cfg(feature = "nightly")]
168    {
169        println!("   Nightly features enabled: ✓");
170        println!("   Advanced optimizations available: ✓");
171    }
172
173    #[cfg(not(feature = "nightly"))]
174    {
175        println!("   Nightly features disabled: use --features nightly to enable");
176    }
177    println!();
178
179    // 9. Configuration Recommendations
180    println!("9. Configuration Recommendations:");
181    let report = detection::detect_available_features();
182
183    if report.avx512f {
184        println!("   ✓ AVX-512 detected: Use OptimizationLevel::Maximum for best performance");
185    } else if report.avx2 {
186        println!("   ✓ AVX2 detected: Use OptimizationLevel::Advanced for good performance");
187    } else if report.sha3_intrinsics {
188        println!(
189            "   ✓ SHA3 intrinsics detected: Use OptimizationLevel::Basic for ARM optimization"
190        );
191    } else {
192        println!("   ⚠ No special hardware detected: Using reference implementation");
193    }
194
195    if report.simd_support {
196        println!("   ✓ SIMD support available: Enable parallel processing for batch operations");
197    }
198
199    if report.nightly_features {
200        println!("   ✓ Nightly features available: Enable advanced optimizations");
201    }
202    println!();
203
204    println!("=== Example Complete ===");
205}
Source

pub fn is_available(self) -> bool

Check if this optimization level is available on the current platform

Examples found in repository?
examples/optimization_usage.rs (line 85)
19fn main() {
20    println!("=== Keccak High-Impact Optimization Example ===\n");
21
22    // 1. Feature Detection
23    println!("1. Hardware Feature Detection:");
24    let report = detection::detect_available_features();
25    println!("   {}", report.summary());
26    println!(
27        "   Recommended optimization level: {:?}",
28        report.recommended_optimization_level()
29    );
30    println!();
31
32    // 2. Basic Usage with Automatic Optimization
33    println!("2. Basic Usage with Automatic Optimization:");
34    let mut state = [0u64; 25];
35    state[0] = 0x1234567890ABCDEF;
36
37    // Use the best available optimization automatically
38    let best_level = OptimizationLevel::best_available();
39    println!("   Using optimization level: {:?}", best_level);
40
41    p1600_optimized(&mut state, best_level);
42    println!("   State[0] after permutation: 0x{:016x}", state[0]);
43    println!();
44
45    // 3. Feature Configuration Examples
46    println!("3. Feature Configuration Examples:");
47
48    // Security-optimized configuration
49    let security_config = FeatureConfig::security_optimized();
50    println!("   Security-optimized: {}", security_config.description());
51
52    // Performance-optimized configuration
53    let performance_config = FeatureConfig::performance_optimized();
54    println!(
55        "   Performance-optimized: {}",
56        performance_config.description()
57    );
58
59    // Compatibility-optimized configuration
60    let compatibility_config = FeatureConfig::compatibility_optimized();
61    println!(
62        "   Compatibility-optimized: {}",
63        compatibility_config.description()
64    );
65    println!();
66
67    // 4. Global Configuration
68    println!("4. Global Configuration:");
69    set_global_config(FeatureConfig::performance_optimized());
70    let current_config = get_global_config();
71    println!("   Current global config: {}", current_config.description());
72    println!();
73
74    // 5. Fast Loop Absorption
75    println!("5. Fast Loop Absorption:");
76    let initial_state = [0u64; 25];
77    let data = b"This is a test message for fast loop absorption. It should be processed efficiently using optimized implementations.";
78
79    for level in [
80        OptimizationLevel::Reference,
81        OptimizationLevel::Basic,
82        OptimizationLevel::Advanced,
83        OptimizationLevel::Maximum,
84    ] {
85        if level.is_available() {
86            let mut test_state = initial_state;
87            let offset = fast_loop_absorb_optimized(&mut test_state, data, level);
88            println!(
89                "   {:?}: processed {} bytes, state[0] = 0x{:016x}",
90                level, offset, test_state[0]
91            );
92        } else {
93            println!("   {:?}: not available on this platform", level);
94        }
95    }
96    println!();
97
98    // 6. Parallel Processing (if available)
99    #[cfg(all(feature = "simd", keccak_portable_simd))]
100    {
101        println!("6. Parallel Processing:");
102        let mut states = vec![[0u64; 25]; 8];
103
104        // Initialize states with different values
105        for (i, state) in states.iter_mut().enumerate() {
106            state[0] = 0x1234567890ABCDEF + i as u64;
107        }
108
109        // Process in parallel
110        parallel::p1600_parallel(&mut states, OptimizationLevel::Advanced);
111
112        println!("   Processed {} states in parallel", states.len());
113        for (i, state) in states.iter().enumerate() {
114            println!("   State[{}][0] = 0x{:016x}", i, state[0]);
115        }
116        println!();
117    }
118
119    // 7. Performance Comparison
120    println!("7. Performance Comparison:");
121    let test_data = vec![0x42u8; 1024 * 1024]; // 1MB of data
122    let mut state = [0u64; 25];
123
124    for level in [
125        OptimizationLevel::Reference,
126        OptimizationLevel::Basic,
127        OptimizationLevel::Advanced,
128        OptimizationLevel::Maximum,
129    ] {
130        if level.is_available() {
131            let start = std::time::Instant::now();
132            let offset = fast_loop_absorb_optimized(&mut state, &test_data, level);
133            let duration = start.elapsed();
134
135            println!(
136                "   {:?}: processed {} bytes in {:?} ({:.2} MB/s)",
137                level,
138                offset,
139                duration,
140                (offset as f64 / 1024.0 / 1024.0) / duration.as_secs_f64()
141            );
142        }
143    }
144    println!();
145
146    // 8. Nightly Features Usage
147    println!("8. Nightly Features Usage:");
148
149    #[cfg(all(feature = "simd", keccak_portable_simd))]
150    {
151        println!("   SIMD features enabled: ✓");
152        println!("   Portable SIMD available: ✓");
153    }
154
155    #[cfg(all(feature = "simd", not(keccak_portable_simd)))]
156    {
157        println!(
158            "   SIMD feature enabled for linkage, but portable SIMD needs a nightly toolchain"
159        );
160    }
161
162    #[cfg(not(feature = "simd"))]
163    {
164        println!("   SIMD features disabled: use --features simd to enable");
165    }
166
167    #[cfg(feature = "nightly")]
168    {
169        println!("   Nightly features enabled: ✓");
170        println!("   Advanced optimizations available: ✓");
171    }
172
173    #[cfg(not(feature = "nightly"))]
174    {
175        println!("   Nightly features disabled: use --features nightly to enable");
176    }
177    println!();
178
179    // 9. Configuration Recommendations
180    println!("9. Configuration Recommendations:");
181    let report = detection::detect_available_features();
182
183    if report.avx512f {
184        println!("   ✓ AVX-512 detected: Use OptimizationLevel::Maximum for best performance");
185    } else if report.avx2 {
186        println!("   ✓ AVX2 detected: Use OptimizationLevel::Advanced for good performance");
187    } else if report.sha3_intrinsics {
188        println!(
189            "   ✓ SHA3 intrinsics detected: Use OptimizationLevel::Basic for ARM optimization"
190        );
191    } else {
192        println!("   ⚠ No special hardware detected: Using reference implementation");
193    }
194
195    if report.simd_support {
196        println!("   ✓ SIMD support available: Enable parallel processing for batch operations");
197    }
198
199    if report.nightly_features {
200        println!("   ✓ Nightly features available: Enable advanced optimizations");
201    }
202    println!();
203
204    println!("=== Example Complete ===");
205}

Trait Implementations§

Source§

impl Clone for OptimizationLevel

Source§

fn clone(&self) -> OptimizationLevel

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for OptimizationLevel

Source§

impl Debug for OptimizationLevel

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for OptimizationLevel

Source§

impl PartialEq for OptimizationLevel

Source§

fn eq(&self, other: &OptimizationLevel) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for OptimizationLevel

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.