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
use crate::binds::MonoObject;
use crate::gc::{gc_unsafe_enter, gc_unsafe_exit, GCHandle};
use crate::interop::{InteropClass, InteropRecive, InteropSend};
use crate::{dimensions::DimensionTrait, domain::Domain, Class, Object, ObjectTrait};
use core::marker::PhantomData;
use core::ptr::null_mut;
use std::borrow::{Borrow, BorrowMut};
use std::ops::Index;
// Documentation finished.
/// Safe, rust representation of `MonoArray` (a reference to a managed array).
/// # Nullable support
/// [`Array<T>`] is non-nullable on default and will panic when null passed as argument form managed code. For nullable support use [`Option<Array<T>>`].
/*
    why is there a weird constraint "where [();DIMENSIONS as usize]:Copy" in array type? It guarantees that Dimensions is higher than 0 and size array is larger than 0,
    so Array<DIMENSIONS,T> can exist.
*/
pub struct Array<Dim: DimensionTrait, T: InteropSend + InteropRecive + InteropClass>
where
    Dim::Lengths: std::ops::IndexMut<usize> + BorrowMut<[usize]> + Copy,
    <Dim::Lengths as std::ops::Index<usize>>::Output: BorrowMut<usize>,
    <<Dim as DimensionTrait>::Lengths as Index<usize>>::Output: Sized + Into<usize> + Copy,
{
    #[cfg(not(feature = "referneced_objects"))]
    arr_ptr: *mut crate::binds::MonoArray,
    #[cfg(feature = "referneced_objects")]
    handle: GCHandle,
    pd: PhantomData<T>,
    lengths: Dim::Lengths,
}
impl<T: InteropSend + InteropRecive + InteropClass, Dim: DimensionTrait> Array<Dim, T>
where
    Dim::Lengths: std::ops::IndexMut<usize> + BorrowMut<[usize]> + Copy + Copy,
    <Dim::Lengths as std::ops::Index<usize>>::Output: BorrowMut<usize>,
    <<Dim as DimensionTrait>::Lengths as Index<usize>>::Output: Sized + Into<usize> + Copy,
    <Dim as DimensionTrait>::Lengths: BorrowMut<[usize]>,
{
    // Private function used to calculate index in an array based on its dimensions.
    fn get_index(&self, indices: Dim::Lengths) -> usize {
        //size of current dimension
        let mut size = 1;
        let mut index = 0;
        for (n, ind) in indices.borrow().iter().enumerate() {
            let len = self.lengths[n];
            #[cfg(not(feature = "unsafe_arrays"))]
            assert!(
                *ind < len.into(),
                "index ({}) outside of array bound ({})",
                ind,
                len.into()
            );
            index += ind * size;
            size *= len.into();
        }
        index
    }
    /// Function returning element at *index*
    /// # Arguments
    /// |Name   |Type   |Description|
    /// |-------|-------|------|
    /// |self|&Self|[`Array`] to read from.|
    /// |indices|`[usize;DIMENSIONS as usize]`| An n-dimensional array containing indices to read value at|
    /// # Examples
    /// ```no_run
    /// # use wrapped_mono::*;
    /// fn some_get_fn(input:&Array<Dim1D,f32>)->f32{
    ///     let a = input.get([0]);  
    ///     let b = input.get([1]);
    ///     a + b
    /// }
    /// ```
    /// ```no_run
    /// # use wrapped_mono::*;
    /// fn some_get_fn_2D(input:&Array<Dim2D,f32>)->f32{
    ///     let a = input.get([0,0]);  
    ///     let b = input.get([1,1]);
    ///     let c = input.get([0,1]);
    ///      a + b + c
    /// }
    /// ```
    pub fn get(&self, indices: Dim::Lengths) -> T {
        let index = self.get_index(indices);
        #[cfg(feature = "referneced_objects")]
        let marker = gc_unsafe_enter();
        #[allow(clippy::cast_possible_truncation)]
        #[allow(clippy::cast_possible_wrap)]
        let src: T::SourceType = unsafe {
            *(crate::binds::mono_array_addr_with_size(
                self.get_ptr().cast(),
                std::mem::size_of::<T::SourceType>() as i32,
                index,
            ) as *const T::SourceType)
        };
        let rr = T::get_rust_rep(src);
        #[cfg(feature = "referneced_objects")]
        gc_unsafe_exit(marker);
        rr
    }
    /// Function setting element at *index* of [`Array`] to *value*
    /// # Arguments
    /// |Name   |Type   |Description|
    /// |-------|-------|------|
    /// |self|&Self|[`Array`] to write value to.|
    /// |indices|`[usize;DIMENSIONS as usize]`| An n-dimensional array containing indices to set value at|
    /// |value  |`T`|value to set element at index to.|
    /// # Example
    /// ```no_run
    /// # use wrapped_mono::*;
    /// fn set_fn(input:&mut Array<Dim1D,i32>){
    ///     input.set([0],0);
    ///     input.set([1],1);
    /// }
    /// ```
    /// ```no_run
    /// # use wrapped_mono::*;
    /// fn set_fn_2D(input:&mut Array<Dim2D,i32>){
    ///     input.set([0,0],0);
    ///     input.set([1,1],1);
    ///     input.set([1,0],9);
    /// }
    /// ```
    pub fn set(&mut self, indices: Dim::Lengths, value: T) {
        let tmp = T::get_mono_rep(value);
        let index = self.get_index(indices);
        #[cfg(feature = "referneced_objects")]
        let marker = gc_unsafe_enter();
        let ptr = unsafe {
            #[allow(clippy::cast_possible_truncation)]
            #[allow(clippy::cast_possible_wrap)]
            crate::binds::mono_array_addr_with_size(
                self.get_ptr().cast(),
                std::mem::size_of::<T::TargetType>() as i32,
                index,
            )
            .cast()
        };
        unsafe { (*ptr) = tmp };
        #[cfg(feature = "referneced_objects")]
        gc_unsafe_exit(marker);
    }
    /// Function returning 1D length of the array(element count).
    /// # Arguments
    /// |Name   |Type   |Description|
    /// |-------|-------|------|
    /// |self|&Self|[`Array`] to get length of|
    /// # Example
    /// ```no_run
    /// # use wrapped_mono::*;
    /// fn get_avg(input:&Array<Dim1D,f32>)->f32{
    ///     let mut sum = 0.0;
    ///     for i in 0..input.len(){
    ///         sum += input.get([i]);
    ///     }
    ///     sum/(input.len() as f32)
    /// }
    /// ```
    #[must_use]
    pub fn len(&self) -> usize {
        #[cfg(feature = "referneced_objects")]
        let marker = gc_unsafe_enter();
        let len = unsafe { crate::binds::mono_array_length(self.get_ptr().cast()) };
        #[cfg(feature = "referneced_objects")]
        gc_unsafe_exit(marker);
        len
    }
    /// Checks if [`Array`] is empty.
    /// # Arguments
    /// |Name   |Type   |Description|
    /// |-------|-------|------|
    /// |self|&Self|[`Array`] to check if is empty|
    #[must_use]
    pub fn is_empty(&self) -> bool {
        0 == self.len()
    }

    /// Converts [`Array`] to [`Object`]
    /// # Arguments
    /// |Name   |Type   |Description|
    /// |-------|-------|------|
    /// |self| &Array | array to cast to object|
    #[must_use]
    pub fn to_object(&self) -> Object {
        #[cfg(feature = "referneced_objects")]
        let marker = gc_unsafe_enter();
        let res = unsafe { Object::from_ptr(self.get_ptr().cast()) }
            .expect("Could not create object from array!");
        #[cfg(feature = "referneced_objects")]
        gc_unsafe_exit(marker);
        res
    }
    /// Allocate new array in *domain* with size *DIMENSIONS* with elements of type *class*.
    /// # Example
    /// ```no_run
    /// # use wrapped_mono::*;
    /// # let domain = Domain::get_current().unwrap();
    /// # let int_managed_class = Class::get_int_32();
    /// let arr_len = 8;
    /// let arr = Array::<Dim1D,i32>::new(&domain,&[arr_len]);
    /// assert!(arr.len() == arr_len);
    /// ```
    ///
    /// # Arguments
    /// |Name   |Type   |Description|
    /// |-------|-------|------|
    /// |domain| &[`Domain`] | domain to create array in|
    /// |size|`&[usize;DIMENSIONS as usize]`| size of the array to create|
    #[must_use]
    pub fn new(domain: &Domain, size: &Dim::Lengths) -> Self {
        #[allow(clippy::cast_possible_truncation)]
        let class = <T as InteropClass>::get_mono_class().get_array_class(Dim::DIMENSIONS as u32);
        #[cfg(feature = "referneced_objects")]
        let marker = gc_unsafe_enter();
        let arr = unsafe {
            Self::from_ptr(
                crate::binds::mono_array_new_full(
                    domain.get_ptr(),
                    class.get_ptr(),
                    size as *const _ as *mut usize,
                    null_mut(),
                )
                .cast(),
            )
        }
        .expect("could not create a new array!");
        #[cfg(feature = "referneced_objects")]
        gc_unsafe_exit(marker);
        arr
    }
    /// Clones managed array, **not** the reference to it.
    /// # Arguments
    /// |Name   |Type   |Description|
    /// |-------|-------|------|
    /// |self|&Array|Array to clone|
    #[must_use]
    pub fn clone_managed_array(&self) -> Self {
        #[cfg(feature = "referneced_objects")]
        let marker = gc_unsafe_enter();
        let res =
            unsafe { Self::from_ptr(crate::binds::mono_array_clone(self.get_ptr().cast()).cast()) }
                .expect("coud not create copy of an array!");
        #[cfg(feature = "referneced_objects")]
        gc_unsafe_exit(marker);
        res
    }
    ///Returns class of this array
    #[must_use]
    pub fn get_class() -> Class {
        #[allow(clippy::cast_possible_truncation)]
        Class::get_array_class(
            &<T as InteropClass>::get_mono_class(),
            Dim::DIMENSIONS as u32,
        )
    }
    /// Returns n-dimensional length of this array.
    /// # Arguments
    /// |Name   |Type   |Description|
    /// |-------|-------|------|
    /// |self|&Array|Array to get size of|
    pub fn get_lenghts(&self) -> Dim::Lengths {
        self.lengths
    }
}
impl<Dim: DimensionTrait, T: InteropSend + InteropRecive + InteropClass> InteropClass
    for Array<Dim, T>
where
    Dim::Lengths: std::ops::IndexMut<usize> + BorrowMut<[usize]> + Copy,
    <Dim::Lengths as std::ops::Index<usize>>::Output: BorrowMut<usize>,
    <<Dim as DimensionTrait>::Lengths as Index<usize>>::Output: Sized + Into<usize> + Copy,
{
    fn get_mono_class() -> Class {
        Self::get_class()
    }
}
impl<Dim: DimensionTrait, T: InteropSend + InteropRecive + InteropClass> ObjectTrait
    for Array<Dim, T>
where
    Dim::Lengths: std::ops::IndexMut<usize> + BorrowMut<[usize]> + Copy,
    <Dim::Lengths as std::ops::Index<usize>>::Output: BorrowMut<usize>,
    <<Dim as DimensionTrait>::Lengths as Index<usize>>::Output: Sized + Into<usize> + Copy,
{
    #[must_use]
    fn get_ptr(&self) -> *mut crate::binds::MonoObject {
        #[cfg(not(feature = "referneced_objects"))]
        return self.arr_ptr.cast();
        #[cfg(feature = "referneced_objects")]
        return self.handle.get_target();
    }
    #[must_use]
    unsafe fn from_ptr_unchecked(ptr: *mut MonoObject) -> Self {
        use crate::Method;
        #[cfg(not(feature = "referneced_objects"))]
        let mut res = Self {
            arr_ptr: ptr.cast(),
            pd: PhantomData,
            lengths: Dim::zeroed(),
        };
        #[cfg(feature = "referneced_objects")]
        let mut res = Self {
            handle: GCHandle::create_default(ptr.cast()),
            pd: PhantomData,
            lengths: Dim::zeroed(),
        };
        #[cfg(not(feature = "unsafe_arrays"))]
        {
            #[allow(clippy::cast_sign_loss)]
            let rank = res.get_class().get_rank() as usize;
            assert_eq!(rank, Dim::DIMENSIONS, "Array dimension mismatch!",);
            let source_class = res.to_object().get_class();
            let target_class = <Self as InteropClass>::get_mono_class();
            assert!(
                !(source_class.get_element_class() != target_class.get_element_class()),
                "tried to create array of type `{}` from object of type `{}`",
                &target_class.get_name(),
                &source_class.get_name()
            );
        }
        //get array size
        {
            let dim: Method<(i32,)> = Method::get_from_name(&Class::get_array(), "GetLength", 1)
                .expect("Array type does not have GetLength method, even toug it is impossible.");
            #[allow(
                clippy::cast_possible_wrap,
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss
            )]
            for i in 0..Dim::DIMENSIONS {
                let dim_obj = dim
                    .invoke(Some(res.to_object()), (i as i32,))
                    .expect("Got an exception while calling Array.GetLength")
                    .expect("Got null instead of int");
                let len_ref: &mut Dim::Lengths = &mut res.lengths;
                let len_ref: &mut [usize] = (len_ref).borrow_mut();
                len_ref[i] = dim_obj.unbox::<i32>() as usize;
            }
        }
        res
    }
}
impl<Dim: DimensionTrait, T: InteropSend + InteropRecive + InteropClass> Clone for Array<Dim, T>
where
    Dim::Lengths: std::ops::IndexMut<usize> + BorrowMut<[usize]> + Copy,
    <Dim::Lengths as std::ops::Index<usize>>::Output: BorrowMut<usize>,
    <<Dim as DimensionTrait>::Lengths as Index<usize>>::Output: Sized + Into<usize> + Copy,
{
    fn clone(&self) -> Self {
        unsafe { Self::from_ptr(self.get_ptr().cast()).unwrap() } //If object exists then it can't be null
    }
}
impl<Dim: DimensionTrait, T: InteropSend + InteropRecive + InteropClass, O: ObjectTrait>
    PartialEq<O> for Array<Dim, T>
where
    Dim::Lengths: std::ops::IndexMut<usize> + BorrowMut<[usize]> + Copy,
    <Dim::Lengths as std::ops::Index<usize>>::Output: BorrowMut<usize>,
    <<Dim as DimensionTrait>::Lengths as Index<usize>>::Output: Sized + Into<usize> + Copy,
{
    fn eq(&self, other: &O) -> bool {
        self.get_ptr() == other.get_ptr().cast()
    }
}
use crate::dimensions::Dim1D;
impl<T: InteropSend + InteropRecive + InteropClass + Clone> From<&[T]> for Array<Dim1D, T> {
    fn from(src: &[T]) -> Self {
        let size = src.len();
        let dom = Domain::get_current().expect("Can't create arrays before JIT starts!");
        let mut res = Self::new(&dom, &[size]);
        for (i, src) in src.iter().enumerate() {
            res.set([i], src.clone());
        }
        res
    }
}