ratatui_core/layout/
offset.rs

1use crate::layout::Position;
2
3/// Amounts by which to move a [`Rect`](crate::layout::Rect).
4///
5/// Positive numbers move to the right/bottom and negative to the left/top.
6///
7/// See [`Rect::offset`](crate::layout::Rect::offset) for usage.
8#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
9#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
10pub struct Offset {
11    /// How much to move on the X axis
12    pub x: i32,
13
14    /// How much to move on the Y axis
15    pub y: i32,
16}
17
18impl Offset {
19    /// A zero offset
20    pub const ZERO: Self = Self::new(0, 0);
21
22    /// The minimum offset
23    pub const MIN: Self = Self::new(i32::MIN, i32::MIN);
24
25    /// The maximum offset
26    pub const MAX: Self = Self::new(i32::MAX, i32::MAX);
27
28    /// Creates a new `Offset` with the given values.
29    pub const fn new(x: i32, y: i32) -> Self {
30        Self { x, y }
31    }
32}
33
34impl From<Position> for Offset {
35    fn from(position: Position) -> Self {
36        Self {
37            x: i32::from(position.x),
38            y: i32::from(position.y),
39        }
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn new_sets_components() {
49        assert_eq!(Offset::new(-3, 7), Offset { x: -3, y: 7 });
50    }
51
52    #[test]
53    fn constants_match_expected_values() {
54        assert_eq!(Offset::ZERO, Offset::new(0, 0));
55        assert_eq!(Offset::MIN, Offset::new(i32::MIN, i32::MIN));
56        assert_eq!(Offset::MAX, Offset::new(i32::MAX, i32::MAX));
57    }
58
59    #[test]
60    fn from_position_converts_coordinates() {
61        let position = Position::new(4, 9);
62        let offset = Offset::from(position);
63
64        assert_eq!(offset, Offset::new(4, 9));
65    }
66}