minlin 0.4.0

Rust library with minimal linear algebra made to be as convinient as possible.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
use std::{
    cmp::Ordering,
    fmt::Display,
    ops::{
        Add, AddAssign, Bound, Div, DivAssign, Index, IndexMut, Mul,
        MulAssign, Neg, Range, RangeBounds, Rem, RemAssign, Sub, SubAssign,
    },
};

use crate::{
    Checked, Float, Goniometric, IntoFloat, Isqrt, LargeType, MapExt,
    NormalLimits, Scale, Sqrt, Vec2RangeIter, Zero,
};

/// Represents two dimensional vector. Can be used as vector, point, size or
/// any tuple-like object where vector math operations are benefit.
///
/// It is meant to be as convinient as possible to work with in many use cases.
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
pub struct Vec2<T = usize> {
    /// The first coordinate of the vector (x, w, [0]).
    pub x: T,
    /// The second coordinate of the vector (y, h, [1])
    pub y: T,
}

impl<T> Vec2<T> {
    /// Creates new two dimensional vector from its components.
    pub const fn new(x: T, y: T) -> Self {
        Self { x, y }
    }

    /// Get the width. Alias to the first coordinate (x, [0])
    pub fn w(&self) -> &T {
        &self.x
    }

    /// Get the height. Alias to the second coorinate (y, [1])
    pub fn h(&self) -> &T {
        &self.y
    }

    /// Get the width. Alias to the first coordinate (x, [0])
    pub fn w_mut(&mut self) -> &mut T {
        &mut self.x
    }

    /// Get the height. Alias to the second coorinate (y, [1])
    pub fn h_mut(&mut self) -> &mut T {
        &mut self.y
    }

    /// Set the width. Alias to the first coordinate (x, [0])
    pub fn set_w(&mut self, w: T) {
        self.x = w;
    }

    /// Set the height. Alias to the second coorinate (y, [1])
    pub fn set_h(&mut self, h: T) {
        self.y = h;
    }

    /// Gets the length (absolute value) of the vector squared.
    pub fn sq_len(&self) -> <T::Output as Add>::Output
    where
        T: Copy + Mul<T>,
        T::Output: Add<T::Output>,
    {
        self.dot(*self)
    }

    /// Gets fractional length (absolute value) of the vector.
    pub fn len(&self) -> <<T::Output as Add>::Output as Sqrt>::Output
    where
        T: Copy + Mul<T>,
        T::Output: Add<T::Output>,
        <T::Output as Add>::Output: Sqrt,
    {
        self.sq_len().sqrt()
    }

    /// Gets the integer length (absolute value) of the vector.
    pub fn ilen(&self) -> <T::Output as Add>::Output
    where
        T: Copy + Mul<T>,
        T::Output: Add<T::Output>,
        <T::Output as Add>::Output: Isqrt,
    {
        self.sq_len().isqrt()
    }

    /// Calculates the dot product of the two vectors.
    pub fn dot<Right>(
        self,
        other: impl Into<Vec2<Right>>,
    ) -> <T::Output as Add>::Output
    where
        T: Mul<Right>,
        T::Output: Add,
    {
        let o = other.into();
        self.x * o.x + self.y * o.y
    }

    /// Checked add of two vectors.
    ///
    /// Returns [`None`] if addition of any of the components fails.
    pub fn checked_add(self, other: impl Into<Vec2<T>>) -> Option<Vec2<T>>
    where
        T: Checked,
    {
        let o = other.into();
        Some(Self::new(
            self.x.checked_add(o.x)?,
            self.y.checked_add(o.y)?,
        ))
    }

    /// Checked subtraction of two vectors.
    ///
    /// Returns [`None`] if subtraction of any of the components fails.
    pub fn checked_sub(self, other: impl Into<Vec2<T>>) -> Option<Vec2<T>>
    where
        T: Checked,
    {
        let o = other.into();
        Some(Self::new(
            self.x.checked_sub(o.x)?,
            self.y.checked_sub(o.y)?,
        ))
    }

    /// Checked componentwise multiplication of two vectors.
    ///
    /// Returns [`None`] if multiplication of any of the components fails.
    pub fn checked_cmul(self, other: impl Into<Vec2<T>>) -> Option<Vec2<T>>
    where
        T: Checked,
    {
        let o = other.into();
        Some(Self::new(
            self.x.checked_mul(o.x)?,
            self.y.checked_mul(o.y)?,
        ))
    }

    /// Sums the components.
    pub fn sum(self) -> T::Output
    where
        T: Add,
    {
        self.x + self.y
    }

    /// Subtracts the components.
    pub fn diff(self) -> T::Output
    where
        T: Sub,
    {
        self.x - self.y
    }

    /// Calculates the absolute difference of the components.
    pub fn abs_diff(self) -> T::Output
    where
        T: Sub + Ord,
    {
        if self.x < self.y {
            self.y - self.x
        } else {
            self.x - self.y
        }
    }

    /// Multiplies the components.
    pub fn prod(self) -> T::Output
    where
        T: Mul,
    {
        self.x * self.y
    }

    /// Divides the components.
    pub fn quot(self) -> T::Output
    where
        T: Div,
    {
        self.x / self.y
    }

    /// Gets the remainder of division of the components.
    pub fn quot_rem(self) -> T::Output
    where
        T: Rem,
    {
        self.x % self.y
    }

    /// Checks if the components are same.
    pub fn same(&self) -> bool
    where
        T: PartialEq,
    {
        self.x == self.y
    }

    /// Checks if the components are different.
    pub fn different(&self) -> bool
    where
        T: PartialEq,
    {
        self.x != self.y
    }

    /// Gets index of the max component.
    pub fn max_idx(&self) -> usize
    where
        T: Ord,
    {
        if self.y > self.x { 1 } else { 0 }
    }

    /// Get the larger of the two components. If both are same, x is returned.
    pub fn max(&self) -> &T
    where
        T: Ord,
    {
        if self.y > self.x { &self.y } else { &self.x }
    }

    /// Gets mutable reference to the largest element.
    pub fn max_mut(&mut self) -> &mut T
    where
        T: Ord,
    {
        if self.y > self.x {
            &mut self.y
        } else {
            &mut self.x
        }
    }

    /// Gets index to the smallest component.
    pub fn min_idx(&self) -> usize
    where
        T: Ord,
    {
        if self.y < self.x { 1 } else { 0 }
    }

    /// The the smaller of the two components. If both are same, x is returned.
    pub fn min(&self) -> &T
    where
        T: Ord,
    {
        if self.y < self.x { &self.y } else { &self.x }
    }

    /// The the smaller of the two components. If both are same, x is returned.
    pub fn min_mut(&mut self) -> &mut T
    where
        T: Ord,
    {
        if self.y < self.x {
            &mut self.y
        } else {
            &mut self.x
        }
    }

    /// Converts vector reference to vector of reference.
    pub fn as_ref(&self) -> Vec2<&T> {
        (&self.x, &self.y).into()
    }

    /// Construct vector of mutable references to the components of the vector.
    pub fn as_mut(&mut self) -> Vec2<&mut T> {
        (&mut self.x, &mut self.y).into()
    }

    /// Checks if both of the components satisfy the condition.
    pub fn are_both(&self, mut f: impl FnMut(&T) -> bool) -> bool {
        f(&self.x) && f(&self.y)
    }

    /// Checks if any of the components satisfies the condition.
    pub fn is_any(&self, mut f: impl FnMut(&T) -> bool) -> bool {
        f(&self.x) || f(&self.y)
    }

    /// Checks if exactly one of the components satisfies the given condition.
    pub fn is_one(&self, f: impl FnMut(&T) -> bool) -> bool {
        self.as_ref().map(f).one()
    }

    /// Checks if no component satisfies the condition.
    pub fn is_none(&self, f: impl FnMut(&T) -> bool) -> bool {
        !self.is_any(f)
    }

    /// Iterate over the two components.
    pub fn iter(&self) -> std::array::IntoIter<&T, 2> {
        let r: [_; 2] = self.as_ref().into();
        r.into_iter()
    }

    /// Get mutable iterator over the two components.
    pub fn iter_mut(&mut self) -> std::array::IntoIter<&mut T, 2> {
        let r: [_; 2] = self.as_mut().into();
        r.into_iter()
    }

    /// Swaps the two components.
    pub fn swap(&mut self) {
        std::mem::swap(&mut self.x, &mut self.y);
    }

    /// Swaps the two components.
    pub fn swapped(self) -> Self {
        (self.y, self.x).into()
    }

    /// Swaps the two components.
    pub fn yx(self) -> Self {
        self.swapped()
    }

    /// Identity
    pub fn xy(self) -> Self {
        self
    }

    /// Sort the components.
    pub fn sort(&mut self)
    where
        T: PartialOrd,
    {
        if self.x > self.y {
            self.swap();
        }
    }

    /// Sort the components.
    pub fn sorted(mut self) -> Self
    where
        T: PartialOrd,
    {
        self.sort();
        self
    }

    /// Clamp the value to the range in this vector.
    pub fn clamp<'a>(&'a self, v: &'a T) -> &'a T
    where
        T: Ord,
    {
        let s = self.as_ref().sorted();
        if v < s.x {
            s.x
        } else if v > s.y {
            s.y
        } else {
            v
        }
    }

    /// Clamp the value to the range in this vector.
    pub fn clamped(mut self, v: T) -> T
    where
        T: Ord,
    {
        self.sort();
        if v < self.x {
            self.x
        } else if v > self.y {
            self.y
        } else {
            v
        }
    }

    /// Get 2D position in 2D space with the size of self represented by 1D
    /// container from index into the 1D container.
    ///
    /// This is inverse opration to [`Self::idx_of_pos`].
    ///
    /// E.g. if we have [`Vec`] representing 2D space with dimesions given in
    /// this [`Vec2`], we can give index into the [`Vec`], and this will return
    /// position of that element within the 2D space of size given by this
    /// [`Vec2`].
    pub fn pos_of_idx<I, R>(self, i: I) -> Vec2<R>
    where
        T: Copy,
        I: Copy + Rem<T, Output = R> + Div<T, Output = R>,
    {
        (i % self.y, i / self.y).into()
    }

    /// Get index corresponding to pos to 1D container that represents 2D space
    /// with size of this.
    ///
    /// This is inverse opration to [`Self::pos_of_idx`].
    ///
    /// E.g. if we have [`Vec`] representing 2D space with dimentions given in
    /// this [`Vec2`], we give position within the 2D space, and this will
    /// return index into the [`Vec`].
    pub fn idx_of_pos<R>(
        self,
        pos: impl Into<Vec2<R>>,
    ) -> <T::Output as Add<R>>::Output
    where
        T: Mul<R>,
        T::Output: Add<R>,
    {
        let pos = pos.into();
        self.x * pos.y + pos.x
    }

    /// Get the angle of the vector.
    pub fn angle(self) -> T::Output
    where
        T: Goniometric,
    {
        T::atan2(self.y, self.x)
    }

    /// Calculate the polar coordinates of the vector.
    pub fn polar(
        self,
    ) -> (
        <<<T as Mul>::Output as Add>::Output as Sqrt>::Output,
        <T as Goniometric>::Output,
    )
    where
        T: Copy + Mul + Goniometric,
        <T as Mul>::Output: Add,
        <<T as Mul>::Output as Add>::Output: Sqrt,
    {
        (self.len(), self.angle())
    }

    /// Gets normalized version of the vector as float.
    #[allow(clippy::type_complexity)]
    pub fn normalized(
        self,
    ) -> Vec2<
        <T::Float as Div<
            <<<T::Float as Mul>::Output as Add>::Output as Sqrt>::Output,
        >>::Output,
    >
    where
        T: IntoFloat,
        T::Float: Copy + Mul,
        <T::Float as Mul>::Output: Add<<T::Float as Mul>::Output>,
        <<T::Float as Mul>::Output as Add>::Output: Sqrt,
        <<<T::Float as Mul>::Output as Add>::Output as Sqrt>::Output: Copy,
        T::Float:
            Div<<<<T::Float as Mul>::Output as Add>::Output as Sqrt>::Output>,
    {
        let v = self.map(|a| a.into_float());
        let len = v.len();
        (v.x / len, v.y / len).into()
    }

    /// Normalizes this vector.
    pub fn normalize(&mut self)
    where
        T: Copy + Float + Mul,
        T::Output: Add<T::Output>,
        <T::Output as Add>::Output: Sqrt,
        <<T::Output as Add>::Output as Sqrt>::Output: Copy,
        T: DivAssign<<<T::Output as Add>::Output as Sqrt>::Output>,
    {
        *self /= self.len();
    }

    /// Craetes range from this vector to the other vector.
    pub fn to(self, other: impl Into<Vec2<T>>) -> Vec2RangeIter<T>
    where
        T: Copy,
    {
        Vec2RangeIter::new(self, other.into())
    }

    /// Creates vector from polar coordinates.
    pub fn from_polar<L, A>(length: L, angle: A) -> Self
    where
        A: Copy + Float + Goniometric,
        A::Output: Mul<L, Output = T>,
        L: Copy,
    {
        Vec2::new(angle.cos(), angle.sin()) * length
    }

    /// Check if 2D space of this size contains pos.
    pub fn size_contains(&self, pos: impl Into<Vec2<T>>) -> bool
    where
        T: PartialOrd + Zero,
    {
        let pos = pos.into();
        pos.are_both(|a| *a >= T::ZERO) && pos.x < self.x && pos.y < self.y
    }

    /// Scales the vector to different type. Floating point types are in range
    /// 0..=1 where integer types are in range MIN..=MAX.
    pub fn scale<S>(self) -> Vec2<S>
    where
        T: Scale<S>,
    {
        (self.x.scale(), self.y.scale()).into()
    }

    /// Change the range of values from `ss..=se` to `ds..=de`.
    pub fn change_range(self, ss: T, se: T, ds: T, de: T) -> Vec2<T>
    where
        T: LargeType + Copy + Sub<Output = T>,
        T::Large: Add<Output = T::Large>
            + Sub<Output = T::Large>
            + Mul<Output = T::Large>
            + Div<Output = T::Large>,
    {
        self.map(|a| {
            T::from_large(
                (a.to_large() - ss.to_large()) * (de - ds).to_large()
                    / (se - ss).to_large()
                    + ds.to_large(),
            )
        })
    }

    /// Transform values from normal range to the given range.
    pub fn norm_to_range(self, s: T, e: T) -> Vec2<T>
    where
        T: LargeType + Copy + NormalLimits + Sub<Output = T>,
        T::Large: Add<Output = T::Large>
            + Sub<Output = T::Large>
            + Mul<Output = T::Large>
            + Div<Output = T::Large>,
    {
        self.change_range(T::NORM_MIN, T::NORM_MAX, s, e)
    }

    /// Transform values from the given range to normal range.
    pub fn to_norm_range(self, s: T, e: T) -> Vec2<T>
    where
        T: LargeType + Copy + NormalLimits + Sub<Output = T>,
        T::Large: Add<Output = T::Large>
            + Sub<Output = T::Large>
            + Mul<Output = T::Large>
            + Div<Output = T::Large>,
    {
        self.change_range(s, e, T::NORM_MIN, T::NORM_MAX)
    }

    /// Calculate the absolute value of each component.
    pub fn cabs(self) -> Vec2<T>
    where
        T: PartialOrd + Zero + Neg<Output = T>,
    {
        self.map(|a| if a < T::ZERO { -a } else { a })
    }

    /// Create range from this. The range will iterate over its range of values.
    pub fn range(self) -> Range<T> {
        self.into()
    }

    /// Combine the two vector based on selector. `true` -> value from other.
    pub fn combine(
        self,
        other: impl Into<Vec2<T>>,
        selector: impl Into<Vec2<bool>>,
    ) -> Self {
        let s = selector.into();
        let o = other.into();
        Vec2::new(
            if s.x { o.x } else { self.x },
            if s.y { o.y } else { self.y },
        )
    }
}

impl Vec2<bool> {
    /// Checks if both are true.
    pub fn both(self) -> bool {
        self.x & self.y
    }

    /// Checks if any of the components is true.
    pub fn any(self) -> bool {
        self.x | self.y
    }

    /// Returns true if only one of the components is true.
    pub fn one(self) -> bool {
        self.different()
    }

    /// Checks if bot of the components are false.
    pub fn none(self) -> bool {
        !self.any()
    }
}

impl<T> Vec2<&T> {
    /// Clones the values in references of the vector.
    pub fn cloned(self) -> Vec2<T>
    where
        T: Clone,
    {
        (self.x.clone(), self.y.clone()).into()
    }

    /// Copies the values in references of the vector.
    pub fn copied(self) -> Vec2<T>
    where
        T: Copy,
    {
        (*self.x, *self.y).into()
    }
}

impl<T: Zero> Vec2<T> {
    /// 2D vectors with all components set to zero.
    pub const ZERO: Vec2<T> = Vec2 {
        x: T::ZERO,
        y: T::ZERO,
    };
}

impl<T> From<(T, T)> for Vec2<T> {
    fn from((x, y): (T, T)) -> Self {
        Self { x, y }
    }
}

impl<T> From<[T; 2]> for Vec2<T> {
    fn from([x, y]: [T; 2]) -> Self {
        Self { x, y }
    }
}

impl<T> From<Range<T>> for Vec2<T> {
    fn from(value: Range<T>) -> Self {
        Self {
            x: value.start,
            y: value.end,
        }
    }
}

impl<T> From<Vec2<T>> for (T, T) {
    fn from(value: Vec2<T>) -> Self {
        (value.x, value.y)
    }
}

impl<T> From<Vec2<T>> for [T; 2] {
    fn from(value: Vec2<T>) -> Self {
        [value.x, value.y]
    }
}

impl<T> From<Vec2<T>> for Range<T> {
    fn from(value: Vec2<T>) -> Self {
        value.x..value.y
    }
}

impl<T> RangeBounds<T> for Vec2<T> {
    fn start_bound(&self) -> Bound<&T> {
        Bound::Included(&self.x)
    }

    fn end_bound(&self) -> Bound<&T> {
        Bound::Excluded(&self.y)
    }
}

impl<T> Index<usize> for Vec2<T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        match index {
            0 => &self.x,
            1 => &self.y,
            _ => panic!("Index `{index}` is out of bounds for Vec2."),
        }
    }
}

impl<T> IndexMut<usize> for Vec2<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        match index {
            0 => &mut self.x,
            1 => &mut self.y,
            _ => panic!("Index `{index}` is out of bounds for Vec2."),
        }
    }
}

impl<Left, Right> PartialEq<(Right, Right)> for Vec2<Left>
where
    Left: PartialEq<Right>,
{
    fn eq(&self, (x, y): &(Right, Right)) -> bool {
        self.x == *x && self.y == *y
    }
}

impl<Left, Right> PartialEq<[Right; 2]> for Vec2<Left>
where
    Left: PartialEq<Right>,
{
    fn eq(&self, [x, y]: &[Right; 2]) -> bool {
        self.x == *x && self.y == *y
    }
}

impl<T> Display for Vec2<T>
where
    T: Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}, {}]", self.x, self.y)
    }
}

impl<T> IntoIterator for Vec2<T> {
    type Item = T;
    type IntoIter = std::array::IntoIter<T, 2>;

    fn into_iter(self) -> Self::IntoIter {
        let r: [_; 2] = self.into();
        r.into_iter()
    }
}

impl<'a, T> IntoIterator for &'a Vec2<T> {
    type Item = &'a T;
    type IntoIter = std::array::IntoIter<&'a T, 2>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut Vec2<T> {
    type Item = &'a mut T;
    type IntoIter = std::array::IntoIter<&'a mut T, 2>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<T> Neg for Vec2<T>
where
    T: Neg,
{
    type Output = Vec2<T::Output>;

    fn neg(self) -> Self::Output {
        (-self.x, -self.y).into()
    }
}

impl<T: PartialOrd> PartialOrd for Vec2<T> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        match (self.x.partial_cmp(&other.x)?, self.y.partial_cmp(&other.y)?) {
            (Ordering::Equal, Ordering::Equal) => Some(Ordering::Equal),
            (
                Ordering::Less | Ordering::Equal,
                Ordering::Less | Ordering::Equal,
            ) => Some(Ordering::Less),
            (
                Ordering::Greater | Ordering::Equal,
                Ordering::Greater | Ordering::Equal,
            ) => Some(Ordering::Greater),
            _ => None,
        }
    }
}

impl<T> AsRef<Vec2<T>> for Vec2<T> {
    fn as_ref(&self) -> &Vec2<T> {
        self
    }
}

macro_rules! op_single {
    ($op:ident, $fn:ident) => {
        impl<Left, Right> $op<Right> for Vec2<Left>
        where
            Left: $op<Right>,
            Right: Copy,
        {
            type Output = Vec2<Left::Output>;

            fn $fn(self, rhs: Right) -> Self::Output {
                (self.x.$fn(rhs), self.y.$fn(rhs)).into()
            }
        }
    };
}

macro_rules! op_assign_single {
    ($op:ident, $fn:ident) => {
        impl<Left, Right> $op<Right> for Vec2<Left>
        where
            Left: $op<Right>,
            Right: Copy,
        {
            fn $fn(&mut self, rhs: Right) {
                self.x.$fn(rhs);
                self.y.$fn(rhs);
            }
        }
    };
}

macro_rules! op_double {
    ($op:ident, $fn:ident) => {
        impl<Left, Right> $op<Vec2<Right>> for Vec2<Left>
        where
            Left: $op<Right>,
        {
            type Output = Vec2<Left::Output>;

            fn $fn(self, rhs: Vec2<Right>) -> Self::Output {
                (self.x.$fn(rhs.x), self.y.$fn(rhs.y)).into()
            }
        }

        impl<Left, Right> $op<(Right, Right)> for Vec2<Left>
        where
            Left: $op<Right>,
        {
            type Output = Vec2<Left::Output>;

            fn $fn(self, (x, y): (Right, Right)) -> Self::Output {
                (self.x.$fn(x), self.y.$fn(y)).into()
            }
        }

        impl<Left, Right> $op<[Right; 2]> for Vec2<Left>
        where
            Left: $op<Right>,
        {
            type Output = Vec2<Left::Output>;

            fn $fn(self, [x, y]: [Right; 2]) -> Self::Output {
                (self.x.$fn(x), self.y.$fn(y)).into()
            }
        }

        impl<Left, Right> $op<Range<Right>> for Vec2<Left>
        where
            Left: $op<Right>,
        {
            type Output = Vec2<Left::Output>;

            fn $fn(self, rhs: Range<Right>) -> Self::Output {
                (self.x.$fn(rhs.start), self.y.$fn(rhs.end)).into()
            }
        }
    };
}

macro_rules! op_assign_double {
    ($op:ident, $fn:ident) => {
        impl<Left, Right> $op<Vec2<Right>> for Vec2<Left>
        where
            Left: $op<Right>,
        {
            fn $fn(&mut self, rhs: Vec2<Right>) {
                self.x.$fn(rhs.x);
                self.y.$fn(rhs.y);
            }
        }

        impl<Left, Right> $op<(Right, Right)> for Vec2<Left>
        where
            Left: $op<Right>,
        {
            fn $fn(&mut self, (x, y): (Right, Right)) {
                self.x.$fn(x);
                self.y.$fn(y);
            }
        }

        impl<Left, Right> $op<[Right; 2]> for Vec2<Left>
        where
            Left: $op<Right>,
        {
            fn $fn(&mut self, [x, y]: [Right; 2]) {
                self.x.$fn(x);
                self.y.$fn(y);
            }
        }
    };
}

op_single!(Mul, mul);
op_assign_single!(MulAssign, mul_assign);

op_single!(Div, div);
op_assign_single!(DivAssign, div_assign);

op_single!(Rem, rem);
op_assign_single!(RemAssign, rem_assign);

op_double!(Add, add);
op_assign_double!(AddAssign, add_assign);

op_double!(Sub, sub);
op_assign_double!(SubAssign, sub_assign);