code cleanup

This commit is contained in:
Henry Schimke
2023-04-29 09:58:04 -05:00
parent ef999a4eb0
commit 508f5f14c5
19 changed files with 56 additions and 154 deletions

View File

@@ -61,10 +61,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let mut tos = if hostEmail.is_empty() { let mut tos = if hostEmail.is_empty() {
Vec::new() Vec::new()
} else { } else {
COMMA COMMA.split(hostEmail).map(|s| s.to_owned()).collect()
.split(hostEmail)
.map(|s| s.to_owned())
.collect()
}; };
// if (!hostEmail.isEmpty()) { // if (!hostEmail.isEmpty()) {
// tos = COMMA.split(hostEmail); // tos = COMMA.split(hostEmail);
@@ -78,29 +75,20 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
// if (nameValues != null) { // if (nameValues != null) {
if tos.is_empty() { if tos.is_empty() {
if let Some(tosString) = nv.get("to") { if let Some(tosString) = nv.get("to") {
tos = COMMA tos = COMMA.split(tosString).map(|s| s.to_owned()).collect();
.split(tosString)
.map(|s| s.to_owned())
.collect();
} }
// if tosString != null { // if tosString != null {
// tos = COMMA.split(tosString); // tos = COMMA.split(tosString);
// } // }
} }
if let Some(ccString) = nv.get("cc") { if let Some(ccString) = nv.get("cc") {
ccs = COMMA ccs = COMMA.split(ccString).map(|s| s.to_owned()).collect();
.split(ccString)
.map(|s| s.to_owned())
.collect();
} }
// if ccString != null { // if ccString != null {
// ccs = COMMA.split(ccString); // ccs = COMMA.split(ccString);
// } // }
if let Some(bccString) = nv.get("bcc") { if let Some(bccString) = nv.get("bcc") {
bccs = COMMA bccs = COMMA.split(bccString).map(|s| s.to_owned()).collect();
.split(bccString)
.map(|s| s.to_owned())
.collect();
} }
// if bccString != null { // if bccString != null {
// bccs = COMMA.split(bccString); // bccs = COMMA.split(bccString);

View File

@@ -18,7 +18,6 @@
// import java.util.Arrays; // import java.util.Arrays;
use std::{cmp, fmt}; use std::{cmp, fmt};
use crate::common::Result; use crate::common::Result;

View File

@@ -1,4 +1,3 @@
use crate::qrcode::decoder::ErrorCorrectionLevel; use crate::qrcode::decoder::ErrorCorrectionLevel;
impl ErrorCorrectionLevel { impl ErrorCorrectionLevel {

View File

@@ -1,5 +1,3 @@
use crate::qrcode::decoder::{ use crate::qrcode::decoder::{
ErrorCorrectionLevel, FormatInformation, FORMAT_INFO_DECODE_LOOKUP, FORMAT_INFO_MASK_QR, ErrorCorrectionLevel, FormatInformation, FORMAT_INFO_DECODE_LOOKUP, FORMAT_INFO_MASK_QR,
}; };

View File

@@ -8,8 +8,6 @@ use crate::{
point, Point, point, Point,
}; };
use super::{ use super::{
BitMatrixCursorTrait, EdgeTracer, FastEdgeToEdgeCounter, Pattern, RegressionLine, BitMatrixCursorTrait, EdgeTracer, FastEdgeToEdgeCounter, Pattern, RegressionLine,
RegressionLineTrait, UpdateMinMax, UpdateMinMaxFloat, RegressionLineTrait, UpdateMinMax, UpdateMinMaxFloat,
@@ -342,18 +340,11 @@ pub fn CollectRingPoints(
} }
pub fn FitQadrilateralToPoints(center: Point, points: &mut [Point]) -> Option<Quadrilateral> { pub fn FitQadrilateralToPoints(center: Point, points: &mut [Point]) -> Option<Quadrilateral> {
let _dist2Center = |a, b| Point::distance(a, center) < Point::distance(b, center);
// rotate points such that the first one is the furthest away from the center (hence, a corner) // rotate points such that the first one is the furthest away from the center (hence, a corner)
let max_by_pred = |a: &&Point, b: &&Point| { let max_by_pred = |a: &&Point, b: &&Point| {
let da = Point::distance(**a, center); let da = Point::distance(**a, center);
let db = Point::distance(**b, center); let db = Point::distance(**b, center);
da.partial_cmp(&db).unwrap() da.partial_cmp(&db).unwrap()
// if dist2Center(**a, **b) {
// std::cmp::Ordering::Greater
// } else {
// std::cmp::Ordering::Less
// }
}; };
let max = points.iter().max_by(max_by_pred)?; let max = points.iter().max_by(max_by_pred)?;
@@ -361,7 +352,6 @@ pub fn FitQadrilateralToPoints(center: Point, points: &mut [Point]) -> Option<Qu
let pos = points.iter().position(|e| e == max)?; let pos = points.iter().position(|e| e == max)?;
points.rotate_left(pos); points.rotate_left(pos);
// std::rotate(points.begin(), std::max_element(points.begin(), points.end(), dist2Center), points.end());
let mut corners = [Point::default(); 4]; let mut corners = [Point::default(); 4];
corners[0] = points[0]; corners[0] = points[0];
@@ -372,17 +362,11 @@ pub fn FitQadrilateralToPoints(center: Point, points: &mut [Point]) -> Option<Qu
// corners[2] = std::max_element(&points[Size(points) * 3 / 8], &points[Size(points) * 5 / 8], dist2Center); // corners[2] = std::max_element(&points[Size(points) * 3 / 8], &points[Size(points) * 5 / 8], dist2Center);
// find the two in between corners by looking for the points farthest from the long diagonal // find the two in between corners by looking for the points farthest from the long diagonal
let l = RegressionLine::with_two_points(corners[0], corners[2]); let l = RegressionLine::with_two_points(corners[0], corners[2]);
let _dist2Diagonal = /*[l = RegressionLine(*corners[0], *corners[2])]*/| a, b| { l.distance_single(a) < l.distance_single(b) };
let diagonal_max_by_pred = |p1: &Point, p2: &Point| { let diagonal_max_by_pred = |p1: &Point, p2: &Point| {
let d1 = l.distance_single(*p1); let d1 = l.distance_single(*p1);
let d2 = l.distance_single(*p2); let d2 = l.distance_single(*p2);
d1.partial_cmp(&d2).unwrap() d1.partial_cmp(&d2).unwrap()
// if dist2Diagonal(*p1, *p2) {
// std::cmp::Ordering::Greater
// } else {
// std::cmp::Ordering::Less
// }
}; };
corners[1] = points[(points.len() / 8)..=(points.len() * 3 / 8)] corners[1] = points[(points.len() / 8)..=(points.len() * 3 / 8)]
.iter() .iter()
@@ -417,14 +401,6 @@ pub fn FitQadrilateralToPoints(center: Point, points: &mut [Point]) -> Option<Qu
RegressionLine::with_point_slice(try_get_range(corner_positions[3], points.len())?), RegressionLine::with_point_slice(try_get_range(corner_positions[3], points.len())?),
]; ];
// let lines = [
// RegressionLine::with_point_slice(&points[corner_positions[0] + 1..corner_positions[1]]),
// RegressionLine::with_point_slice(&points[corner_positions[1] + 1..corner_positions[2]]),
// RegressionLine::with_point_slice(&points[corner_positions[2] + 1..corner_positions[3]]),
// RegressionLine::with_point_slice(&points[corner_positions[3] + 1..points.len()]),
// ];
// std::array lines{RegressionLine{corners[0] + 1, corners[1]}, RegressionLine{corners[1] + 1, corners[2]},
// RegressionLine{corners[2] + 1, corners[3]}, RegressionLine{corners[3] + 1, &points.back() + 1}};
if lines.iter().any(|line| !line.isValid()) { if lines.iter().any(|line| !line.isValid()) {
return None; return None;
} }
@@ -515,15 +491,6 @@ pub fn FindConcentricPatternCorners(
let res = Quadrilateral::blend(&innerCorners, &outerCorners); let res = Quadrilateral::blend(&innerCorners, &outerCorners);
// for p in innerCorners{
// log(p, 3);}
// for p in outerCorners{
// log(p, 3);}
// for p in res{
// log(p, 3);}
Some(res) Some(res)
} }

View File

@@ -1,4 +1,4 @@
use std::{rc::Rc}; use std::rc::Rc;
use crate::{common::ECIStringBuilder, Exceptions}; use crate::{common::ECIStringBuilder, Exceptions};

View File

@@ -45,7 +45,7 @@ impl<'a> FastEdgeToEdgeCounter<'a> {
stride, stride,
stepsToBorder, stepsToBorder,
_arr: cur.p().y as isize * stride, //cur.img().getRow(cur.p().y as u32), _arr: cur.p().y as isize * stride, //cur.img().getRow(cur.p().y as u32),
under_arry: cur.img(), //.into(), under_arry: cur.img(), //.into(),
} }
} }

View File

@@ -217,11 +217,6 @@ impl<'a> PatternView<'a> {
|| Into::<f32>::into(self.data.0[self.count]) || Into::<f32>::into(self.data.0[self.count])
>= Into::<f32>::into(self.sum(None)) * scale >= Into::<f32>::into(self.sum(None)) * scale
} }
// template<bool acceptIfAtFirstBar = false>
// bool hasQuietZoneBefore(float scale) const
// {
// return (acceptIfAtFirstBar && isAtFirstBar()) || _data[-1] >= sum() * scale;
// }
pub fn hasQuietZoneAfter(&self, scale: f32, acceptIfAtLastBar: Option<bool>) -> bool { pub fn hasQuietZoneAfter(&self, scale: f32, acceptIfAtLastBar: Option<bool>) -> bool {
(acceptIfAtLastBar.unwrap_or(true) && self.isAtLastBar()) (acceptIfAtLastBar.unwrap_or(true) && self.isAtLastBar())
@@ -229,12 +224,6 @@ impl<'a> PatternView<'a> {
>= Into::<f32>::into(self.sum(None)) * scale >= Into::<f32>::into(self.sum(None)) * scale
} }
// template<bool acceptIfAtLastBar = true>
// bool hasQuietZoneAfter(float scale) const
// {
// return (acceptIfAtLastBar && isAtLastBar()) || _data[_size] >= sum() * scale;
// }
pub fn subView(&self, offset: usize, size: Option<usize>) -> PatternView<'a> { pub fn subView(&self, offset: usize, size: Option<usize>) -> PatternView<'a> {
let mut size = size.unwrap_or(0); let mut size = size.unwrap_or(0);
if size == 0 { if size == 0 {
@@ -251,28 +240,11 @@ impl<'a> PatternView<'a> {
} }
} }
// PatternView subView(int offset, int size = 0) const
// {
// // if(std::abs(size) > count())
// // printf("%d > %d\n", std::abs(size), _count);
// // assert(std::abs(size) <= count());
// if (size == 0)
// size = _size - offset;
// else if (size < 0)
// size = _size - offset + size;
// return {begin() + offset, std::max(size, 0), _base, _end};
// }
pub fn shift(&mut self, n: usize) -> bool { pub fn shift(&mut self, n: usize) -> bool {
self.current += n; self.current += n;
!self.data.0.is_empty() && self.start + self.count <= (self.start + self.count) !self.data.0.is_empty() && self.start + self.count <= (self.start + self.count)
} }
// bool shift(int n)
// {
// return _data && ((_data += n) + _size <= _end);
// }
pub fn skipPair(&mut self) -> bool { pub fn skipPair(&mut self) -> bool {
self.shift(2) self.shift(2)
} }
@@ -361,6 +333,16 @@ impl<'a> Into<Vec<PatternType>> for &PatternView<'a> {
} }
} }
impl<'a, const LEN: usize> Into<[PatternType; LEN]> for &PatternView<'a> {
fn into(self) -> [PatternType; LEN] {
let mut result = [PatternType::default(); LEN];
for i in 0..self.count {
result[i] = self[i];
}
result
}
}
/** /**
* @brief The BarAndSpace struct is a simple 2 element data structure to hold information about bar(s) and space(s). * @brief The BarAndSpace struct is a simple 2 element data structure to hold information about bar(s) and space(s).
* *
@@ -407,7 +389,7 @@ impl<T: Default + std::cmp::PartialEq> std::ops::IndexMut<usize> for BarAndSpace
// bool isValid() const { return bar != T{} && space != T{}; } // bool isValid() const { return bar != T{} && space != T{}; }
// }; // };
type BarAndSpaceI = BarAndSpace<PatternType>; // type BarAndSpaceI = BarAndSpace<PatternType>;
/** /**
* @brief FixedPattern describes a compile-time constant (start/stop) pattern. * @brief FixedPattern describes a compile-time constant (start/stop) pattern.
@@ -488,7 +470,7 @@ pub fn IsPattern<const E2E: bool, const LEN: usize, const SUM: usize, const SPAR
if E2E { if E2E {
//using float_t = double; //using float_t = double;
let v_src: Vec<PatternType> = view.into(); let v_src: [PatternType; LEN] = view.into();
let widths = BarAndSpaceSum::<LEN, PatternType, f64>(&v_src); let widths = BarAndSpaceSum::<LEN, PatternType, f64>(&v_src);
let sums = pattern.sums(); let sums = pattern.sums();
let modSize: BarAndSpace<f64> = BarAndSpace { let modSize: BarAndSpace<f64> = BarAndSpace {
@@ -627,13 +609,8 @@ pub fn FindLeftGuard<'a, const LEN: usize, const SUM: usize, const IS_SPARCE: bo
{ {
return false; return false;
} }
IsPattern::<false, LEN, SUM, IS_SPARCE>( IsPattern::<false, LEN, SUM, IS_SPARCE>(window, pattern, spaceInPixel, minQuietZone, 0.0)
window, != 0.0
pattern,
spaceInPixel,
minQuietZone,
0.0,
) != 0.0
}) })
} }

View File

@@ -26,8 +26,6 @@ use std::{
fmt::{self}, fmt::{self},
}; };
use super::{CharacterSet, Eci, StringUtils}; use super::{CharacterSet, Eci, StringUtils};
/** /**

View File

@@ -1,7 +1,5 @@
use crate::{point, Point}; use crate::{point, Point};
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
pub struct Quadrilateral(pub [Point; 4]); pub struct Quadrilateral(pub [Point; 4]);

View File

@@ -5,7 +5,6 @@ pub(self) use crate::common::cpp_essentials::bitmatrix_cursor_trait::*;
pub(self) use crate::common::cpp_essentials::dm_regression_line::*; pub(self) use crate::common::cpp_essentials::dm_regression_line::*;
pub(self) use crate::common::cpp_essentials::edge_tracer::*; pub(self) use crate::common::cpp_essentials::edge_tracer::*;
pub(self) use crate::common::cpp_essentials::util; pub(self) use crate::common::cpp_essentials::util;
pub use cpp_new_detector::detect; pub use cpp_new_detector::detect;

View File

@@ -9,8 +9,7 @@ use crate::common::reedsolomon::{
get_predefined_genericgf, PredefinedGenericGF, ReedSolomonDecoder, get_predefined_genericgf, PredefinedGenericGF, ReedSolomonDecoder,
}; };
use crate::common::{ use crate::common::{
AIFlag, BitMatrix, BitSource, CharacterSet, ECIStringBuilder, Eci, Result, AIFlag, BitMatrix, BitSource, CharacterSet, ECIStringBuilder, Eci, Result, SymbologyIdentifier,
SymbologyIdentifier,
}; };
use crate::qrcode::cpp_port::bitmatrix_parser::{ use crate::qrcode::cpp_port::bitmatrix_parser::{
ReadCodewords, ReadFormatInformation, ReadVersion, ReadCodewords, ReadFormatInformation, ReadVersion,

View File

@@ -4,7 +4,8 @@ use crate::{
CenterOfRing, DMRegressionLine, FindConcentricPatternCorners, FindLeftGuardBy, Matrix, CenterOfRing, DMRegressionLine, FindConcentricPatternCorners, FindLeftGuardBy, Matrix,
}, },
DefaultGridSampler, GridSampler, Result, SamplerControl, DefaultGridSampler, GridSampler, Result, SamplerControl,
}, point_i, },
point_i,
qrcode::{ qrcode::{
decoder::{FormatInformation, Version, VersionRef}, decoder::{FormatInformation, Version, VersionRef},
detector::QRCodeDetectorResult, detector::QRCodeDetectorResult,
@@ -16,10 +17,9 @@ use multimap::MultiMap;
use crate::{ use crate::{
common::{ common::{
cpp_essentials::{ cpp_essentials::{
BitMatrixCursorTrait, ConcentricPattern, Direction, EdgeTracer, BitMatrixCursorTrait, ConcentricPattern, Direction, EdgeTracer, FixedPattern,
FixedPattern, GetPatternRowTP, IsPattern, LocateConcentricPattern, GetPatternRowTP, IsPattern, LocateConcentricPattern, PatternRow, PatternType,
PatternRow, PatternType, PatternView, ReadSymmetricPattern, RegressionLine, PatternView, ReadSymmetricPattern, RegressionLine, RegressionLineTrait,
RegressionLineTrait,
}, },
BitMatrix, PerspectiveTransform, Quadrilateral, BitMatrix, PerspectiveTransform, Quadrilateral,
}, },
@@ -502,8 +502,16 @@ pub fn SampleQR(image: &BitMatrix, fp: &FinderPatternSet) -> Result<QRCodeDetect
} }
let best = if top.err == left.err { let best = if top.err == left.err {
if top.dim > left.dim { top } else { left } if top.dim > left.dim {
} else if top.err < left.err { top } else { left }; top
} else {
left
}
} else if top.err < left.err {
top
} else {
left
};
let mut dimension = best.dim; let mut dimension = best.dim;
let moduleSize = (best.ms + 1.0) as i32; let moduleSize = (best.ms + 1.0) as i32;

View File

@@ -120,8 +120,8 @@
use crate::{ use crate::{
common::{cpp_essentials::ConcentricPattern, DetectorRXingResult}, common::{cpp_essentials::ConcentricPattern, DetectorRXingResult},
multi::MultipleBarcodeReader, multi::MultipleBarcodeReader,
BarcodeFormat, DecodeHintType, DecodeHintValue, DecodingHintDictionary, BarcodeFormat, DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions,
Exceptions, RXingResult, Reader, RXingResult, Reader,
}; };
use super::{ use super::{
@@ -132,8 +132,6 @@ use super::{
}, },
}; };
#[derive(Default)] #[derive(Default)]
pub struct QrReader; pub struct QrReader;

View File

@@ -8,86 +8,62 @@ use crate::{common::BitMatrix, qrcode::cpp_port::data_mask::GetMaskedBit};
#[test] #[test]
fn Mask0() { fn Mask0() {
TestMaskAcrossDimensions(0, |i, j| { TestMaskAcrossDimensions(0, |i, j| (i + j) % 2 == 0);
(i + j) % 2 == 0
});
} }
#[test] #[test]
fn Mask1() { fn Mask1() {
TestMaskAcrossDimensions(1, |i, _| { TestMaskAcrossDimensions(1, |i, _| i % 2 == 0);
i % 2 == 0
});
} }
#[test] #[test]
fn Mask2() { fn Mask2() {
TestMaskAcrossDimensions(2, |_, j| { TestMaskAcrossDimensions(2, |_, j| j % 3 == 0);
j % 3 == 0
});
} }
#[test] #[test]
fn Mask3() { fn Mask3() {
TestMaskAcrossDimensions(3, |i, j| { TestMaskAcrossDimensions(3, |i, j| (i + j) % 3 == 0);
(i + j) % 3 == 0
});
} }
#[test] #[test]
fn Mask4() { fn Mask4() {
TestMaskAcrossDimensions(4, |i, j| { TestMaskAcrossDimensions(4, |i, j| (i / 2 + j / 3) % 2 == 0);
(i / 2 + j / 3) % 2 == 0
});
} }
#[test] #[test]
fn Mask5() { fn Mask5() {
TestMaskAcrossDimensions(5, |i, j| { TestMaskAcrossDimensions(5, |i, j| (i * j) % 2 + (i * j) % 3 == 0);
(i * j) % 2 + (i * j) % 3 == 0
});
} }
#[test] #[test]
fn Mask6() { fn Mask6() {
TestMaskAcrossDimensions(6, |i, j| { TestMaskAcrossDimensions(6, |i, j| ((i * j) % 2 + (i * j) % 3) % 2 == 0);
((i * j) % 2 + (i * j) % 3) % 2 == 0
});
} }
#[test] #[test]
fn Mask7() { fn Mask7() {
TestMaskAcrossDimensions(7, |i, j| { TestMaskAcrossDimensions(7, |i, j| ((i + j) % 2 + (i * j) % 3) % 2 == 0);
((i + j) % 2 + (i * j) % 3) % 2 == 0
});
} }
#[test] #[test]
fn MicroMask0() { fn MicroMask0() {
TestMicroMaskAcrossDimensions(0, |i, _| { TestMicroMaskAcrossDimensions(0, |i, _| i % 2 == 0);
i % 2 == 0
});
} }
#[test] #[test]
fn MicroMask1() { fn MicroMask1() {
TestMicroMaskAcrossDimensions(1, |i, j| { TestMicroMaskAcrossDimensions(1, |i, j| (i / 2 + j / 3) % 2 == 0);
(i / 2 + j / 3) % 2 == 0
});
} }
#[test] #[test]
fn MicroMask2() { fn MicroMask2() {
TestMicroMaskAcrossDimensions(2, |i, j| { TestMicroMaskAcrossDimensions(2, |i, j| ((i * j) % 2 + (i * j) % 3) % 2 == 0);
((i * j) % 2 + (i * j) % 3) % 2 == 0
});
} }
#[test] #[test]
fn MicroMask3() { fn MicroMask3() {
TestMicroMaskAcrossDimensions(3, |i, j| { TestMicroMaskAcrossDimensions(3, |i, j| ((i + j) % 2 + (i * j) % 3) % 2 == 0);
((i + j) % 2 + (i * j) % 3) % 2 == 0
});
} }
fn TestMaskAcrossDimensionsImpl<F>( fn TestMaskAcrossDimensionsImpl<F>(

View File

@@ -23,10 +23,8 @@
// using namespace ZXing; // using namespace ZXing;
// using namespace ZXing::QRCode; // using namespace ZXing::QRCode;
use crate::{ use crate::{
common::{BitArray}, common::BitArray,
qrcode::{ qrcode::{
cpp_port::decoder::DecodeBitStream, cpp_port::decoder::DecodeBitStream,
decoder::{ErrorCorrectionLevel, Version}, decoder::{ErrorCorrectionLevel, Version},

View File

@@ -43,8 +43,8 @@ fn VersionForNumber() {
fn GetProvisionalVersionForDimension() { fn GetProvisionalVersionForDimension() {
for i in 1..=40 { for i in 1..=40 {
// for (int i = 1; i <= 40; i++) { // for (int i = 1; i <= 40; i++) {
let prov = let prov = Version::FromDimension(4 * i + 17)
Version::FromDimension(4 * i + 17).unwrap_or_else(|_| panic!("version should exist for {i}")); .unwrap_or_else(|_| panic!("version should exist for {i}"));
// assert_ne!(prov, nullptr); // assert_ne!(prov, nullptr);
assert_eq!(i, prov.getVersionNumber()); assert_eq!(i, prov.getVersionNumber());
} }

View File

@@ -151,10 +151,10 @@ impl Mode {
return Mode::try_from(bits); return Mode::try_from(bits);
} }
} else { } else {
const Bits2Mode: [Mode; BITS_2_MODE_LEN] = const BITS_2_MODE: [Mode; BITS_2_MODE_LEN] =
[Mode::NUMERIC, Mode::ALPHANUMERIC, Mode::BYTE, Mode::KANJI]; [Mode::NUMERIC, Mode::ALPHANUMERIC, Mode::BYTE, Mode::KANJI];
if (bits as usize) < BITS_2_MODE_LEN { if (bits as usize) < BITS_2_MODE_LEN {
return Ok(Bits2Mode[bits as usize]); return Ok(BITS_2_MODE[bits as usize]);
} }
} }