screencapturekit/cg/
point.rs

1//! `CGPoint` type for 2D coordinates
2
3use std::fmt;
4
5/// `CGPoint` representation
6///
7/// Represents a point in 2D space.
8///
9/// # Examples
10///
11/// ```
12/// use screencapturekit::cg::CGPoint;
13///
14/// let p1 = CGPoint::new(0.0, 0.0);
15/// let p2 = CGPoint::new(3.0, 4.0);
16/// assert_eq!(p1.distance_to(&p2), 5.0);
17/// ```
18#[repr(C)]
19#[derive(Debug, Clone, Copy, PartialEq)]
20pub struct CGPoint {
21    pub x: f64,
22    pub y: f64,
23}
24
25impl std::hash::Hash for CGPoint {
26    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
27        self.x.to_bits().hash(state);
28        self.y.to_bits().hash(state);
29    }
30}
31
32impl Eq for CGPoint {}
33
34impl CGPoint {
35    /// Create a new point
36    ///
37    /// # Examples
38    ///
39    /// ```
40    /// use screencapturekit::cg::CGPoint;
41    ///
42    /// let point = CGPoint::new(100.0, 200.0);
43    /// assert_eq!(point.x, 100.0);
44    /// ```
45    pub const fn new(x: f64, y: f64) -> Self {
46        Self { x, y }
47    }
48
49    /// Create a point at origin (0, 0)
50    ///
51    /// # Examples
52    ///
53    /// ```
54    /// use screencapturekit::cg::CGPoint;
55    ///
56    /// let point = CGPoint::zero();
57    /// assert!(point.is_zero());
58    /// ```
59    pub const fn zero() -> Self {
60        Self::new(0.0, 0.0)
61    }
62
63    /// Check if point is at origin (0, 0)
64    pub const fn is_zero(&self) -> bool {
65        self.x == 0.0 && self.y == 0.0
66    }
67
68    /// Calculate distance to another point
69    pub fn distance_to(&self, other: &Self) -> f64 {
70        let dx = self.x - other.x;
71        let dy = self.y - other.y;
72        dx.hypot(dy)
73    }
74
75    /// Calculate squared distance to another point (faster than `distance_to`)
76    pub const fn distance_squared_to(&self, other: &Self) -> f64 {
77        let dx = self.x - other.x;
78        let dy = self.y - other.y;
79        dx * dx + dy * dy
80    }
81}
82
83impl Default for CGPoint {
84    fn default() -> Self {
85        Self::zero()
86    }
87}
88
89impl fmt::Display for CGPoint {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        write!(f, "({}, {})", self.x, self.y)
92    }
93}