//! Angle helpers (all angles in degrees). /// Normalizes an angle into `[0, 360)`. pub fn normalize(deg: f64) -> f64 { let r = deg.rem_euclid(360.0); // rem_euclid can return 360.0 for tiny negative inputs due to rounding if r >= 360.0 { 0.0 } else { r } } /// Shortest angular distance between two longitudes, in `[0, 180]`. pub fn separation(a: f64, b: f64) -> f64 { let d = normalize(a - b); if d > 180.0 { 360.0 - d } else { d } } /// Forward arc from `from` to `to` (counter-clockwise, increasing longitude), in `[0, 360)`. pub fn arc(from: f64, to: f64) -> f64 { normalize(to - from) } /// Formats an unsigned angle as `DD°MM'SS"`. pub fn dms(deg: f64) -> String { let (d, m, s) = split_dms(deg.abs()); format!("{d}°{m:02}'{s:02}\"") } /// Formats a signed angle as `+DD°MM'SS"` / `-DD°MM'SS"`. pub fn signed_dms(deg: f64) -> String { let sign = if deg < 0.0 { '-' } else { '+' }; format!("{sign}{}", dms(deg)) } /// Formats hours as `HH:MM:SS`. pub fn hms(hours: f64) -> String { let (h, m, s) = split_dms(hours.rem_euclid(24.0)); format!("{:02}:{m:02}:{s:02}", h % 24) } /// Splits a non-negative value into whole units, minutes and seconds, rounding /// to the nearest second without producing 60 minutes or seconds. fn split_dms(value: f64) -> (u32, u32, u32) { let total = (value * 3600.0).round() as u64; ((total / 3600) as u32, ((total / 60) % 60) as u32, (total % 60) as u32) } #[cfg(test)] mod tests { use super::*; #[test] fn normalizes() { assert_eq!(normalize(-10.0), 350.0); assert_eq!(normalize(720.5), 0.5); assert_eq!(normalize(-1e-15), 0.0); } #[test] fn separations() { assert_eq!(separation(350.0, 10.0), 20.0); assert_eq!(separation(10.0, 190.0), 180.0); assert_eq!(arc(350.0, 10.0), 20.0); } #[test] fn formats() { assert_eq!(dms(21.8866), "21°53'12\""); assert_eq!(dms(29.99999), "30°00'00\""); assert_eq!(signed_dms(-1.5), "-1°30'00\""); assert_eq!(hms(25.5), "01:30:00"); } }