Skip to content

Commit

Permalink
adjust clippy warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
tsionyx committed Jul 14, 2024
1 parent 2ee0178 commit fb9b972
Show file tree
Hide file tree
Showing 11 changed files with 118 additions and 94 deletions.
19 changes: 11 additions & 8 deletions types/src/angle/dd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,9 @@ impl DecimalDegree {
Ok(())
}

// no panic is possible because the precision
// does not allow for too big whole-degree value (max=2^32 / 10^7 ~= 429)
#[allow(clippy::missing_panics_doc)]
/// The whole number of degrees in the angle
pub fn degrees(self) -> u16 {
let degrees = self.units / Self::units_in_deg();
Expand Down Expand Up @@ -760,7 +763,7 @@ mod tests {
#[test]
fn print_zero_as_dms() {
let d = DecimalDegree::default();
let s = format!("{:#}", d);
let s = format!("{d:#}");
assert_eq!(s, "0°");
}

Expand All @@ -773,22 +776,22 @@ mod tests {
#[test]
fn print_right_as_dms() {
let d: DecimalDegree = 90.try_into().unwrap();
let s = format!("{:#}", d);
let s = format!("{d:#}");
assert_eq!(s, "90°");
}

#[test]
fn print_fraction_as_dms() {
let d = DecimalDegree::from_deg_and_fraction(60, 5_467_182).unwrap();
let s = format!("{:#}", d);
let s = format!("{d:#}");
assert_eq!(s, "60°32′48.186″");
}

#[test]
fn print_fraction_as_dms_without_milli() {
for f in 0..3 {
let d = DecimalDegree::from_deg_and_fraction(60, 5_466_666 + f).unwrap();
let s = format!("{:#}", d);
let s = format!("{d:#}");
assert_eq!(s, "60°32′48″");
}
}
Expand All @@ -797,15 +800,15 @@ mod tests {
fn print_fraction_as_dms_without_seconds() {
for f in 0..3 {
let d = DecimalDegree::from_deg_and_fraction(60, 5_333_332 + f).unwrap();
let s = format!("{:#}", d);
let s = format!("{d:#}");
assert_eq!(s, "60°32′");
}
}

#[test]
fn print_overflow_fraction_as_dms() {
let d = DecimalDegree::from_deg_and_fraction(59, 9_999_999).unwrap();
let s = format!("{:#}", d);
let s = format!("{d:#}");
assert_eq!(s, "60°");
}

Expand Down Expand Up @@ -858,7 +861,7 @@ mod tests {
}

#[test]
#[should_panic(expected = "assertion failed")]
#[should_panic(expected = "sum overflowed")]
fn summing_dms_accumulate_errors() {
let min = DecimalDegree::from_dms(0, 0, 0, 1).unwrap();

Expand All @@ -868,7 +871,7 @@ mod tests {
acc = acc + min;
}

assert_eq!(acc.milli_arc_seconds(), 10);
assert_eq!(acc.milli_arc_seconds(), 10, "sum overflowed");
}

#[test]
Expand Down
34 changes: 22 additions & 12 deletions types/src/angle/degree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,16 +77,30 @@ macro_rules! impl_conv_traits {

/// Use with caution: the floating numbers has bad precision in the fraction part
fn try_from(value: f64) -> Result<Self, Self::Error> {
if value.is_sign_negative() {
return Err(OutOfRange::Degrees);
fn f64_to_u64(value: f64) -> Result<u64, &'static str> {
if value < 0.0 {
return Err("Value cannot be negative");
}

#[allow(clippy::cast_precision_loss)]
if value > u64::MAX as f64 {
return Err("Value is too large for u64");
}

#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
Ok(value as u64)
}

// prevent wrapping around
let integer = value.floor() as u64;
let integer = f64_to_u64(value.floor()).map_err(|_| {
assert!(value.is_sign_negative());
OutOfRange::Degrees
})?;
let integer = integer.try_into().map_err(|_| OutOfRange::Degrees)?;

let precision = Self::$fraction_multiplier_func();
let fraction = (value.fract() * f64::from(precision)).round() as u64;
let fraction = (value.fract() * f64::from(precision)).round();
let fraction = f64_to_u64(fraction).map_err(|_| OutOfRange::DegreeFraction)?;
let fraction = fraction
.try_into()
.map_err(|_| OutOfRange::DegreeFraction)?;
Expand Down Expand Up @@ -187,23 +201,19 @@ pub(super) fn parse_dms_re(is_ascii: bool, arc_seconds_fd: usize) -> String {
r#"(?x) # enables verbose mode (to allow these comments)
^ # match the whole line from the start
(?P<deg>[123]?\d{{1,2}}) # mandatory degree VALUE (0..=399) - requires more validation!
{} # degree sign (can be mandatory or optional)
{deg} # degree sign (can be mandatory or optional)
(?:\x20? # minutes and seconds group optionally started with the space
(?P<min>[0-5]?\d) # minutes VALUE (0..=59)
{} # arcminute sign
{min} # arcminute sign
(?:\x20? # seconds with the decimal fraction group optionally started with the space
(?P<sec>[0-5]?\d) # whole seconds VALUE (0..=59)
(?: # fractions of arcsecond with the decimal dot
\.(?P<sec_fract>\d{{1,{precision}}}) # fractions of arcsecond VALUE (up to [precision] digits, 0..=99)
\.(?P<sec_fract>\d{{1,{arc_seconds_fd}}}) # fractions of arcsecond VALUE (up to [precision] digits, 0..=99)
)? # fractions of arcsecond are optional
{} # arcsecond sign
{sec} # arcsecond sign
)? # seconds are optional
)? # minutes and seconds are optional
$ # match the whole line till the end
"#,
deg,
min,
sec,
precision = arc_seconds_fd
)
}
15 changes: 9 additions & 6 deletions types/src/angle/dms_dd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,9 @@ impl AccurateDegree {
Ok(())
}

// no panic is possible because the precision
// does not allow for too big whole-degree value (max=2^32 / 9*10^6 ~= 477)
#[allow(clippy::missing_panics_doc)]
/// The whole number of degrees in the angle
pub fn degrees(self) -> u16 {
let degrees = self.units / Self::units_in_deg();
Expand Down Expand Up @@ -789,7 +792,7 @@ mod tests {
#[test]
fn print_zero_as_dms() {
let d = AccurateDegree::default();
let s = format!("{:#}", d);
let s = format!("{d:#}");
assert_eq!(s, "0°");
}

Expand All @@ -802,22 +805,22 @@ mod tests {
#[test]
fn print_right_as_dms() {
let d: AccurateDegree = 90.try_into().unwrap();
let s = format!("{:#}", d);
let s = format!("{d:#}");
assert_eq!(s, "90°");
}

#[test]
fn print_fraction_as_dms() {
let d = AccurateDegree::from_deg_and_fraction(60, 546_718).unwrap();
let s = format!("{:#}", d);
let s = format!("{d:#}");
assert_eq!(s, "60°32′48.18″");
}

#[test]
fn print_fraction_as_dms_without_milli() {
for f in 0..3 {
let d = AccurateDegree::from_deg_and_fraction(60, 546_666 + f).unwrap();
let s = format!("{:#}", d);
let s = format!("{d:#}");
assert_eq!(s, "60°32′48″");
}
}
Expand All @@ -826,15 +829,15 @@ mod tests {
fn print_fraction_as_dms_without_seconds() {
for f in 0..3 {
let d = AccurateDegree::from_deg_and_fraction(60, 533_332 + f).unwrap();
let s = format!("{:#}", d);
let s = format!("{d:#}");
assert_eq!(s, "60°32′");
}
}

#[test]
fn print_overflow_fraction_as_dms() {
let d = AccurateDegree::from_deg_and_fraction(59, 999_999).unwrap();
let s = format!("{:#}", d);
let s = format!("{d:#}");
assert_eq!(s, "60°");
}

Expand Down
8 changes: 4 additions & 4 deletions types/src/angle/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ impl fmt::Display for OutOfRange {
Self::ArcMilliSeconds => "Angle's arc millisecond should be less than 1000",
};

write!(f, "{}", msg)
write!(f, "{msg}")
}
}

Expand All @@ -60,9 +60,9 @@ impl fmt::Display for ParseAngleError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Cannot parse angle: ")?;
match self {
Self::Range(inner) => write!(f, "{}", inner),
Self::Float(inner) => write!(f, "{}", inner),
Self::Int(inner) => write!(f, "{}", inner),
Self::Range(inner) => write!(f, "{inner}"),
Self::Float(inner) => write!(f, "{inner}"),
Self::Int(inner) => write!(f, "{inner}"),
Self::DmsNotation => write!(f, "not a Degree-Minute-Second notation"),
}
}
Expand Down
4 changes: 3 additions & 1 deletion types/src/angle/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,15 @@ pub trait Angle:
Self::straight().checked_sub(&self)
}

#[must_use]
/// Adjacent angle which sum to a [complete](trait.AngleNames.html#tymethod.complete) angle
fn explement(self) -> Self {
Self::complete()
.checked_sub(&self)
.expect("Current implementation stores angles <=360 degrees")
}

#[must_use]
/// Difference between the angles by modulo independent of the order
fn abs_diff(self, rhs: Self) -> Self {
let diff = self.checked_sub(&rhs).or_else(|| rhs.checked_sub(&self));
Expand Down Expand Up @@ -146,7 +148,7 @@ pub trait Angle:
}
}

pub(super) trait UnitsAngle: Angle {
pub trait UnitsAngle: Angle {

Check failure on line 151 in types/src/angle/mod.rs

View workflow job for this annotation

GitHub Actions / Clippy on rust 'stable'

item name ends with its containing module's name

Check failure on line 151 in types/src/angle/mod.rs

View workflow job for this annotation

GitHub Actions / Clippy on rust 'beta'

item name ends with its containing module's name
type Units: CheckedAdd + CheckedSub;

fn from_units(u: Self::Units) -> Result<Self, Self::NumErr>;
Expand Down
20 changes: 10 additions & 10 deletions types/src/coord/lat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ impl<A: Angle> Neg for Latitude<A> {

fn neg(self) -> Self::Output {
let angle = self.angle_from_equator();
#[allow(clippy::option_if_let_else)]
let opposite_pole = match self.hemisphere() {
Some(pole) => -pole,
// just a convention for equator, it means nothing when constructing a Latitude
Expand All @@ -157,9 +158,9 @@ impl<A: Angle> TryFrom<f64> for Latitude<A> {
}
}

impl<A: Angle> TryFrom<(i8, u8, u8, u16)> for Latitude<A>
impl<A> TryFrom<(i8, u8, u8, u16)> for Latitude<A>
where
A: TryFrom<(u16, u8, u8, u16), Error = <A as Angle>::NumErr>,
A: Angle + TryFrom<(u16, u8, u8, u16), Error = <A as Angle>::NumErr>,
{
type Error = A::NumErr;

Expand Down Expand Up @@ -257,25 +258,24 @@ where
}
}

impl<A: Angle> fmt::Display for Latitude<A>
impl<A> fmt::Display for Latitude<A>
where
A: fmt::Display,
A: Angle + fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let angle = self.angle_from_equator();
if f.alternate() {
write!(f, "{:#}", angle)?;
write!(f, "{angle:#}")?;

if let Some(hemisphere) = self.hemisphere() {
write!(f, "{:#}", hemisphere)
} else {
Ok(())
write!(f, "{hemisphere:#}")?

Check failure on line 271 in types/src/coord/lat.rs

View workflow job for this annotation

GitHub Actions / Clippy on rust 'stable'

consider adding a `;` to the last statement for consistent formatting

Check failure on line 271 in types/src/coord/lat.rs

View workflow job for this annotation

GitHub Actions / Clippy on rust 'beta'

consider adding a `;` to the last statement for consistent formatting
}
Ok(())
} else {
if let Some(South) = self.hemisphere() {
if self.hemisphere() == Some(South) {
write!(f, "-")?;
}
write!(f, "{}", angle)
write!(f, "{angle}")
}
}
}
Expand Down
25 changes: 15 additions & 10 deletions types/src/coord/lon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,12 @@ impl<A: Angle> Longitude<A> {
}
}

// no panic is possible because
// the angle always stays:
// - (angle - PI) for angle >= PI (>= 0)
// - (angle + PI) for angle < PI (< 2*PI)
#[allow(clippy::missing_panics_doc)]
#[must_use]
/// Diametrically opposite meridian
/// which together with the current one defines
/// the hemisphere (great circle)
Expand Down Expand Up @@ -203,9 +209,9 @@ impl<A: Angle> TryFrom<f64> for Longitude<A> {
}
}

impl<A: Angle> TryFrom<(i16, u8, u8, u16)> for Longitude<A>
impl<A> TryFrom<(i16, u8, u8, u16)> for Longitude<A>
where
A: TryFrom<(u16, u8, u8, u16), Error = <A as Angle>::NumErr>,
A: Angle + TryFrom<(u16, u8, u8, u16), Error = <A as Angle>::NumErr>,
{
type Error = A::NumErr;

Expand Down Expand Up @@ -295,26 +301,25 @@ where
}
}

impl<A: Angle> fmt::Display for Longitude<A>
impl<A> fmt::Display for Longitude<A>
where
A: fmt::Display,
A: Angle + fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let angle = self.angle();

if f.alternate() {
write!(f, "{:#}", angle)?;
write!(f, "{angle:#}")?;

if let Some(direction) = self.direction() {
write!(f, "{:#}", direction)
} else {
Ok(())
write!(f, "{direction:#}")?

Check failure on line 315 in types/src/coord/lon.rs

View workflow job for this annotation

GitHub Actions / Clippy on rust 'stable'

consider adding a `;` to the last statement for consistent formatting

Check failure on line 315 in types/src/coord/lon.rs

View workflow job for this annotation

GitHub Actions / Clippy on rust 'beta'

consider adding a `;` to the last statement for consistent formatting
}
Ok(())
} else {
if let Some(West) = self.direction() {
if self.direction() == Some(West) {
write!(f, "-")?;
}
write!(f, "{}", angle)
write!(f, "{angle}")
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions types/src/coord/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl<A: Error> fmt::Display for ParseCoordinateError<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Coordinate parsing failed: ")?;
match self {
Self::Angle(inner) => write!(f, "{}", inner),
Self::Angle(inner) => write!(f, "{inner}"),
Self::EmptyString => write!(f, "empty string provided"),
Self::NoHemisphere => write!(f, "direction (hemisphere) was not detected"),
}
Expand Down Expand Up @@ -128,7 +128,7 @@ macro_rules! bool_enum {
($name:ident: $truthy:ident and $falsy:ident; parse from $true_ch:literal:$false_ch:literal with $parse_err:ident) => {
use self::$name::{$falsy, $truthy};

#[derive(Debug, Copy, Clone, PartialEq)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum $name {
$truthy,
$falsy,
Expand Down
Loading

0 comments on commit fb9b972

Please sign in to comment.