Skip to main content

ingrid/
coordinate.rs

1// Copyright (c) 2020 - BytePlug
2//
3// This source file is part of Ingrid which is released under the MIT license.
4// Please refer to the LICENSE file that can be found at the root of the project
5// directory.
6//
7// Written by Jonathan De Wachter <dewachter.jonathan@gmail.com>, January 2020
8
9/// A two-dimensional coordinate
10///
11/// This structure defines a basic two-dimensional coordinate to index grids. It
12/// enables copy semantics to avoid handling ownership and references
13/// throughout your code for no significant performance. Also, in practice, you
14/// use the `coord!` macro helper to instantiate coordinates.
15///
16/// # Examples
17///
18/// ```
19/// # use ingrid::{Coordinate, coord};
20/// #
21/// // Create a coordinate to index the top-left element of a grid.
22/// let mut coord1 = coord!(0, 0);
23///
24/// // Copy the coordinate into another variable.
25/// let coord2 = coord1;
26///
27/// // The first variable is still accessible.
28/// coord1.x = 42;
29/// coord1.y += 1;
30///
31/// // Additionally, you could also type the following.
32/// let coord3 = Coordinate::zero();
33/// ```
34///
35#[derive(Debug, Copy, Clone, Eq, PartialEq)]
36pub struct Coordinate {
37    /// The coordinate on the X axis.
38    pub x: usize,
39
40    /// The coordinate on the Y axis.
41    pub y: usize
42}
43
44impl Coordinate {
45    /// Construct a new coordinate.
46    ///
47    /// This function constructs a new coordinate from given X and Y values.
48    ///
49    /// # Examples
50    ///
51    /// ```
52    /// # use ingrid::Coordinate;
53    /// #
54    /// let coord = Coordinate::new(0, 42);
55    ///
56    /// assert_eq!(coord.x, 0);
57    /// assert_eq!(coord.y, 42);
58    /// ```
59    ///
60    pub fn new(x: usize, y: usize) -> Coordinate {
61        Coordinate { x, y }
62    }
63
64    /// Construct a zero coordinate.
65    ///
66    /// This function constructs a 'zero' coordinate which is a coordinate with
67    /// both `x` and `y` values set at `0`.
68    ///
69    /// # Examples
70    ///
71    /// ```
72    /// # use ingrid::Coordinate;
73    /// #
74    /// let coord = Coordinate::zero();
75    ///
76    /// assert_eq!(coord.x, 0);
77    /// assert_eq!(coord.y, 0);
78    /// ```
79    ///
80    pub fn zero() -> Coordinate {
81        Coordinate { x: 0, y: 0 }
82    }
83}
84
85/// A coordinate instantiation helper.
86///
87/// This macro helps instantiate coordinates with a shorter syntax. Instead of
88/// typing a full `Coordinate::new(x, y)`, one simply has to write
89/// `coord!(x, y)` leading to more readable code.
90///
91/// # Examples
92///
93/// ```
94/// # use ingrid::{Coordinate, coord};
95/// assert_eq!(coord!(0, 0), Coordinate::new(0, 0));
96/// ```
97///
98#[macro_export]
99macro_rules! coord {
100    ($x:expr, $y:expr) => {
101        Coordinate::new($x, $y);
102    };
103}