diff --git a/delsum-lib/src/checksum.rs b/delsum-lib/src/checksum.rs index 830f20c..f3bf3f9 100644 --- a/delsum-lib/src/checksum.rs +++ b/delsum-lib/src/checksum.rs @@ -229,7 +229,7 @@ fn find_segments_aligned( presums( summer, b, - &s, + s, // since they are already normalized, this should work start_range.to_unsigned(b.len()).unwrap(), end_range.to_unsigned(b.len()).unwrap(), @@ -358,7 +358,7 @@ fn presums( // from the startsums, we substract the init value of the checksum start_presums.push(summer.add(state.clone(), &neg_init)); } - state = summer.dig_word(state, c as u64); + state = summer.dig_word(state, c); if end_range.contains(i + step - 1) { // from the endsums, we finalize them and subtract the given final sum let endstate = summer.add(summer.finalize(state.clone()), &summer.negate(sum.clone())); @@ -427,7 +427,7 @@ impl PresumSet { // get a permutation vector representing the sort of the presum arrays first by value and then by index #[cfg(feature = "parallel")] - idxvec.par_sort_unstable_by(|a, b| Self::cmp_idx(&presum, *a, &presum, *b).then(a.cmp(&b))); + idxvec.par_sort_unstable_by(|a, b| Self::cmp_idx(&presum, *a, &presum, *b).then(a.cmp(b))); #[cfg(not(feature = "parallel"))] idxvec.sort_unstable_by(|a, b| Self::cmp_idx(&presum, *a, &presum, *b).then(a.cmp(&b))); Self { @@ -638,7 +638,7 @@ nie gefühlten, leichten, dumpfen Schmerz zu fühlen begann. let sum_1_9_1 = chk.digest(&b"12345678987654321"[..]).unwrap(); assert_eq!( chk.find_segments( - &[Vec::from(&"a123456789X1235H123456789Y"[..])], + &[Vec::from("a123456789X1235H123456789Y")], &[sum_1_9.clone()], Relativity::Start ), @@ -647,8 +647,8 @@ nie gefühlten, leichten, dumpfen Schmerz zu fühlen begann. assert_eq!( chk.find_segments( &[ - Vec::from(&"XX98765432123456789XXX"[..]), - Vec::from(&"XX12345678987654321XX"[..]) + Vec::from("XX98765432123456789XXX"), + Vec::from("XX12345678987654321XX") ], &[sum_1_9.clone(), sum_9_1.clone()], Relativity::Start @@ -818,7 +818,7 @@ nie gefühlten, leichten, dumpfen Schmerz zu fühlen begann. } ret.push(cur_file); } - ret.sort_by(|a, b| a.len().cmp(&b.len()).then(a.cmp(&b)).reverse()); + ret.sort_by(|a, b| a.len().cmp(&b.len()).then(a.cmp(b)).reverse()); ReverseFileSet(ret) } fn shrink(&self) -> Box> { @@ -856,7 +856,7 @@ nie gefühlten, leichten, dumpfen Schmerz zu fühlen begann. has_appeared = true; } for (file, original_check) in &chk_files { - let checksum = modsum_loop.to_bytes(modsum_loop.digest(*file).unwrap()); + let checksum = modsum_loop.to_bytes(modsum_loop.digest(file).unwrap()); if &checksum != original_check { eprint!("expected checksum: "); for x in original_check { diff --git a/delsum-lib/src/crc/mod.rs b/delsum-lib/src/crc/mod.rs index e3d03e7..0520d19 100644 --- a/delsum-lib/src/crc/mod.rs +++ b/delsum-lib/src/crc/mod.rs @@ -27,7 +27,7 @@ use std::str::FromStr; /// For more information on the parameters (and CRCs in general), see "A PAINLESS GUIDE CRC ERROR DETECTION ALGORITHMS" /// or https://reveng.sourceforge.io/crc-catalogue/legend.htm (which is also a source of parameters for various common algorithms) #[derive(Clone, Debug)] -pub struct CRCBuilder { +pub struct CrcBuilder { width: Option, poly: Option, init: Option, @@ -41,7 +41,7 @@ pub struct CRCBuilder { name: Option, } -impl CRCBuilder { +impl CrcBuilder { /// Sets the poly, mandatory pub fn poly(&mut self, p: Sum) -> &mut Self { self.poly = Some(p); @@ -212,8 +212,8 @@ impl Display for CRC { impl CRC { /// Construct a new CRC from parameters, see also the documentation for CRCBuilder. - pub fn with_options() -> CRCBuilder { - CRCBuilder { + pub fn with_options() -> CrcBuilder { + CrcBuilder { poly: None, init: None, xorout: None, @@ -265,9 +265,9 @@ impl CRC { } } } -impl FromStr for CRCBuilder { +impl FromStr for CrcBuilder { /// See documentation of Fromstr on CRC - fn from_str(s: &str) -> Result, CheckBuilderErr> { + fn from_str(s: &str) -> Result, CheckBuilderErr> { let mut crc = CRC::::with_options(); for x in KeyValIter::new(s) { let (current_key, current_val) = match x { @@ -312,7 +312,7 @@ impl FromStr for CRC { /// /// Note: the `residue` parameter is currently ignored. fn from_str(s: &str) -> Result, CheckBuilderErr> { - CRCBuilder::::from_str(s)?.build() + CrcBuilder::::from_str(s)?.build() } type Err = CheckBuilderErr; } diff --git a/delsum-lib/src/crc/rev.rs b/delsum-lib/src/crc/rev.rs index bc36043..cf21c28 100644 --- a/delsum-lib/src/crc/rev.rs +++ b/delsum-lib/src/crc/rev.rs @@ -10,7 +10,7 @@ //! //! If `init` is not known, it is neccessary to know two checksums of files with different lengths. //! In case only checksums of files with a set length are required, setting `init = 0` is sufficient. -use super::{CRCBuilder, CRC}; +use super::{CrcBuilder, CRC}; use crate::checksum::CheckReverserError; use crate::endian::{bytes_to_int, int_to_bytes, wordspec_combos, Endian, WordSpec}; use crate::utils::{cart_prod, unresult_iter}; @@ -28,7 +28,7 @@ use std::pin::Pin; /// /// The `width` parameter of the builder has to be set. pub fn reverse_crc<'a>( - spec: &CRCBuilder, + spec: &CrcBuilder, chk_bytes: &'a [(&[u8], Vec)], verbosity: u64, extended_search: bool, @@ -39,7 +39,7 @@ pub fn reverse_crc<'a>( let ref_combinations: Vec<_> = discrete_combos(&spec, extended_search); ref_combinations .into_iter() - .map(move |((refin, refout), wordspec)| { + .flat_map(move |((refin, refout), wordspec)| { unresult_iter(reverse( &spec, files.clone(), @@ -49,7 +49,6 @@ pub fn reverse_crc<'a>( wordspec, )) }) - .flatten() .filter_map(|x| { // .transpose() but for Err match x { @@ -63,7 +62,7 @@ pub fn reverse_crc<'a>( /// Parallel version of reverse_crc. #[cfg(feature = "parallel")] pub fn reverse_crc_para<'a>( - spec: &CRCBuilder, + spec: &CrcBuilder, chk_bytes: &'a [(&[u8], Vec)], verbosity: u64, extended_search: bool, @@ -95,7 +94,7 @@ pub fn reverse_crc_para<'a>( // find all combinations of refin, refout and wordspecs using all values when a parameter is not given fn discrete_combos( - spec: &CRCBuilder, + spec: &CrcBuilder, extended_search: bool, ) -> Vec<((bool, bool), WordSpec)> { let width = spec.width.expect("Missing width argument"); @@ -112,7 +111,7 @@ fn discrete_combos( vec![refin] } }); - let input_endian = spec.input_endian.or_else(|| { + let input_endian = spec.input_endian.or({ Some(match refin { // big if true since for little, it is equivalent to wordsize=8 which is the same as big true => Endian::Big, @@ -135,7 +134,7 @@ fn discrete_combos( // wrapper to call rev_from_polys with polynomial arguments fn reverse<'a>( - spec: &CRCBuilder, + spec: &CrcBuilder, chk_bytes: Vec<(&'a [u8], Vec)>, verbosity: u64, refin: bool, @@ -179,7 +178,7 @@ fn reverse<'a>( None => return Err(None), }; // sort by reverse file length - polys.sort_by(|(fa, la), (fb, lb)| la.cmp(&lb).then(deg(fa).cmp(°(fb)).reverse())); + polys.sort_by(|(fa, la), (fb, lb)| la.cmp(lb).then(deg(fa).cmp(°(fb)).reverse())); // convert parameters to polynomials let revinfo = RevInfo::from_builder(spec, refin, refout, wordspec); rev_from_polys(&revinfo, &polys, verbosity).map(|x| x.iter()) @@ -199,7 +198,7 @@ impl RevInfo { // this is responsible for converting integer values to polynomial values // and returning a RevInfo that can be used for further reversing fn from_builder( - spec: &CRCBuilder, + spec: &CrcBuilder, refin: bool, refout: bool, wordspec: WordSpec, @@ -250,33 +249,29 @@ impl RevResult { refout, wordspec, } = self; - polys - .into_iter() - .map(move |pol| { - // for each polynomial of degree width, iterate over all solutions of the PrefactorMod - inits - .iter_inits(&pol, &xorout) - .map(move |(poly_p, init_p, xorout_p)| { - // convert polynomial parameters to a CRC - let poly = - poly_to_u128(&add(&poly_p, &new_poly_shifted(&[1], width as i64))); - let init = poly_to_u128(&init_p); - let xorout = cond_reverse(width as u8, poly_to_u128(&xorout_p), refout); - CRC::::with_options() - .width(width) - .poly(poly) - .init(init) - .xorout(xorout) - .refin(refin) - .refout(refout) - .inendian(wordspec.input_endian) - .outendian(wordspec.output_endian) - .wordsize(wordspec.wordsize) - .build() - .unwrap() - }) - }) - .flatten() + polys.into_iter().flat_map(move |pol| { + // for each polynomial of degree width, iterate over all solutions of the PrefactorMod + inits + .iter_inits(&pol, &xorout) + .map(move |(poly_p, init_p, xorout_p)| { + // convert polynomial parameters to a CRC + let poly = poly_to_u128(&add(&poly_p, &new_poly_shifted(&[1], width as i64))); + let init = poly_to_u128(&init_p); + let xorout = cond_reverse(width as u8, poly_to_u128(&xorout_p), refout); + CRC::::with_options() + .width(width) + .poly(poly) + .init(init) + .xorout(xorout) + .refin(refin) + .refout(refout) + .inendian(wordspec.input_endian) + .outendian(wordspec.output_endian) + .wordsize(wordspec.wordsize) + .build() + .unwrap() + }) + }) } } @@ -354,7 +349,7 @@ fn rev_from_polys( .collect(); if let Some(init) = &spec.init { log("removing inits"); - remove_inits(&init, &mut polys); + remove_inits(init, &mut polys); } log("removing xorouts"); let (polys, mut xorout) = remove_xorouts(&spec.xorout, polys); @@ -417,7 +412,7 @@ fn remove_xorouts( // if we already have xorout, we can subtract it from the files themselves so // that we have one more to get parameters from ret_vec.push((add(&prev.0, xorout), prev.1)); - (copy_poly(&xorout), InitPlace::None) + (copy_poly(xorout), InitPlace::None) } None => (copy_poly(&prev.0), prev.1), }; @@ -596,7 +591,7 @@ impl MemoPower { fn new(hull: &Poly) -> Self { MemoPower { prev_power: 0, - prev_ppoly: new_polyrem(&new_poly(&[1]), &hull), + prev_ppoly: new_polyrem(&new_poly(&[1]), hull), init_fac: new_zero(), hull: copy_poly(hull), } @@ -628,7 +623,7 @@ impl MemoPower { } fn update_hull(&mut self, hull: &Poly) { self.hull = copy_poly(hull); - self.prev_ppoly = new_polyrem(&self.prev_ppoly.rep(), &hull) + self.prev_ppoly = new_polyrem(&self.prev_ppoly.rep(), hull) } } // describes a set of solutions for unknown*possible % hull @@ -656,7 +651,7 @@ impl PrefactorMod { PrefactorMod { unknown, possible, - hull: copy_poly(&hull), + hull: copy_poly(hull), } } @@ -809,10 +804,7 @@ fn find_init( for (p, l) in polys { power.update_init_fac(&l); let file_solutions = PrefactorMod::new_file(p, &mut power, hull.as_mut()); - ret = match file_solutions - .map(|f| ret.merge(f, hull.as_mut())) - .flatten() - { + ret = match file_solutions.and_then(|f| ret.merge(f, hull.as_mut())) { Some(valid) => valid, None => return PrefactorMod::empty(), } @@ -869,7 +861,7 @@ fn find_prod_comb( break; } ret[inc_deg].push(copy_poly(&q)); - for (j, el) in retcopy[0..=width as usize - inc_deg].iter().enumerate() { + for (j, el) in retcopy[0..=width - inc_deg].iter().enumerate() { for m in el { ret[j + inc_deg].push(mul(&q, m)); } @@ -890,7 +882,7 @@ fn bytes_to_poly( ) -> Option { let new_bytes = reorder_poly_bytes(bytes, refin, wordspec); let mut poly = new_poly_shifted(&new_bytes, width as i64); - let sum = bytes_to_int(&checksum, wordspec.output_endian); + let sum = bytes_to_int(checksum, wordspec.output_endian); let check_mask = 1u128.checked_shl(width as u32).unwrap_or(0).wrapping_sub(1); if (!check_mask & sum) != 0 { return None; @@ -904,7 +896,7 @@ fn reorder_poly_bytes(bytes: &[u8], refin: bool, wordspec: WordSpec) -> Vec wordspec .iter_words(bytes) .rev() - .map(|n| { + .flat_map(|n| { let n_ref = if refin { n.reverse_bits() >> (64 - wordspec.wordsize) } else { @@ -912,7 +904,6 @@ fn reorder_poly_bytes(bytes: &[u8], refin: bool, wordspec: WordSpec) -> Vec }; int_to_bytes(n_ref, Endian::Little, wordspec.wordsize) }) - .flatten() .collect() } @@ -939,9 +930,9 @@ fn poly_to_u128(poly: &Poly) -> u128 { mod tests { use super::*; use crate::checksum::tests::ReverseFileSet; - use crate::crc::{CRCBuilder, CRC}; + use crate::crc::{CrcBuilder, CRC}; use quickcheck::{Arbitrary, Gen, TestResult}; - impl Arbitrary for CRCBuilder { + impl Arbitrary for CrcBuilder { fn arbitrary(g: &mut Gen) -> Self { let width = (u8::arbitrary(g) % 128) + 1; let poly; @@ -976,7 +967,7 @@ mod tests { #[quickcheck] fn qc_crc_rev( files: ReverseFileSet, - crc_build: CRCBuilder, + crc_build: CrcBuilder, known: (bool, bool, bool, bool, bool), wordspec_known: (bool, bool), ) -> TestResult { diff --git a/delsum-lib/src/endian.rs b/delsum-lib/src/endian.rs index c0542f8..cc78765 100644 --- a/delsum-lib/src/endian.rs +++ b/delsum-lib/src/endian.rs @@ -43,8 +43,8 @@ pub(crate) fn int_to_bytes(n: N, e: Endian, bits: usize) -> Vec { let mut ret = Vec::new(); for x in 0..n_bytes { let shift = match e { - Endian::Little => 8 * x as usize, - Endian::Big => 8 * (n_bytes - 1 - x) as usize, + Endian::Little => 8 * x, + Endian::Big => 8 * (n_bytes - 1 - x), }; if let Ok(a) = (n >> shift & N::from(0xffu8)).try_into() { ret.push(a) @@ -112,7 +112,7 @@ impl WordSpec { bytes_to_int(s, self.output_endian) } pub fn iter_words(self, bytes: &'_ [u8]) -> impl DoubleEndedIterator + '_ { - (0..(bytes.len() / self.word_bytes() as usize)) + (0..(bytes.len() / self.word_bytes())) .map(move |i| &bytes[self.word_bytes() * i..self.word_bytes() * (i + 1)]) .map(move |x| bytes_to_int(x, self.input_endian)) } diff --git a/delsum-lib/src/factor.rs b/delsum-lib/src/factor.rs index 5664028..65c8407 100644 --- a/delsum-lib/src/factor.rs +++ b/delsum-lib/src/factor.rs @@ -81,7 +81,12 @@ impl PrimeSieve { fn next_prime(&mut self, p: usize) -> usize { let old_len = self.sieve.len(); // find index of next prime - if let Some(i) = self.sieve[p + 1..].iter().enumerate().find(|(_, x)| !**x).map(|(a, _)| a) { + if let Some(i) = self.sieve[p + 1..] + .iter() + .enumerate() + .find(|(_, x)| !**x) + .map(|(a, _)| a) + { let q = p + 1 + i; // add the new found prime to the sieve self.update(q); @@ -89,7 +94,12 @@ impl PrimeSieve { } // if we did not find a next prime, extend the sieve self.extend(); - match self.sieve[old_len..].iter().enumerate().find(|(_, x)| !**x).map(|(a, b)| (a, *b)) { + match self.sieve[old_len..] + .iter() + .enumerate() + .find(|(_, x)| !**x) + .map(|(a, b)| (a, *b)) + { Some((j, _)) => { self.update(old_len + j); old_len + j @@ -358,7 +368,7 @@ impl MonContext { fn to_mon(&self, a: T) -> T { self.mon_mul(a, self.r_squared) } - fn from_mon(&self, a: T) -> T { + fn convert_from_mon(&self, a: T) -> T { self.mon_mul(a, T::one()) } // new_n divides n @@ -565,7 +575,7 @@ fn p1fac( ret.push(fac); } *n = mon.n; - (mon.from_mon(power), ret) + (mon.convert_from_mon(power), ret) } // implementation of probabilistic rabin-miller primality test @@ -650,7 +660,7 @@ fn factor(mut num: u128, bound: u128) -> Vec<(u128, u8)> { } else { let trial_fac: Vec<_> = trial_div(factor, &mut sieve, bound) .iter() - .map(|(p, e)| (*p as u128, *e)) + .map(|(p, e)| (*p, *e)) .collect(); merge_factors(&trial_fac, &prime_factors) } @@ -861,14 +871,14 @@ mod tests { } #[test] fn primes() { - assert_eq!(is_prob_prime(1433u64), true); - assert_eq!(is_prob_prime(1431u128), false); - assert_eq!(is_prob_prime(283408420968530627042721395551u128), true); - assert_eq!(is_prob_prime(4957391571224061778730779295067043u128), true); - assert_eq!(is_prob_prime(4957391571224061778730779295067041u128), false); - assert_eq!(is_prob_prime(4957391571224061778730779295067042u128), false); - assert_eq!(is_prob_prime(3u64), true); - assert_eq!(is_prob_prime(9u64), false); + assert!(is_prob_prime(1433u64)); + assert!(!is_prob_prime(1431u128)); + assert!(is_prob_prime(283408420968530627042721395551u128)); + assert!(is_prob_prime(4957391571224061778730779295067043u128)); + assert!(!is_prob_prime(4957391571224061778730779295067041u128)); + assert!(!is_prob_prime(4957391571224061778730779295067042u128)); + assert!(is_prob_prime(3u64)); + assert!(!is_prob_prime(9u64)); } #[test] fn combs() { diff --git a/delsum-lib/src/fletcher/mod.rs b/delsum-lib/src/fletcher/mod.rs index a00daa1..d5fbd6f 100644 --- a/delsum-lib/src/fletcher/mod.rs +++ b/delsum-lib/src/fletcher/mod.rs @@ -172,7 +172,7 @@ impl FletcherBuilder { mask, name: self.name.clone(), }; - let (mut s, mut c) = fletch.from_compact(addout); + let (mut s, mut c) = fletch.convert_from_compact(addout); if !module.is_zero() { s = s % module; c = c % module; @@ -253,7 +253,7 @@ impl Fletcher { name: None, } } - fn from_compact(&self, x: Sum::Double) -> (Sum, Sum) { + fn convert_from_compact(&self, x: Sum::Double) -> (Sum, Sum) { let l = Sum::from_double(x & self.mask); let h = Sum::from_double((x >> self.hwidth) & self.mask); if self.swap { @@ -333,7 +333,7 @@ impl Digest for Fletcher { self.to_compact((self.init, S::zero())) } fn dig_word(&self, sum: Self::Sum, word: u64) -> Self::Sum { - let (mut s, mut c) = self.from_compact(sum); + let (mut s, mut c) = self.convert_from_compact(sum); let modword = S::mod_from(word, &self.module); s = S::add_mod(s, &modword, &self.module); c = S::add_mod(c, &s, &self.module); @@ -361,20 +361,20 @@ impl LinearCheck for Fletcher { S::add_mod(shift, &S::one(), &self.module) } fn shift(&self, sum: Self::Sum, shift: &Self::Shift) -> Self::Sum { - let (s, mut c) = self.from_compact(sum); + let (s, mut c) = self.convert_from_compact(sum); let shift_diff = S::mul_mod(s, shift, &self.module); c = S::add_mod(c, &shift_diff, &self.module); self.to_compact((s, c)) } fn add(&self, sum_a: Self::Sum, sum_b: &Self::Sum) -> Self::Sum { - let (sa, ca) = self.from_compact(sum_a); - let (sb, cb) = self.from_compact(*sum_b); + let (sa, ca) = self.convert_from_compact(sum_a); + let (sb, cb) = self.convert_from_compact(*sum_b); let sum_s = sa.add_mod(&sb, &self.module); let sum_c = ca.add_mod(&cb, &self.module); self.to_compact((sum_s, sum_c)) } fn negate(&self, sum: Self::Sum) -> Self::Sum { - let (s, c) = self.from_compact(sum); + let (s, c) = self.convert_from_compact(sum); self.to_compact((s.neg_mod(&self.module), c.neg_mod(&self.module))) } } diff --git a/delsum-lib/src/fletcher/rev.rs b/delsum-lib/src/fletcher/rev.rs index 95a2bbc..d27f633 100644 --- a/delsum-lib/src/fletcher/rev.rs +++ b/delsum-lib/src/fletcher/rev.rs @@ -42,12 +42,11 @@ pub fn reverse_fletcher<'a>( files.sort_unstable_by(|a, b| a.0.len().cmp(&b.0.len()).reverse()); discrete_combos(spec.clone(), extended_search) .into_iter() - .map(move |x| { + .flat_map(move |x| { unresult_iter( reverse_discrete(spec.clone(), files.clone(), x, verbosity).map(|y| y.iter()), ) }) - .flatten() } /// Parallel version of reverse_fletcher. @@ -104,7 +103,7 @@ fn reverse_discrete( .iter() .map(|(f, c)| { ( - wordspec.iter_words(*f), + wordspec.iter_words(f), bytes_to_int::(c, wordspec.output_endian), ) }) @@ -154,30 +153,27 @@ impl RevResult { swap, wordspec, } = self; - modules - .into_iter() - .map(move |m| { - let module = if m.is_zero() { - 0u64 - } else { - (&m).try_into().unwrap() - }; - inits.iter(&addout1, &addout2, &m).map(move |(i, s1, s2)| { - let addout = glue_sum(s1, s2, width, swap); - Fletcher::with_options() - .addout(addout) - .init(i as u64) - .module(module) - .width(width) - .swap(swap) - .inendian(wordspec.input_endian) - .outendian(wordspec.output_endian) - .wordsize(wordspec.wordsize) - .build() - .unwrap() - }) + modules.into_iter().flat_map(move |m| { + let module = if m.is_zero() { + 0u64 + } else { + (&m).try_into().unwrap() + }; + inits.iter(&addout1, &addout2, &m).map(move |(i, s1, s2)| { + let addout = glue_sum(s1, s2, width, swap); + Fletcher::with_options() + .addout(addout) + .init(i) + .module(module) + .width(width) + .swap(swap) + .inendian(wordspec.input_endian) + .outendian(wordspec.output_endian) + .wordsize(wordspec.wordsize) + .build() + .unwrap() }) - .flatten() + }) } } @@ -332,19 +328,16 @@ fn summarize( fn find_regular_sum(spec: &RevSpec, sums: &[i128], mut module: u128) -> (u128, i128) { let width = spec.width; // init is here actually addout1 + init, which we can only know if we have both values - let maybe_init = spec - .addout - .map(|x| { - spec.init - .map(|y| y as i128 + split_sum(x, width, spec.swap).0 as i128) - }) - .flatten(); + let maybe_init = spec.addout.and_then(|x| { + spec.init + .map(|y| y as i128 + split_sum(x, width, spec.swap).0 as i128) + }); // delegate to the corresponding modsum function - let sum1_addout = super::super::modsum::find_largest_mod(&sums, maybe_init, &mut module); + let sum1_addout = super::super::modsum::find_largest_mod(sums, maybe_init, &mut module); (module, sum1_addout) } -fn remove_init(sums: &mut Vec<(BigInt, usize)>, init: &BigInt) { +fn remove_init(sums: &mut [(BigInt, usize)], init: &BigInt) { for (s, l) in sums.iter_mut() { *s -= init * BigInt::from(*l); *l = 0; @@ -552,16 +545,15 @@ impl PrefactorMod { module: &BigInt, ) -> impl Iterator { let mut red = self.clone(); - red.update_module(&module); + red.update_module(module); let mod_addout1 = mod_red(addout1, module); let mod_addout2 = mod_red(&addout2.0, module); let mod_addfac = mod_red(&BigInt::from(addout2.1), module); let module = module.clone(); (0u64..(&red.unknown).try_into().unwrap()) - .into_iter() .map(BigInt::from) .map(move |i| { - let real_init: u64 = mod_red(&(i * (&red).valid() + &red.possible), &module) + let real_init: u64 = mod_red(&(i * red.valid() + &red.possible), &module) .try_into() .unwrap(); let real_addout1: u64 = mod_red(&(&mod_addout1 - real_init), &module) @@ -577,7 +569,7 @@ impl PrefactorMod { // from b*x ≡ a mod m, try to calculate x mod m/y where y is the second return value fn partial_mod_div(a: &BigInt, b: &BigInt, module: &mut BigInt) -> (BigInt, BigInt) { - let common = gcd(&b, &module); + let common = gcd(b, module); // if we want b*x ≡ a mod m, and c divides both b and m, // then a must be divisible by c as well // if that is not the case, we determine the maximal module where this is true @@ -594,16 +586,16 @@ fn partial_mod_div(a: &BigInt, b: &BigInt, module: &mut BigInt) -> (BigInt, BigI // this works by first determining p^m by squaring and gcd'ing the product of all p's where // m < n, so that we have the maximum powers that divide module loop { - let new_x = gcd(&(&x * &x), &module); + let new_x = gcd(&(&x * &x), module); if new_x == x { break; } x = new_x; } - *module = module.clone() / &x * gcd(&x, &a); + *module = module.clone() / &x * gcd(&x, a); } - let (common, (b_inv_unmod, _)) = xgcd(&b, &module); - let b_inv = mod_red(&b_inv_unmod, &module); + let (common, (b_inv_unmod, _)) = xgcd(b, module); + let b_inv = mod_red(&b_inv_unmod, module); let inv = (a / &common * b_inv) % &*module; (inv, common) } @@ -649,7 +641,7 @@ mod tests { fn arbitrary(g: &mut Gen) -> Self { let mut new_fletcher = Fletcher::with_options(); let width = ((u8::arbitrary(g) % 63 + 2) * 2) as usize; - new_fletcher.width(width as usize); + new_fletcher.width(width); let mut module = 0; while module <= 1 { module = u64::arbitrary(g); @@ -662,13 +654,13 @@ mod tests { new_fletcher.init(init); let swap = bool::arbitrary(g); new_fletcher.swap(swap); - let addout1 = u64::arbitrary(g) as u64 % module; - let addout2 = u64::arbitrary(g) as u64 % module; + let addout1 = u64::arbitrary(g) % module; + let addout2 = u64::arbitrary(g) % module; let addout = glue_sum(addout1, addout2, width, swap); new_fletcher.addout(addout); let wordspec = WordSpec::arbitrary(g); let max_word_width = ((width + 15) / 16).next_power_of_two() * 8; - new_fletcher.wordsize(max_word_width.min(wordspec.wordsize) as usize); + new_fletcher.wordsize(max_word_width.min(wordspec.wordsize)); new_fletcher.inendian(wordspec.input_endian); new_fletcher.outendian(wordspec.output_endian); new_fletcher diff --git a/delsum-lib/src/keyval.rs b/delsum-lib/src/keyval.rs index 9ad3d1d..b1ada65 100644 --- a/delsum-lib/src/keyval.rs +++ b/delsum-lib/src/keyval.rs @@ -70,7 +70,7 @@ impl<'a> Iterator for KeyValIter<'a> { State::Value } (State::Key, '=') => State::Equal, - (State::Key, 'A'..='Z' ) + (State::Key, 'A'..='Z') | (State::Key, 'a'..='z') | (State::Key, '_') | (State::Whitespace, 'A'..='Z') diff --git a/delsum-lib/src/lib.rs b/delsum-lib/src/lib.rs index 9aa5b0d..21bf06b 100644 --- a/delsum-lib/src/lib.rs +++ b/delsum-lib/src/lib.rs @@ -12,7 +12,7 @@ pub mod modsum; use bitnum::BitNum; use checksum::{CheckBuilderErr, CheckReverserError}; use checksum::{Digest, LinearCheck, RangePair}; -use crc::{reverse_crc, CRCBuilder, CRC}; +use crc::{reverse_crc, CrcBuilder, CRC}; use fletcher::{reverse_fletcher, Fletcher, FletcherBuilder}; use modsum::{reverse_modsum, ModSum, ModSumBuilder}; use std::cmp::Ordering; @@ -177,7 +177,7 @@ pub fn find_checksum(strspec: &str, bytes: &[&[u8]]) -> Result>, Che } enum BuilderEnum { - CRC(CRCBuilder), + Crc(CrcBuilder), ModSum(ModSumBuilder), Fletcher(FletcherBuilder), } @@ -191,7 +191,7 @@ pub struct AlgorithmFinder<'a> { impl<'a> AlgorithmFinder<'a> { pub fn find_all(&'_ self) -> impl Iterator> + '_ { - let maybe_crc = if let BuilderEnum::CRC(crc) = &self.spec { + let maybe_crc = if let BuilderEnum::Crc(crc) = &self.spec { Some( reverse_crc( crc, @@ -241,7 +241,7 @@ impl<'a> AlgorithmFinder<'a> { pub fn find_all_para( &'_ self, ) -> impl ParallelIterator> + '_ { - let maybe_crc = if let BuilderEnum::CRC(crc) = &self.spec { + let maybe_crc = if let BuilderEnum::Crc(crc) = &self.spec { Some( reverse_crc_para( crc, @@ -299,7 +299,7 @@ pub fn find_algorithm<'a>( let (prefix, _, rest) = find_prefix_width(strspec)?; let prefix = prefix.to_ascii_lowercase(); let spec = match prefix.as_str() { - "crc" => BuilderEnum::CRC(CRCBuilder::::from_str(rest)?), + "crc" => BuilderEnum::Crc(CrcBuilder::::from_str(rest)?), "modsum" => BuilderEnum::ModSum(ModSumBuilder::::from_str(rest)?), "fletcher" => BuilderEnum::Fletcher(FletcherBuilder::::from_str(rest)?), _ => unimplemented!(), diff --git a/delsum-lib/src/modsum/rev.rs b/delsum-lib/src/modsum/rev.rs index d2401ec..978240f 100644 --- a/delsum-lib/src/modsum/rev.rs +++ b/delsum-lib/src/modsum/rev.rs @@ -35,7 +35,7 @@ pub fn reverse_modsum<'a>( extended_search, ) .into_iter() - .map(move |wordspec| { + .flat_map(move |wordspec| { let rev = match spec.width { None => Err(CheckReverserError::MissingParameter("width")), Some(width) => { @@ -43,7 +43,7 @@ pub fn reverse_modsum<'a>( .iter() .map(|(f, c)| { ( - wordspec.iter_words(*f), + wordspec.iter_words(f), bytes_to_int(c, wordspec.output_endian), ) }) @@ -59,7 +59,6 @@ pub fn reverse_modsum<'a>( }; unresult_iter(rev) }) - .flatten() } struct RevSpec { @@ -87,7 +86,7 @@ impl RevResult { } = self; modlist.into_iter().map(move |module| { let init_negative = init < 0; - let mut init = init.abs() as u128 % module; + let mut init = init.unsigned_abs() % module; if init_negative { init = module - init; } @@ -132,7 +131,7 @@ fn reverse( let original_mod = spec .module .map(|x| if x == 0 { 1u128 << width } else { x as u128 }); - let mut module = original_mod.unwrap_or(0) as u128; + let mut module = original_mod.unwrap_or(0); log("removing inits"); // here we find module by gcd'ing between the differences (init - init == 0 mod m) let init = find_largest_mod(&sums, spec.init.map(i128::from), &mut module); @@ -145,7 +144,7 @@ fn reverse( // find all possible divisors let modlist = match original_mod { Some(x) => { - if x as u128 == module && x > min_sum && x <= max_sum { + if x == module && x > min_sum && x <= max_sum { vec![module] } else { Vec::new() @@ -162,23 +161,22 @@ fn reverse( } pub(crate) fn find_largest_mod(sums: &[i128], maybe_init: Option, module: &mut u128) -> i128 { - let init = match maybe_init { + match maybe_init { Some(i) => { // if we already have init, we can just subtract that from the sum and get a multiple of m for s in sums { - *module = gcd(*module, (s + i).abs() as u128); + *module = gcd(*module, (s + i).unsigned_abs()); } i } None => { // otherwise their difference will do, but we do get one gcd less for (s1, s2) in sums.iter().zip(sums.iter().skip(1)) { - *module = gcd(*module, (s1 - s2).abs() as u128); + *module = gcd(*module, (s1 - s2).unsigned_abs()); } -sums[0] } - }; - init + } } #[cfg(test)] @@ -206,7 +204,7 @@ mod tests { new_modsum.init(init); let wordspec = WordSpec::arbitrary(g); let max_word_width = ((width as usize + 7) / 8).next_power_of_two() * 8; - new_modsum.wordsize(max_word_width.min(wordspec.wordsize) as usize); + new_modsum.wordsize(max_word_width.min(wordspec.wordsize)); new_modsum.inendian(wordspec.input_endian); new_modsum.outendian(wordspec.output_endian); new_modsum diff --git a/delsum-lib/src/utils.rs b/delsum-lib/src/utils.rs index b93e19f..6867b4e 100644 --- a/delsum-lib/src/utils.rs +++ b/delsum-lib/src/utils.rs @@ -1,4 +1,9 @@ -use std::{convert::{TryFrom, TryInto}, fmt::Display, num::ParseIntError, str::FromStr}; +use std::{ + convert::{TryFrom, TryInto}, + fmt::Display, + num::ParseIntError, + str::FromStr, +}; use crate::checksum::Relativity; @@ -98,8 +103,7 @@ impl FromStr for SignedInclRange { fn from_str(s: &str) -> Result { let from_maybe_hex = |s: &str| match s { "" => Ok(None), - otherwise => read_signed_maybe_hex(otherwise) - .map(Some), + otherwise => read_signed_maybe_hex(otherwise).map(Some), }; let split = s .split(':') diff --git a/delsum-poly/build.rs b/delsum-poly/build.rs index 0bd356a..79441aa 100644 --- a/delsum-poly/build.rs +++ b/delsum-poly/build.rs @@ -15,13 +15,13 @@ fn main() { if value == "1" { link_type = "static"; } - }, + } "DELSUM_NTL_LIB_PATH" | "DELSUM_GF2X_LIB_PATH" | "DELSUM_GMP_LIB_PATH" => { println!("cargo:rustc-link-search=native={}", value); - }, + } "DELSUM_NTL_INCLUDE" => { build.include(value); - }, + } _ => continue, } } diff --git a/delsum-poly/include/poly.hh b/delsum-poly/include/poly.hh index c41a0f4..fdcb4ae 100644 --- a/delsum-poly/include/poly.hh +++ b/delsum-poly/include/poly.hh @@ -26,7 +26,7 @@ namespace poly void sqr(); bool div_to_checked(const Poly &b); bool coeff(int64_t idx) const; - bool eq(const Poly &b) const; + bool equals(const Poly &b) const; bool is_zero() const; std::unique_ptr> to_bytes(int64_t min_bytes) const; }; diff --git a/delsum-poly/src/lib.rs b/delsum-poly/src/lib.rs index 47d32f4..b87e429 100644 --- a/delsum-poly/src/lib.rs +++ b/delsum-poly/src/lib.rs @@ -92,6 +92,12 @@ impl ops::DivAssign<&PolyRem> for PolyRemPtr { } } +impl PartialEq for Poly { + fn eq(&self, other: &Self) -> bool { + self.equals(other) + } +} + // ntl author says it is thread safe unsafe impl Send for Poly {} unsafe impl Sync for Poly {} @@ -122,7 +128,7 @@ mod ffi { fn div_to_checked(self: Pin<&mut Poly>, b: &Poly) -> bool; fn sqr(self: Pin<&mut Poly>); fn coeff(self: &Poly, idx: i64) -> bool; - fn eq(self: &Poly, b: &Poly) -> bool; + fn equals(self: &Poly, b: &Poly) -> bool; fn is_zero(self: &Poly) -> bool; fn add(b: &Poly, c: &Poly) -> UniquePtr; fn mul(b: &Poly, c: &Poly) -> UniquePtr; diff --git a/delsum-poly/src/poly.cc b/delsum-poly/src/poly.cc index e49e783..ce2b837 100644 --- a/delsum-poly/src/poly.cc +++ b/delsum-poly/src/poly.cc @@ -31,7 +31,7 @@ namespace poly { return NTL::IsOne(NTL::coeff(int_pol, i64_to_l(idx))); } - bool Poly::eq(const Poly &b) const + bool Poly::equals(const Poly &b) const { return int_pol == b.int_pol; } diff --git a/src/bin.rs b/src/bin.rs index 7a90479..95fe292 100644 --- a/src/bin.rs +++ b/src/bin.rs @@ -36,7 +36,7 @@ fn reverse(opts: &Reverse) { }; let algorithms = |model: &str| { find_algorithm( - &model, + model, &ranged_files, &checksums, opts.verbose as u64,