use crate::core::geo::geometry::Geometry;
use crate::core::geo::line2d::{Line2D, create_from_xy_line};
use crate::core::geo::xy_encoding_utils::XYEncodingUtils;
use crate::core::geo::xy_geometry::XYGeometry;
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 XYLine {
x: Vec<f32>,
y: Vec<f32>,
pub min_x: f32,
pub max_x: f32,
pub min_y: f32,
pub max_y: f32,
}
impl XYLine {
pub fn new<A, B>(x: A, y: B) -> Result<Self>
where
A: Into<Vec<f32>>,
B: Into<Vec<f32>>,
{
let x = x.into();
let y = y.into();
if x.len() != y.len() {
return Err(LuceneError::illegal_argument(
"x and y must be equal length",
));
}
if x.len() < 2 {
return Err(LuceneError::illegal_argument(
"at least 2 line points required",
));
}
let mut min_x = f32::MAX;
let mut min_y = f32::MAX;
let mut max_x = -f32::MAX;
let mut max_y = -f32::MAX;
for i in 0..x.len() {
min_x = CoreHelper::min_f32(XYEncodingUtils::check_val(x[i])?, min_x);
min_y = CoreHelper::min_f32(XYEncodingUtils::check_val(y[i])?, min_y);
max_x = CoreHelper::max_f32(x[i], max_x);
max_y = CoreHelper::max_f32(y[i], max_y);
}
Ok(Self {
x,
y,
min_x,
max_x,
min_y,
max_y,
})
}
pub fn num_points(&self) -> usize {
self.x.len()
}
pub fn get_x(&self, vertex: usize) -> f32 {
self.x[vertex]
}
pub fn get_y(&self, vertex: usize) -> f32 {
self.y[vertex]
}
pub fn get_xs(&self) -> &[f32] {
self.x.as_slice()
}
pub fn get_ys(&self) -> &[f32] {
self.y.as_slice()
}
}
impl Geometry for XYLine {
type Component2D = Line2D;
fn to_component2d(&self) -> Result<Self::Component2D> {
create_from_xy_line(self)
}
}
impl XYGeometry for XYLine {}
impl PartialEq for XYLine {
fn eq(&self, other: &Self) -> bool {
CoreHelper::array_equals_f32(&self.x, &other.x)
&& CoreHelper::array_equals_f32(&self.y, &other.y)
}
}
impl Eq for XYLine {}
impl Hash for XYLine {
fn hash<H: Hasher>(&self, state: &mut H) {
for x in &self.x {
(BitUtil::float_to_int_bits(*x) as u32).hash(state);
}
for y in &self.y {
(BitUtil::float_to_int_bits(*y) as u32).hash(state);
}
}
}
impl Display for XYLine {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "XYLine(")?;
for i in 0..self.x.len() {
write!(f, "[{}, {}]", self.x[i], self.y[i])?;
}
write!(f, ")")
}
}