use crate::core::geo::geo_utils::GeoUtils;
use crate::core::geo::geometry::Geometry;
use crate::core::geo::lat_lon_geometry::LatLonGeometry;
use crate::core::geo::line2d::{Line2D, create_from_line};
use crate::core::util::bit_util::BitUtil;
use crate::core::util::core_helper::CoreHelper;
use crate::core::util::error::lucene_error::{LuceneError, Result};
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};
#[derive(Debug, Clone)]
pub struct Line {
lats: Vec<f64>,
lons: Vec<f64>,
pub min_lat: f64,
pub max_lat: f64,
pub min_lon: f64,
pub max_lon: f64,
}
impl Line {
pub fn new<A, B>(lats: A, lons: B) -> Result<Self>
where
A: Into<Vec<f64>>,
B: Into<Vec<f64>>,
{
let lats = lats.into();
let lons = lons.into();
if lats.len() != lons.len() {
return Err(LuceneError::illegal_argument(
"lats and lons must be equal length",
));
}
if lats.len() < 2 {
return Err(LuceneError::illegal_argument(
"at least 2 line points required",
));
}
let mut min_lat = lats[0];
let mut min_lon = lons[0];
let mut max_lat = lats[0];
let mut max_lon = lons[0];
for i in 0..lats.len() {
GeoUtils::check_latitude(lats[i])?;
GeoUtils::check_longitude(lons[i])?;
min_lat = CoreHelper::min_f64(lats[i], min_lat);
min_lon = CoreHelper::min_f64(lons[i], min_lon);
max_lat = CoreHelper::max_f64(lats[i], max_lat);
max_lon = CoreHelper::max_f64(lons[i], max_lon);
}
Ok(Self {
lats,
lons,
min_lat,
max_lat,
min_lon,
max_lon,
})
}
pub fn num_points(&self) -> usize {
self.lats.len()
}
pub fn get_lat(&self, vertex: usize) -> f64 {
self.lats[vertex]
}
pub fn get_lon(&self, vertex: usize) -> f64 {
self.lons[vertex]
}
pub fn get_lats(&self) -> &[f64] {
self.lats.as_slice()
}
pub fn get_lons(&self) -> &[f64] {
self.lons.as_slice()
}
}
impl PartialEq for Line {
fn eq(&self, other: &Self) -> bool {
CoreHelper::array_equals_f64(&self.lats, &other.lats)
&& CoreHelper::array_equals_f64(&self.lons, &other.lons)
}
}
impl Eq for Line {}
impl Hash for Line {
fn hash<H: Hasher>(&self, state: &mut H) {
for lat in &self.lats {
(BitUtil::double_to_long_bits(*lat) as u64).hash(state);
}
for lon in &self.lons {
(BitUtil::double_to_long_bits(*lon) as u64).hash(state);
}
}
}
impl Display for Line {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "Line(")?;
for i in 0..self.lats.len() {
write!(f, "[{}, {}]", self.lons[i], self.lats[i])?;
}
write!(f, ")")
}
}
impl Geometry for Line {
type Component2D = Line2D;
fn to_component2d(&self) -> Result<Self::Component2D> {
create_from_line(self)
}
}
impl LatLonGeometry for Line {}