reda_geometry/shape/
text.rs

1use crate::shape::Point;
2use crate::traits::{BoundingBox, MapPoint};
3use std::fmt;
4use std::hash::Hash;
5use std::ops::Deref;
6
7use super::Rect;
8
9pub trait TextType: Eq + Hash + Clone + fmt::Debug {}
10
11#[derive(Debug, Clone, Hash, PartialEq, Eq)]
12#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
13pub struct Text<T, S = String> {
14    location: Point<T>,
15    text: S,
16}
17
18impl<T, S: TextType> Text<T, S> {
19    /// Create a new text object.
20    pub fn new(text: S, location: Point<T>) -> Self {
21        Text { location, text }
22    }
23
24    /// Get a reference to the text string.
25    pub fn text(&self) -> &S {
26        &self.text
27    }
28}
29
30impl<T: Copy, S: TextType> Text<T, S> {
31    /// Get location of the text label.
32    #[inline]
33    pub fn location(&self) -> Point<T> {
34        self.location
35    }
36
37    /// Get x-coordinate of the label location.
38    #[inline]
39    pub fn x(&self) -> T {
40        self.location.x
41    }
42
43    /// Get y-coordinate of the label location.
44    #[inline]
45    pub fn y(&self) -> T {
46        self.location.y
47    }
48}
49
50/// Display format of the text label.
51impl<T, S> fmt::Display for Text<T, S>
52where
53    T: fmt::Display,
54    S: TextType + fmt::Display,
55{
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        write!(f, "Text({}, {})", self.text, self.location)
58    }
59}
60
61impl<T, S> Deref for Text<T, S>
62where
63    S: Deref<Target = String>,
64{
65    type Target = String;
66
67    /// Dereference to String.
68    fn deref(&self) -> &Self::Target {
69        self.text.deref()
70    }
71}
72
73impl<T, S> MapPoint<T> for Text<T, S>
74where
75    T: Copy,
76    S: Clone,
77{
78    /// Point wise transformation.
79    #[inline]
80    fn transform<F>(&self, transformation: F) -> Self
81    where
82        F: Fn(Point<T>) -> Point<T>,
83    {
84        Text {
85            location: transformation(self.location),
86            text: self.text.clone(),
87        }
88    }
89}
90
91impl<T: Copy + PartialOrd, S> BoundingBox<T> for Text<T, S> {
92    fn bounding_box(&self) -> Rect<T> {
93        Rect::new(self.location, self.location)
94    }
95}