wedged 0.1.1

A robust and generalized library for Geometric Algebra in Rust.
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
//!
//! Traits and structs for the storage of vector-like data.
//!
//! This module provides a system to unify the different statically-sized
//! arrays and dynamic arrays in order to make managing the backing data of the algebras
//! easier.
//!

use std::borrow::{Borrow, BorrowMut};
use std::ops::{Index, IndexMut};
use std::convert::{AsRef, AsMut};
use std::iter::{IntoIterator, FromIterator, FusedIterator};
use std::mem::{MaybeUninit, transmute, transmute_copy};

#[cfg(doc)] use crate::base::dim::*;
#[cfg(doc)] use crate::base::alloc::*;
#[cfg(doc)] use crate::algebra::*;

use crate::base::*;

use na::dimension::{Dim};

/// Contains all the array-like functionality we need for backing buffers for the algebraic types
pub trait Storage<T>:
    Index<usize, Output=T> + IndexMut<usize> +
    AsRef<[T]> + AsMut<[T]> +
    Borrow<[T]> + BorrowMut<[T]> +
    IntoIterator<Item=T, IntoIter=Self::Iter>
{

    ///The corresponding uninitialized storage that can transmute into this type
    type Uninit: UninitStorage<T,Init=Self>;

    ///
    /// The iterator over this type. Wraps [`IntoIterator::IntoIter`]
    ///
    /// We need this so we can add extra trait bounds to the `IntoIterator::IntoIter`
    /// implementation for `Self`.
    type Iter: Iterator<Item=T> + DoubleEndedIterator + ExactSizeIterator + FusedIterator; //Add TrustedLen when stabilized

    ///
    /// The number of items in self.
    ///
    /// Note this takes in `&self` and can vary over time. This way we can support [`Dynamic`] dimensions
    fn elements(&self) -> usize;

    ///
    /// Wraps [`Clone::clone()`] whenever `T:Clone`
    ///
    /// This allows us to have `Clone` `impl`s that only require `T:Clone` without bounds on
    /// the underlying storage object.
    fn clone_storage(&self) -> Self where T:Clone;

    ///
    /// Wraps [`Clone::clone_from()`] whenever `T:Clone`
    ///
    /// This allows us to have `Clone` `impl`s that only require `T:Clone` without bounds on
    /// the underlying storage object.
    fn clone_from_storage(&mut self, other: &Self) where T:Clone;


}

///
/// A [`Storage`] type that contains [`MaybeUninit<T>`] elements.
///
/// This allows us to follow the  [`std::mem::MaybeUninit`] design paradigm when constructing
/// the algebraic structs while still having access to the individual elements of the buffer
pub trait UninitStorage<T>: Storage<MaybeUninit<T>> {
    /// The initialized storage that we can trasmute into
    type Init: Storage<T,Uninit=Self>;

    ///
    /// Transmutes this buffer into one assumed to be initialized
    ///
    /// # Safety
    /// Should follow all considerations of [`MaybeUninit::assume_init()`]
    unsafe fn assume_init(self) -> Self::Init;
}

/// A [`Storage`] type that can contain a [`Blade`] of the given dimension and grade
///
/// # Safety
/// The backing buffer should have the *exact* amount of components to fill the given `Blade`.
pub unsafe trait BladeStorage<T,N:Dim,G:Dim>: Storage<T> {

    ///The dimension of `Blade` being stored. Can vary when using a [`Dynamic`] dimension
    fn dim(&self) -> N;

    ///The dimension of `Blade` being stored. Can vary when using a [`Dynamic`] grade
    fn grade(&self) -> G;

    ///Allocates a buffer to contain a `Blade` of the given dimension and grade
    fn uninit(n:N, g:G) -> Self::Uninit;

    ///Allocates and initializes a buffer to contain a `Blade` of the given dimension and grade
    fn from_iterator<I:IntoIterator<Item=T>>(n:N, g:G, iter: I) -> Self;

}

/// A [`Storage`] type that can contain an [`Even`] of the given dimension
///
/// # Safety
/// The backing buffer should have the *exact* amount of components to fill the given `Even`.
pub unsafe trait EvenStorage<T,N:Dim>: Storage<T> {

    ///The dimension of `Even` being stored. Can vary when using a [`Dynamic`] dimension
    fn dim(&self) -> N;

    ///Allocates a buffer to contain a `Even` of the given dimension
    fn uninit(n:N) -> Self::Uninit;

    ///Allocates and initializes a buffer to contain a `Even` of the given dimension
    fn from_iterator<I:IntoIterator<Item=T>>(n:N, iter: I) -> Self;
}

/// A [`Storage`] type that can contain an [`Odd`] of the given dimension
///
/// # Safety
/// The backing buffer should have the *exact* amount of components to fill the given `Odd`.
pub unsafe trait OddStorage<T,N:Dim>: Storage<T> {

    ///The dimension of `Odd` being stored. Can vary when using a [`Dynamic`] dimension
    fn dim(&self) -> N;

    ///Allocates a buffer to contain a `Odd` of the given dimension
    fn uninit(n:N) -> Self::Uninit;

    ///Allocates and initializes a buffer to contain a `Odd` of the given dimension
    fn from_iterator<I:IntoIterator<Item=T>>(n:N, iter: I) -> Self;
}

/// A [`Storage`] type that can contain a [`Multivector`] of the given dimension
///
/// # Safety
/// The backing buffer should have the *exact* amount of components to fill the given `Multivector`.
pub unsafe trait MultivectorStorage<T,N:Dim>: Storage<T> {

    ///The dimension of `Multivector` being stored. Can vary when using a [`Dynamic`] dimension
    fn dim(&self) -> N;

    ///Allocates a buffer to contain a `Multivector` of the given dimension
    fn uninit(n:N) -> Self::Uninit;

    ///Allocates and initializes a buffer to contain a `Multivector` of the given dimension
    fn from_iterator<I:IntoIterator<Item=T>>(n:N, iter: I) -> Self;
}

//
//Statically sized arrays
//

impl<T, const L: usize> Storage<T> for [T;L] {
    type Uninit = [MaybeUninit<T>; L];
    type Iter = <Self as IntoIterator>::IntoIter;
    fn elements(&self) -> usize { L }
    fn clone_storage(&self) -> Self where T:Clone { self.clone() }
    fn clone_from_storage(&mut self, other: &Self) where T:Clone { self.clone_from(other) }
}

impl<T, const L: usize> UninitStorage<T> for [MaybeUninit<T>;L] {
    type Init = [T; L];
    unsafe fn assume_init(self) -> Self::Init {
        //TODO: use `MaybeUninit::assume_init_array(self)` when stabilized
        //This _probably_ optimizes to zero-cost, but who knows!
        transmute_copy::<Self, Self::Init>(&self)
    }
}

//
// Dynamic storage
//

#[inline(always)]
fn vec_uninit<T>(count:usize) -> Vec<MaybeUninit<T>> {
    //Ideally, there'd be a built-in function for this, but it *does* work within the guarrantees
    //made by a Vec, so we're gonna do it anyway!
    let mut vec = Vec::with_capacity(count);
    unsafe { vec.set_len(count) };
    vec
}

#[inline(always)]
fn vec_from_iter<T,I:IntoIterator<Item=T>>(count:usize, iter: I, kind:&str) -> Vec<T> {
    let vec: Vec<T> = FromIterator::from_iter(iter.into_iter().take(count));
    if vec.len() != count {
        panic!("Not enough elements to fill {}", kind);
    }
    vec
}

/// Storage buffer for a [`Blade`] that can use a
/// [`Dynamic`] dim to vary its size at runtime
#[derive(Clone)]
pub struct DynBladeStorage<T,N:Dim,G:Dim> {
    data: Vec<T>,
    dim: N,
    grade: G
}

/// Storage buffer for an [`Even`] that can use a
/// [`Dynamic`] dim to vary its size at runtime
#[derive(Clone)]
pub struct DynEvenStorage<T,N:Dim> {
    data: Vec<T>,
    dim: N
}

/// Storage buffer for an [`Odd`] that can use a
/// [`Dynamic`] dim to vary its size at runtime
#[derive(Clone)]
pub struct DynOddStorage<T,N:Dim> {
    data: Vec<T>,
    dim: N
}

/// Storage buffer for a [`Multivector`] that can use a
/// [`Dynamic`] dim to vary its size at runtime
#[derive(Clone)]
pub struct DynMultivectorStorage<T,N:Dim> {
    data: Vec<T>,
    dim: N
}

macro_rules! impl_dyn_storage {
    ($($Ty:ident<T, $($N:ident),*>;)*) => {
        $(
            impl<T,$($N:Dim),*> Index<usize> for $Ty<T,$($N),*> {
                type Output = T;
                fn index(&self, i: usize) -> &T { &self.data[i] }
            }

            impl<T,$($N:Dim),*> IndexMut<usize> for $Ty<T,$($N),*> {
                fn index_mut(&mut self, i: usize) -> &mut T { &mut self.data[i] }
            }

            impl<T,$($N:Dim),*> AsRef<[T]> for $Ty<T,$($N),*> {
                fn as_ref(&self) -> &[T] { self.data.as_ref() }
            }

            impl<T,$($N:Dim),*> AsMut<[T]> for $Ty<T,$($N),*> {
                fn as_mut(&mut self) -> &mut [T] { self.data.as_mut() }
            }

            impl<T,$($N:Dim),*> Borrow<[T]> for $Ty<T,$($N),*> {
                fn borrow(&self) -> &[T] { self.data.borrow() }
            }

            impl<T,$($N:Dim),*> BorrowMut<[T]> for $Ty<T,$($N),*> {
                fn borrow_mut(&mut self) -> &mut [T] { self.data.borrow_mut() }
            }

            impl<T,$($N:Dim),*> IntoIterator for $Ty<T,$($N),*> {
                type Item = T;
                type IntoIter = std::vec::IntoIter<T>;
                fn into_iter(self) -> Self::IntoIter {
                    self.data.into_iter()
                }
            }

            impl<T,$($N:Dim),*> Storage<T> for $Ty<T,$($N),*> {
                type Uninit = $Ty<MaybeUninit<T>,$($N),*>;
                type Iter = <Self as IntoIterator>::IntoIter;
                fn elements(&self) -> usize { self.data.len() }
                fn clone_storage(&self) -> Self where T:Clone { self.clone() }
                fn clone_from_storage(&mut self, other: &Self) where T:Clone { self.clone_from(other) }
            }

        )*
    }
}

impl_dyn_storage!(
    DynBladeStorage<T,N,G>; DynEvenStorage<T,N>; DynOddStorage<T,N>; DynMultivectorStorage<T,N>;
);

impl<T,N:Dim,G:Dim> UninitStorage<T> for DynBladeStorage<MaybeUninit<T>,N,G> {
    type Init = DynBladeStorage<T,N,G>;

    unsafe fn assume_init(self) -> Self::Init {
        //TODO: maybe make less ugly
        DynBladeStorage {
            data: transmute::<Vec<MaybeUninit<T>>, Vec<T>>(self.data),
            dim: self.dim, grade: self.grade
        }
    }

}

unsafe impl<T,N:Dim,G:Dim> BladeStorage<T,N,G> for DynBladeStorage<T,N,G> {

    fn dim(&self) -> N { self.dim }
    fn grade(&self) -> G { self.grade }

    fn uninit(n:N, g:G) -> Self::Uninit {
        DynBladeStorage {
            data: vec_uninit(binom(n.value(), g.value())),
            dim: n,
            grade: g
        }
    }

    fn from_iterator<I:IntoIterator<Item=T>>(n:N, g:G, iter: I) -> Self {
        DynBladeStorage {
            data: vec_from_iter(binom(n.value(), g.value()), iter, "blade"),
            dim: n,
            grade: g
        }
    }

}

impl<T,N:Dim> UninitStorage<T> for DynEvenStorage<MaybeUninit<T>,N> {
    type Init = DynEvenStorage<T,N>;

    unsafe fn assume_init(self) -> Self::Init {
        //TODO: maybe make less ugly
        DynEvenStorage {
            data: transmute::<Vec<MaybeUninit<T>>, Vec<T>>(self.data),
            dim: self.dim
        }
    }

}

unsafe impl<T,N:Dim> EvenStorage<T,N> for DynEvenStorage<T,N> {

    fn dim(&self) -> N { self.dim }

    fn uninit(n:N) -> Self::Uninit {
        DynEvenStorage {
            data: vec_uninit(even_elements(n.value())),
            dim: n
        }
    }

    fn from_iterator<I:IntoIterator<Item=T>>(n:N, iter: I) -> Self {
        DynEvenStorage {
            data: vec_from_iter(even_elements(n.value()), iter, "value"),
            dim: n
        }
    }

}

impl<T,N:Dim> UninitStorage<T> for DynOddStorage<MaybeUninit<T>,N> {
    type Init = DynOddStorage<T,N>;

    unsafe fn assume_init(self) -> Self::Init {
        //TODO: maybe make less ugly
        DynOddStorage {
            data: transmute::<Vec<MaybeUninit<T>>, Vec<T>>(self.data),
            dim: self.dim
        }
    }

}

unsafe impl<T,N:Dim> OddStorage<T,N> for DynOddStorage<T,N> {

    fn dim(&self) -> N { self.dim }

    fn uninit(n:N) -> Self::Uninit {
        DynOddStorage {
            data: vec_uninit(odd_elements(n.value())),
            dim: n
        }
    }

    fn from_iterator<I:IntoIterator<Item=T>>(n:N, iter: I) -> Self {
        DynOddStorage {
            data: vec_from_iter(odd_elements(n.value()), iter, "value"),
            dim: n
        }
    }

}


impl<T,N:Dim> UninitStorage<T> for DynMultivectorStorage<MaybeUninit<T>,N> {
    type Init = DynMultivectorStorage<T,N>;

    unsafe fn assume_init(self) -> Self::Init {
        //TODO: maybe make less ugly
        DynMultivectorStorage {
            data: transmute::<Vec<MaybeUninit<T>>, Vec<T>>(self.data),
            dim: self.dim
        }
    }

}

unsafe impl<T,N:Dim> MultivectorStorage<T,N> for DynMultivectorStorage<T,N> {

    fn dim(&self) -> N { self.dim }

    fn uninit(n:N) -> Self::Uninit {
        DynMultivectorStorage {
            data: vec_uninit(multivector_elements(n.value())),
            dim: n
        }
    }

    fn from_iterator<I:IntoIterator<Item=T>>(n:N, iter: I) -> Self {
        DynMultivectorStorage {
            data: vec_from_iter(multivector_elements(n.value()), iter, "multivector"),
            dim: n
        }
    }

}