From f7a74646410e7afafda66e8e576d16f1a30ea6cc Mon Sep 17 00:00:00 2001 From: TrAyZeN <1810leo@gmail.com> Date: Fri, 29 Mar 2024 11:16:36 +0100 Subject: [PATCH] Fix clippy warnings --- src/cpa.rs | 28 ++++++++++++++-------------- src/cpa_normal.rs | 4 ++-- src/preprocessors.rs | 27 ++++++++++++--------------- src/quicklog.rs | 24 +++++++++++++++++------- src/trace.rs | 2 +- src/util.rs | 10 +++------- 6 files changed, 49 insertions(+), 46 deletions(-) diff --git a/src/cpa.rs b/src/cpa.rs index 2f8d6a5..6bd2eba 100644 --- a/src/cpa.rs +++ b/src/cpa.rs @@ -30,8 +30,8 @@ impl Cpa { Self { len_samples: size, a_l: Array2::zeros((guess_range as usize, size)), - target_byte: target_byte, - guess_range: guess_range, + target_byte, + guess_range, sum_leakages: Array1::zeros(size), sig_leakages: Array1::zeros(size), sum_keys: Array1::zeros(guess_range as usize), @@ -56,24 +56,24 @@ impl Cpa { pub fn gen_values(&mut self, metadata: Array1, _guess_range: i32, _target_key: i32) { for guess in 0.._guess_range { self.values[guess as usize] = - (self.leakage_func)(metadata[_target_key as usize], guess as usize) as usize; + (self.leakage_func)(metadata[_target_key as usize], guess as usize); } } pub fn go(&mut self, _trace: Array1, metadata: Array1, _guess_range: i32) { for i in 0..self.len_samples { - self.sum_leakages[i] += _trace[i] as usize; - self.sig_leakages[i] += (_trace[i] * _trace[i]) as usize; + self.sum_leakages[i] += _trace[i]; + self.sig_leakages[i] += _trace[i] * _trace[i]; } for guess in 0.._guess_range { - self.sum_keys[guess as usize] += self.values[guess as usize] as usize; + self.sum_keys[guess as usize] += self.values[guess as usize]; self.sig_keys[guess as usize] += - (self.values[guess as usize] * self.values[guess as usize]) as usize; + self.values[guess as usize] * self.values[guess as usize]; } - let partition: usize = metadata[self.target_byte as usize] as usize; + let partition: usize = metadata[self.target_byte as usize]; for i in 0..self.len_samples { - self.a_l[[partition, i]] += _trace[i] as usize; + self.a_l[[partition, i]] += _trace[i]; } } @@ -86,21 +86,20 @@ impl Cpa { Array2::zeros((shape_p, shape_p)); for i in 0..self.guess_range { for x in 0..self.guess_range { - p[[x as usize, i as usize]] = (self.leakage_func)(x as usize, i as usize) as usize; + p[[x as usize, i as usize]] = (self.leakage_func)(x as usize, i as usize); } } for i in 0..self.guess_range { let _sigkeys = self.sig_keys[i as usize] as f32 / self.len_leakages as f32; let _sumkeys = self.sum_keys[i as usize] as f32 / self.len_leakages as f32; let lower1: f32 = _sigkeys - (_sumkeys * _sumkeys); + /* Parallel operation using multi-threading */ let tmp: Vec = (0..self.len_samples) .into_par_iter() .map(|x| { - let _sumleakages = - self.sum_leakages[x as usize] as f32 / self.len_leakages as f32; - let _sigleakages = - self.sig_leakages[x as usize] as f32 / self.len_leakages as f32; + let _sumleakages = self.sum_leakages[x] as f32 / self.len_leakages as f32; + let _sigleakages = self.sig_leakages[x] as f32 / self.len_leakages as f32; let slice_a = self.a_l.slice(s![.., x]); let slice_b = p.slice(s![.., i]); let summult: i32 = self.sum_mult(slice_a, slice_b); @@ -112,6 +111,7 @@ impl Cpa { }) .collect(); + #[allow(clippy::needless_range_loop)] for z in 0..self.len_samples { self.corr[[i as usize, z]] = tmp[z]; } diff --git a/src/cpa_normal.rs b/src/cpa_normal.rs index 853cb90..f32331b 100644 --- a/src/cpa_normal.rs +++ b/src/cpa_normal.rs @@ -32,7 +32,7 @@ impl Cpa { Self { len_samples: size, chunk: patch, - guess_range: guess_range, + guess_range, sum_leakages: Array1::zeros(size), sum2_leakages: Array1::zeros(size), sum_keys: Array1::zeros(guess_range as usize), @@ -133,7 +133,7 @@ impl Cpa { let denominator_2: f32 = std_leakages[x] - (avg_leakages[x] * avg_leakages[x]); if numerator != 0.0 { - self.corr[[i as usize, x]] = + self.corr[[i, x]] = f32::abs(numerator / f32::sqrt(denominator_1 * denominator_2)); } } diff --git a/src/preprocessors.rs b/src/preprocessors.rs index 460ee0b..4ee7160 100644 --- a/src/preprocessors.rs +++ b/src/preprocessors.rs @@ -6,7 +6,7 @@ use crate::processors::MeanVar; /// Computes the centered product of "order" leakage samples /// Used particularly when performing high-order SCA -struct CenteredProduct { +pub struct CenteredProduct { /// Sum of traces acc: Array1, /// Number of traces processed @@ -30,7 +30,7 @@ impl CenteredProduct { Self { acc: Array1::zeros(size), count: 0, - intervals: intervals, + intervals, processed: false, mean: Array1::zeros(size), } @@ -58,13 +58,13 @@ impl CenteredProduct { /// The centered product substract the mean of the traces and then perform products between every input time samples pub fn apply + Copy>(&mut self, trace: &ArrayView1) -> Array1 { // First we substract the mean trace - let centered_trace: Array1 = trace.mapv(|x| f64::from(x.into())) - &self.mean; + let centered_trace: Array1 = trace.mapv(|x| x.into()) - &self.mean; let length_out_trace: usize = self.intervals.iter().map(|x| x.len()).product(); let mut centered_product_trace = Array1::ones(length_out_trace); // Then we do the products - let mut multi_prod = (0..self.intervals.len()) + let multi_prod = (0..self.intervals.len()) .map(|i| self.intervals[i].clone()) .multi_cartesian_product(); //NOTE/TODO: maybe this can go in the struct parameters, which could improve performances @@ -75,12 +75,13 @@ impl CenteredProduct { } } println! {"{:?}",centered_product_trace}; - return centered_product_trace; + + centered_product_trace } } /// Elevates parts of a trace to a certain power -struct Power { +pub struct Power { intervals: Vec>, power: i32, } @@ -90,14 +91,10 @@ impl Power { /// /// # Arguments /// - /// * `size` - Number of samples per trace /// * `intervals` - Intervals to elevate to the power /// * `power` - Power to elevate - pub fn new(size: usize, intervals: Vec>, power: i32) -> Self { - Self { - intervals: intervals, - power: power, - } + pub fn new(intervals: Vec>, power: i32) -> Self { + Self { intervals, power } } /// Processes an input trace @@ -115,7 +112,7 @@ impl Power { } /// Standardization of the traces by removing the mean and scaling to unit variance -struct StandardScaler { +pub struct StandardScaler { /// meanVar processor meanvar: MeanVar, /// mean @@ -146,7 +143,7 @@ impl StandardScaler { /// Apply the processing to an input trace pub fn apply + Copy>(&mut self, trace: &ArrayView1) -> Array1 { - (trace.mapv(|x| f64::from(x.into())) - &self.mean) / &self.std + (trace.mapv(|x| x.into()) - &self.mean) / &self.std } } @@ -159,7 +156,7 @@ mod tests { use ndarray::array; fn round_to_2_digits(x: f64) -> f64 { - return (x * 100 as f64).round() / 100 as f64; + (x * 100f64).round() / 100f64 } #[test] diff --git a/src/quicklog.rs b/src/quicklog.rs index 2e13424..a983f6d 100644 --- a/src/quicklog.rs +++ b/src/quicklog.rs @@ -2,13 +2,11 @@ use ndarray::Array1; use npyz::{Deserialize, NpyFile}; -use serde_json::map::IntoIter; use std::{ fs::File, - io::{BufRead, BufReader, Error, Lines, Seek, SeekFrom}, + io::{BufRead, BufReader, Lines, Seek, SeekFrom}, marker::PhantomData, path::Path, - time::Instant, }; use crate::{trace::Trace, util::read_array_1_from_npy_file}; @@ -99,6 +97,7 @@ impl Log { } /// Returns the number of records in the log + #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> usize { self.records.len() } @@ -180,7 +179,7 @@ impl Record { let buf = BufReader::new(f); let npy = NpyFile::new(buf).unwrap(); Ok(read_array_1_from_npy_file(npy)) - } else if let Some(tid) = self.tid() { + } else if let Some(_tid) = self.tid() { // Trace is stored in a single file todo!() } else { @@ -254,7 +253,6 @@ impl CachedLoader { self.current_path = Some(path) } let toff = record.toff(); - let start = Instant::now(); let chunk = &self.current_data.as_slice()[toff as usize..]; let npy = NpyFile::new(chunk).unwrap(); Ok(read_array_1_from_npy_file(npy)) @@ -264,6 +262,12 @@ impl CachedLoader { } } +impl Default for CachedLoader { + fn default() -> Self { + Self::new() + } +} + /// Holds a trace batch file content and an offset list in the file, plus the /// data associated to each trace. /// @@ -275,7 +279,7 @@ pub struct Batch { } impl Batch { - fn new() -> Self { + pub fn new() -> Self { Self { file: Vec::new(), toffs_and_values: Vec::new(), @@ -284,6 +288,12 @@ impl Batch { } } +impl Default for Batch { + fn default() -> Self { + Self::new() + } +} + impl IntoIterator for Batch { type Item = Trace; @@ -403,7 +413,7 @@ impl Iterator for BatchTraceIterator { } pub fn array_from_bytes(bytes: &[u8], toff: usize) -> Array1 { - let chunk = &bytes[toff as usize..]; + let chunk = &bytes[toff..]; let npy = NpyFile::new(chunk).unwrap(); read_array_1_from_npy_file(npy) } diff --git a/src/trace.rs b/src/trace.rs index 079bbb8..dec2352 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -1,5 +1,4 @@ //! Defines the [`Trace`] storage structure. - use ndarray::Array1; /// A side channel leakage record associated to its leakage data. @@ -18,6 +17,7 @@ impl Trace { } /// Returns the number of points in the leakage waveform. + #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> usize { self.leakage.len() } diff --git a/src/util.rs b/src/util.rs index b654698..f61d438 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,15 +1,11 @@ //! Convenient utility functions. -use std::{ - fs::File, - io::{self, BufWriter}, - time::Duration, -}; +use std::{fs::File, io::BufWriter, time::Duration}; use indicatif::{ProgressBar, ProgressStyle}; use ndarray::{Array, Array1, Array2, ArrayView2}; use ndarray_npy::{write_npy, ReadNpyExt, ReadableElement, WriteNpyExt}; -use npyz::{Deserialize, NpyFile, WriterBuilder}; +use npyz::{Deserialize, NpyFile}; /// Reads a [`NpyFile`] as a [`Array1`] /// @@ -19,7 +15,7 @@ use npyz::{Deserialize, NpyFile, WriterBuilder}; pub fn read_array_1_from_npy_file(npy: NpyFile) -> Array1 { let mut v: Vec = Vec::new(); v.reserve_exact(npy.shape()[0] as usize); - v.extend(npy.data().unwrap().into_iter().map(|x| x.unwrap())); + v.extend(npy.data().unwrap().map(|x| x.unwrap())); Array::from_vec(v) }