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
/*
 * Copyright (c) 2023 Martin Mills <daggerbot@gmail.com>
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#[cfg(feature = "cgmath")]
mod cgmath;

#[cfg(feature = "ext-ops")]
mod ext_ops;

#[cfg(feature = "num-traits")]
mod num_traits;

use core::fmt::{Display, Formatter};
use core::ops::{
    Add,
    AddAssign,
    Div,
    DivAssign,
    Mul,
    MulAssign,
    Neg,
    Sub,
    SubAssign,
};

/// 2-dimensional vector type.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Vec2<T> {
    pub x: T,
    pub y: T,
}

impl<T: Display> Display for Vec2<T> {
    fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
        f.write_str("(")?;
        Display::fmt(&self.x, f)?;
        f.write_str(", ")?;
        Display::fmt(&self.y, f)?;
        f.write_str(")")
    }
}

#[cfg(feature = "num-complex")]
impl<T> From<num_complex::Complex<T>> for Vec2<T> {
    fn from(c: num_complex::Complex<T>) -> Vec2<T> {
        Vec2 { x: c.re, y: c.im }
    }
}

#[cfg(feature = "num-complex")]
impl<T> Into<num_complex::Complex<T>> for Vec2<T> {
    fn into(self) -> num_complex::Complex<T> {
        num_complex::Complex { re: self.x, im: self.y }
    }
}

/// 3-dimensional vector type.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Vec3<T> {
    pub x: T,
    pub y: T,
    pub z: T,
}

impl<T: Display> Display for Vec3<T> {
    fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
        f.write_str("(")?;
        Display::fmt(&self.x, f)?;
        f.write_str(", ")?;
        Display::fmt(&self.y, f)?;
        f.write_str(", ")?;
        Display::fmt(&self.z, f)?;
        f.write_str(")")
    }
}

/// 4-dimensional vector type.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Vec4<T> {
    pub x: T,
    pub y: T,
    pub z: T,
    pub w: T,
}

impl<T: Display> Display for Vec4<T> {
    fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
        f.write_str("(")?;
        Display::fmt(&self.x, f)?;
        f.write_str(", ")?;
        Display::fmt(&self.y, f)?;
        f.write_str(", ")?;
        Display::fmt(&self.z, f)?;
        f.write_str(", ")?;
        Display::fmt(&self.w, f)?;
        f.write_str(")")
    }
}

/// Shorthand constructor for [Vec2].
pub fn vec2<T>(x: T, y: T) -> Vec2<T> {
    Vec2 { x, y }
}

/// Shorthand constructor for [Vec3].
pub fn vec3<T>(x: T, y: T, z: T) -> Vec3<T> {
    Vec3 { x, y, z }
}

/// Shorthand constructor for [Vec4].
pub fn vec4<T>(x: T, y: T, z: T, w: T) -> Vec4<T> {
    Vec4 { x, y, z, w }
}

//--------------------------------------------------------------------------------------------------

/// Implements unary operators for vector types.
macro_rules! impl_unary_ops {
    { $(impl $trait:ident::$fn:ident for $vec:ident($($field:ident),*);)* } => { $(
        impl<T> $trait for $vec<T>
        where T: $trait
        {
            type Output = $vec<<T as $trait>::Output>;

            fn $fn(self) -> Self::Output {
                $vec { $($field: $trait::$fn(self.$field)),* }
            }
        }

        impl<'a, T> $trait for &'a $vec<T>
        where &'a T: $trait
        {
            type Output = $vec<<&'a T as $trait>::Output>;

            fn $fn(self) -> Self::Output {
                $vec { $($field: $trait::$fn(&self.$field)),* }
            }
        }
    )* };
}

/// Implements vector-scalar binary operators.
macro_rules! impl_scalar_ops {
    { $(impl $trait:ident::$fn:ident for $vec:ident($($field:ident),*);)* } => { $(
        impl<T> $trait<T> for $vec<T>
        where T: Copy + $trait
        {
            type Output = $vec<<T as $trait>::Output>;

            fn $fn(self, rhs: T) -> Self::Output {
                $vec { $($field: $trait::$fn(self.$field, rhs)),* }
            }
        }

        impl<'a, T> $trait<T> for &'a $vec<T>
        where T: Copy,
              &'a T: $trait<T>
        {
            type Output = $vec<<&'a T as $trait<T>>::Output>;

            fn $fn(self, rhs: T) -> Self::Output {
                $vec { $($field: $trait::$fn(&self.$field, rhs)),* }
            }
        }

        impl<'r, T> $trait<&'r T> for $vec<T>
        where T: $trait<&'r T>
        {
            type Output = $vec<<T as $trait<&'r T>>::Output>;

            fn $fn(self, rhs: &'r T) -> Self::Output {
                $vec { $($field: $trait::$fn(self.$field, &rhs)),* }
            }
        }

        impl<'a, 'r, T> $trait<&'r T> for &'a $vec<T>
        where &'a T: $trait<&'r T>
        {
            type Output = $vec<<&'a T as $trait<&'r T>>::Output>;

            fn $fn(self, rhs: &'r T) -> Self::Output {
                $vec { $($field: $trait::$fn(&self.$field, &rhs)),* }
            }
        }
    )* };
}

/// Implements vector-scalar binary assignment operators.
macro_rules! impl_scalar_assign_ops {
    { $(impl $trait:ident::$fn:ident for $vec:ident($($field:ident),*);)* } => { $(
        impl<T> $trait<T> for $vec<T>
        where T: Copy + $trait
        {
            fn $fn(&mut self, rhs: T) {
                $($trait::$fn(&mut self.$field, rhs);)*
            }
        }

        impl<'r, T> $trait<&'r T> for $vec<T>
        where T: $trait<&'r T>
        {
            fn $fn(&mut self, rhs: &'r T) {
                $($trait::$fn(&mut self.$field, rhs);)*
            }
        }
    )* };
}

/// Implements vector-vector binary operators.
macro_rules! impl_binary_ops {
    { $(impl $trait:ident::$fn:ident for $vec:ident($($field:ident),*);)* } => { $(
        impl<T> $trait for $vec<T>
        where T: $trait
        {
            type Output = $vec<<T as $trait>::Output>;

            fn $fn(self, rhs: $vec<T>) -> Self::Output {
                $vec { $($field: $trait::$fn(self.$field, rhs.$field)),* }
            }
        }

        impl<'a, T> $trait<$vec<T>> for &'a $vec<T>
        where &'a T: $trait<T>
        {
            type Output = $vec<<&'a T as $trait<T>>::Output>;

            fn $fn(self, rhs: $vec<T>) -> Self::Output {
                $vec { $($field: $trait::$fn(&self.$field, rhs.$field)),* }
            }
        }

        impl<'r, T> $trait<&'r $vec<T>> for $vec<T>
        where T: $trait<&'r T>
        {
            type Output = $vec<<T as $trait<&'r T>>::Output>;

            fn $fn(self, rhs: &'r $vec<T>) -> Self::Output {
                $vec { $($field: $trait::$fn(self.$field, &rhs.$field)),* }
            }
        }

        impl<'a, 'r, T> $trait<&'r $vec<T>> for &'a $vec<T>
        where &'a T: $trait<&'r T>
        {
            type Output = $vec<<&'a T as $trait<&'r T>>::Output>;

            fn $fn(self, rhs: &'r $vec<T>) -> Self::Output {
                $vec { $($field: $trait::$fn(&self.$field, &rhs.$field)),* }
            }
        }
    )* };
}

/// Implements vector-vector binary assignment operators.
macro_rules! impl_binary_assign_ops {
    { $(impl $trait:ident::$fn:ident for $vec:ident($($field:ident),*);)* } => { $(
        impl<T> $trait for $vec<T>
        where T: $trait
        {
            fn $fn(&mut self, rhs: $vec<T>) {
                $($trait::$fn(&mut self.$field, rhs.$field);)*
            }
        }

        impl<'r, T> $trait<&'r $vec<T>> for $vec<T>
        where T: $trait<&'r T>
        {
            fn $fn(&mut self, rhs: &'r $vec<T>) {
                $($trait::$fn(&mut self.$field, &rhs.$field);)*
            }
        }
    )* };
}

/// Implements common functions and traits for vector types.
macro_rules! impl_all {
    { $(impl $vec:ident($($field:ident: $t:ident),*; $n:expr);)* } => { $(
        impl<T> $vec<T> {
            /// Converts the vector's fields into another type.
            pub fn convert<U>(self) -> $vec<U>
            where T: Into<U>
            {
                $vec { $($field: self.$field.into()),* }
            }

            /// Constructs a new vector.
            pub const fn new($($field: $t),*) -> $vec<T> {
                $vec { $($field),* }
            }

            /// Converts the vector's fields into another type.
            pub fn ref_convert<'a, U>(&'a self) -> $vec<U>
            where &'a T: Into<U>
            {
                $vec { $($field: (&self.$field).into()),* }
            }

            /// Attempts to convert the vector's fields into another type. On failure, this returns
            /// the first error that occurred.
            pub fn try_convert<U>(self) -> Result<$vec<U>, <T as TryInto<U>>::Error>
            where T: TryInto<U>
            {
                Ok($vec { $($field: self.$field.try_into()?),* })
            }

            /// Attempts to convert the vector's fields into another type. On failure, this returns
            /// the first error that occurred.
            pub fn try_ref_convert<'a, U>(&'a self) -> Result<$vec<U>, <&'a T as TryInto<U>>::Error>
            where &'a T: TryInto<U>
            {
                Ok($vec { $($field: (&self.$field).try_into()?),* })
            }
        }

        impl<T> From<($($t),*)> for $vec<T> {
            fn from(t: ($($t),*)) -> $vec<T> {
                let ($($field),*) = t;
                $vec { $($field),* }
            }
        }

        impl<T> From<[T; $n]> for $vec<T> {
            fn from(a: [T; $n]) -> $vec<T> {
                let mut iter = a.into_iter();
                $(let $field = iter.next().unwrap();)*
                $vec { $($field),* }
            }
        }

        impl<T> Into<($($t),*)> for $vec<T> {
            fn into(self) -> ($($t),*) {
                ($(self.$field),*)
            }
        }

        impl<T> Into<[T; $n]> for $vec<T> {
            fn into(self) -> [T; $n] {
                [$(self.$field),*]
            }
        }

        impl_unary_ops! {
            impl Neg::neg for $vec($($field),*);
        }

        impl_scalar_ops! {
            impl Div::div for $vec($($field),*);
            impl Mul::mul for $vec($($field),*);
        }

        impl_scalar_assign_ops! {
            impl DivAssign::div_assign for $vec($($field),*);
            impl MulAssign::mul_assign for $vec($($field),*);
        }

        impl_binary_ops! {
            impl Add::add for $vec($($field),*);
            impl Div::div for $vec($($field),*);
            impl Mul::mul for $vec($($field),*);
            impl Sub::sub for $vec($($field),*);
        }

        impl_binary_assign_ops! {
            impl AddAssign::add_assign for $vec($($field),*);
            impl DivAssign::div_assign for $vec($($field),*);
            impl MulAssign::mul_assign for $vec($($field),*);
            impl SubAssign::sub_assign for $vec($($field),*);
        }
    )* };
}

impl_all! {
    impl Vec2(x: T, y: T; 2);
    impl Vec3(x: T, y: T, z: T; 3);
    impl Vec4(x: T, y: T, z: T, w: T; 4);
}