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
use std::cmp::min;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::sync::Arc;

use once_cell::sync::Lazy;
use suitesparse_graphblas_sys::{GrB_Type, GxB_Vector_build_Scalar, GxB_Vector_diag};

use crate::collections::collection::Collection;
use crate::collections::sparse_matrix::operations::GetSparseMatrixSize;
use crate::collections::sparse_matrix::{GetGraphblasSparseMatrix, SparseMatrix};
use crate::collections::sparse_scalar::{GraphblasSparseScalarTrait, SparseScalar};
use crate::collections::sparse_vector::operations::GetSparseVectorLength;
use crate::collections::sparse_vector::operations::GetVectorElementList;
use crate::collections::sparse_vector::VectorElementList;
use crate::context::CallGraphBlasContext;
use crate::context::{Context, GetContext};
use crate::error::SparseLinearAlgebraError;
use crate::graphblas_bindings::{
    GrB_Index, GrB_Vector, GrB_Vector_clear, GrB_Vector_dup, GrB_Vector_free, GrB_Vector_new,
    GrB_Vector_nvals,
};
use crate::index::{DiagonalIndex, DiagonalIndexConversion, ElementIndex, IndexConversion};
use crate::operators::mask::VectorMask;
use crate::operators::options::{OperatorOptions, OperatorOptionsTrait};
use crate::value_type::utilities_to_implement_traits_for_all_value_types::implement_macro_for_all_value_types;
use crate::value_type::ValueType;

static DEFAULT_GRAPHBLAS_OPERATOR_OPTIONS: Lazy<OperatorOptions> =
    Lazy::new(|| OperatorOptions::new_default());

#[derive(Debug)]
pub struct SparseVector<T: ValueType> {
    context: Arc<Context>,
    vector: GrB_Vector,
    value_type: PhantomData<T>,
}

// Mutable access to GrB_Vector shall occur through a write lock on RwLock<GrB_Matrix>.
// Code review must consider that the correct lock is made via
// SparseMatrix::get_write_lock() and SparseMatrix::get_read_lock().
// https://doc.rust-lang.org/nomicon/send-and-sync.html
unsafe impl<T: ValueType> Send for SparseVector<T> {}
unsafe impl<T: ValueType> Sync for SparseVector<T> {}

pub unsafe fn new_graphblas_vector(
    context: &Arc<Context>,
    length: &ElementIndex,
    graphblas_value_type: GrB_Type,
) -> Result<GrB_Vector, SparseLinearAlgebraError> {
    let length = length.to_graphblas_index()?;

    let mut vector: MaybeUninit<GrB_Vector> = MaybeUninit::uninit();

    context.call_without_detailed_error_information(|| unsafe {
        GrB_Vector_new(vector.as_mut_ptr(), graphblas_value_type, length)
    })?;

    let vector = unsafe { vector.assume_init() };
    return Ok(vector);
}

impl<T: ValueType> SparseVector<T> {
    pub fn new(
        context: &Arc<Context>,
        length: &ElementIndex,
    ) -> Result<Self, SparseLinearAlgebraError> {
        let context = context.to_owned();

        let vector = unsafe { new_graphblas_vector(&context, length, T::to_graphblas_type())? };
        return Ok(SparseVector {
            context,
            vector,
            value_type: PhantomData,
        });
    }

    pub unsafe fn from_graphblas_vector(
        context: &Arc<Context>,
        vector: GrB_Vector,
    ) -> Result<SparseVector<T>, SparseLinearAlgebraError> {
        Ok(SparseVector {
            context: context.to_owned(),
            vector,
            value_type: PhantomData,
        })
    }

    pub fn from_sparse_scalar(
        context: &Arc<Context>,
        length: &ElementIndex,
        indices: Vec<ElementIndex>,
        value: SparseScalar<T>,
    ) -> Result<Self, SparseLinearAlgebraError> {
        let mut vector = SparseVector::<T>::new(context, length)?;
        let context = context.to_owned();

        let graphblas_length = indices.len().to_graphblas_index()?;

        let mut graphblas_indices = Vec::with_capacity(indices.len());
        for index in indices.into_iter() {
            graphblas_indices.push(index.to_graphblas_index()?);
        }

        context.call_without_detailed_error_information(|| unsafe {
            GxB_Vector_build_Scalar(
                // vector.as_ptr(),
                GetGraphblasSparseVector::graphblas_vector(&vector),
                graphblas_indices.as_ptr(),
                value.graphblas_scalar(),
                graphblas_length,
            )
        })?;

        // let vector = unsafe { vector.assume_init() };
        // return Ok(SparseVector {
        //     context,
        //     vector,
        //     value_type: PhantomData,
        // });
        return Ok(vector);
    }

    pub fn from_sparse_matrix_diagonal(
        matrix: &SparseMatrix<T>,
        diagonal_index: &DiagonalIndex,
    ) -> Result<Self, SparseLinearAlgebraError> {
        let diagonal_length;
        if *diagonal_index > 0 {
            diagonal_length = min(
                matrix.column_width()? - diagonal_index.to_graphblas_element_index()?,
                matrix.row_height()?,
            );
        } else {
            diagonal_length = min(
                matrix.row_height()? - diagonal_index.abs().to_graphblas_element_index()?,
                matrix.column_width()?,
            );
        }

        let diagonal = SparseVector::new(matrix.context_ref(), &diagonal_length)?;
        let context = matrix.context();
        let graphblas_diagonal_index = diagonal_index.to_graphblas_index()?;

        context.call_without_detailed_error_information(|| unsafe {
            GxB_Vector_diag(
                GetGraphblasSparseVector::graphblas_vector(&diagonal),
                matrix.graphblas_matrix(),
                graphblas_diagonal_index,
                DEFAULT_GRAPHBLAS_OPERATOR_OPTIONS.to_graphblas_descriptor(),
            )
        })?;

        return Ok(diagonal);
    }
}

// TODO: this trait is not consistent with other constructors, which do not have a trait
pub trait SparseVectorFromValue<T: ValueType> {
    fn from_value(
        context: &Arc<Context>,
        length: &ElementIndex,
        indices: Vec<ElementIndex>,
        value: T,
    ) -> Result<SparseVector<T>, SparseLinearAlgebraError>;
}

macro_rules! implement_from_value {
    ($value_type: ty) => {
        impl SparseVectorFromValue<$value_type> for SparseVector<$value_type> {
            fn from_value(
                context: &Arc<Context>,
                length: &ElementIndex,
                indices: Vec<ElementIndex>,
                value: $value_type,
            ) -> Result<Self, SparseLinearAlgebraError> {
                let sparse_scalar: SparseScalar<$value_type> =
                    SparseScalar::<$value_type>::from_value(context, value)?;
                SparseVector::<$value_type>::from_sparse_scalar(
                    context,
                    length,
                    indices,
                    sparse_scalar,
                )
            }
        }
    };
}
implement_macro_for_all_value_types!(implement_from_value);

// impl<T: ValueType + CustomValueType> SparseVector<T> {
//     pub fn new_custom_type(
//         // context: Arc<Context>,
//         value_type: Arc<RegisteredCustomValueType<T>>,
//         length: ElementIndex,
//     ) -> Result<Self, SparseLinearAlgebraError> {
//         let mut vector: MaybeUninit<GrB_Vector> = MaybeUninit::uninit();
//         let context = value_type.context();

//         let length = length.to_graphblas_index()?;

//         context.call(|| unsafe {
//             GrB_Vector_new(vector.as_mut_ptr(), value_type.to_graphblas_type(), length)
//         })?;

//         let vector = unsafe { vector.assume_init() };
//         return Ok(SparseVector {
//             context,
//             vector,
//             value_type: PhantomData,
//         });
//     }
// }

impl<T: ValueType> GetContext for SparseVector<T> {
    fn context(&self) -> Arc<Context> {
        self.context.to_owned()
    }
    fn context_ref(&self) -> &Arc<Context> {
        &self.context
    }
}

impl<T: ValueType> Collection for SparseVector<T> {
    fn clear(&mut self) -> Result<(), SparseLinearAlgebraError> {
        self.context
            .call(|| unsafe { GrB_Vector_clear(self.vector) }, &self.vector)?;
        Ok(())
    }

    fn number_of_stored_elements(&self) -> Result<ElementIndex, SparseLinearAlgebraError> {
        let mut number_of_values: MaybeUninit<GrB_Index> = MaybeUninit::uninit();
        self.context.call(
            || unsafe { GrB_Vector_nvals(number_of_values.as_mut_ptr(), self.vector) },
            &self.vector,
        )?;
        let number_of_values = unsafe { number_of_values.assume_init() };
        Ok(ElementIndex::from_graphblas_index(number_of_values)?)
    }
}

pub trait GetGraphblasSparseVector {
    unsafe fn graphblas_vector(&self) -> GrB_Vector;
    unsafe fn graphblas_vector_ref(&self) -> &GrB_Vector;
    unsafe fn graphblas_vector_mut_ref(&mut self) -> &mut GrB_Vector;
}

impl<T: ValueType> GetGraphblasSparseVector for SparseVector<T> {
    unsafe fn graphblas_vector(&self) -> GrB_Vector {
        self.vector.to_owned()
    }
    unsafe fn graphblas_vector_ref(&self) -> &GrB_Vector {
        &self.vector
    }
    unsafe fn graphblas_vector_mut_ref(&mut self) -> &mut GrB_Vector {
        &mut self.vector
    }
}

impl<T: ValueType> Drop for SparseVector<T> {
    fn drop(&mut self) -> () {
        let _ = self
            .context
            .call_without_detailed_error_information(|| unsafe {
                GrB_Vector_free(&mut self.vector)
            });
    }
}

impl<T: ValueType> Clone for SparseVector<T> {
    fn clone(&self) -> Self {
        SparseVector {
            context: self.context.to_owned(),
            vector: unsafe {
                clone_graphblas_vector(self.context_ref(), self.graphblas_vector_ref()).unwrap()
            },
            value_type: PhantomData,
        }
    }
}

pub unsafe fn clone_graphblas_vector(
    context: &Arc<Context>,
    matrix: &GrB_Vector,
) -> Result<GrB_Vector, SparseLinearAlgebraError> {
    let mut matrix_copy: MaybeUninit<GrB_Vector> = MaybeUninit::uninit();
    context
        .call(|| GrB_Vector_dup(matrix_copy.as_mut_ptr(), *matrix), matrix)
        .unwrap();
    return Ok(matrix_copy.assume_init());
}

// TODO: use standard GrB method
// TODO improve printing format
// summary data, column aligning
macro_rules! implement_dispay {
    ($value_type:ty) => {
        impl std::fmt::Display for SparseVector<$value_type> {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                let element_list: VectorElementList<$value_type>;
                match self.get_element_list() {
                    Err(_error) => return Err(std::fmt::Error),
                    Ok(list) => {
                        element_list = list;
                    }
                }

                let indices = element_list.indices_ref();
                let values = element_list.values_ref();

                writeln! {f,"Vector length: {:?}", self.length()?};
                writeln! {f,"Number of stored elements: {:?}", self.number_of_stored_elements()?};

                for element_index in 0..values.len() {
                    write!(
                        f,
                        "({}, {})\n",
                        indices[element_index], values[element_index]
                    );
                }
                return writeln!(f, "");
            }
        }
    };
}
implement_macro_for_all_value_types!(implement_dispay);

// impl SetElement<i128> for SparseVector<i128> {
//     fn set_element(
//         &mut self,
//         element: VectorElement<i128>,
//     ) -> Result<(), SparseLinearAlgebraError> {
//         let index_to_set = element.index().to_graphblas_index()?;
//         // https://users.rust-lang.org/t/cast-c-int-to-mut-c-void/44766/3
//         let value: *mut c_void = &mut element.value() as *mut i128 as *mut c_void; // https://stackoverflow.com/questions/24191249/working-with-c-void-in-an-ffi
//         self.context.call(|| unsafe {
//             GrB_Vector_setElement_UDT(self.vector,  value, index_to_set)
//         })?;
//         Ok(())
//     }
// }

// implement_set_element_for_custom_type!(i128);
// implement_set_element_for_custom_type!(u128);

// macro_rules! implement_get_element_for_custom_type {
//     ($value_type:ty) => {
//         impl GetVectorElement<$value_type> for SparseVector<$value_type> {
//             fn get_element(
//                 &self,
//                 index: ElementIndex,
//             ) -> Result<VectorElement<$value_type>, SparseLinearAlgebraError> {
//                 let mut value: MaybeUninit<$value_type> = MaybeUninit::uninit();
//                 let pointer_to_value: *mut c_void = &mut value as *mut _ as *mut c_void; // https://stackoverflow.com/questions/24191249/working-with-c-void-in-an-ffi
//                 let index_to_get = index.to_graphblas_index()?;

//                 self.context.call(
//                     || unsafe {
//                         GrB_Vector_extractElement_UDT(pointer_to_value, self.vector, index_to_get)
//                     },
//                     &self.vector,
//                 )?;

//                 let value = unsafe { value.assume_init() };

//                 Ok(VectorElement::new(index, value))
//             }
//         }
//     };
// }

// implement_get_element_for_custom_type!(i128);
// implement_get_element_for_custom_type!(u128);

impl<T: ValueType> VectorMask for SparseVector<T> {
    unsafe fn graphblas_vector(&self) -> GrB_Vector {
        GetGraphblasSparseVector::graphblas_vector(self)
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::collections::sparse_matrix::operations::FromMatrixElementList;
    use crate::collections::sparse_matrix::MatrixElementList;
    use crate::collections::sparse_vector::operations::{
        DeleteSparseVectorElement, FromVectorElementList, GetVectorElement,
        GetVectorElementIndices, GetVectorElementValue, GetVectorElementValues, ResizeSparseVector,
        SetVectorElement,
    };
    use crate::collections::sparse_vector::VectorElement;
    use crate::context::Mode;
    use crate::error::{GraphblasErrorType, LogicErrorType, SparseLinearAlgebraErrorType};
    use crate::operators::binary_operator::First;

    #[test]
    fn new_vector() {
        let context = Context::init_ready(Mode::NonBlocking).unwrap();

        let length: ElementIndex = 10;

        let sparse_vector = SparseVector::<i32>::new(&context, &length).unwrap();

        assert_eq!(length, sparse_vector.length().unwrap());
        assert_eq!(0, sparse_vector.number_of_stored_elements().unwrap());
    }

    #[test]
    fn get_indices() {
        let context = Context::init_ready(Mode::NonBlocking).unwrap();

        let length: ElementIndex = 10;
        let value: usize = 11;
        let indices = vec![2, 3, 5];

        let sparse_vector =
            SparseVector::<usize>::from_value(&context, &length, indices.to_owned(), value)
                .unwrap();

        assert_eq!(indices, sparse_vector.element_indices().unwrap());

        let indices = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

        let sparse_vector =
            SparseVector::<usize>::from_value(&context, &length, indices.to_owned(), value)
                .unwrap();

        assert_eq!(indices, sparse_vector.element_indices().unwrap());
    }

    #[test]
    fn get_values() {
        let context = Context::init_ready(Mode::NonBlocking).unwrap();

        let length: ElementIndex = 10;
        let value: u8 = 11;
        let indices = vec![2, 3, 5];

        let sparse_vector =
            SparseVector::<u8>::from_value(&context, &length, indices.to_owned(), value).unwrap();

        assert_eq!(vec![11, 11, 11], sparse_vector.element_values().unwrap());

        let indices = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

        let sparse_vector =
            SparseVector::<u8>::from_value(&context, &length, indices.to_owned(), value).unwrap();

        assert_eq!(
            vec![11, 11, 11, 11, 11, 11, 11, 11, 11, 11],
            sparse_vector.element_values().unwrap()
        );
    }

    #[test]
    fn from_value() {
        let context = Context::init_ready(Mode::NonBlocking).unwrap();

        let length: ElementIndex = 10;
        let value: isize = 11;
        let indices = vec![2, 3, 5];

        let sparse_vector =
            SparseVector::<isize>::from_value(&context, &length, indices.to_owned(), value)
                .unwrap();

        assert_eq!(length, sparse_vector.length().unwrap());
        assert_eq!(
            indices.len(),
            sparse_vector.number_of_stored_elements().unwrap()
        );
        for index in indices {
            assert_eq!(
                sparse_vector.element_value_or_default(&index).unwrap(),
                value
            );
        }
    }

    #[test]
    fn from_sparse_diagonal() {
        let context = Context::init_ready(Mode::NonBlocking).unwrap();

        let element_list = MatrixElementList::<u8>::from_element_vector(vec![
            (0, 0, 0).into(),
            (0, 1, 1).into(),
            (0, 2, 2).into(),
            (2, 2, 4).into(),
            (2, 4, 6).into(),
            (2, 5, 10).into(),
            (3, 1, 4).into(),
        ]);

        let matrix = SparseMatrix::<u8>::from_element_list(
            &context,
            &(10, 15).into(),
            &element_list,
            &First::<u8>::new(),
        )
        .unwrap();

        let diagonal = SparseVector::from_sparse_matrix_diagonal(&matrix, &0).unwrap();
        assert_eq!(diagonal.length().unwrap(), 10);
        assert_eq!(diagonal.number_of_stored_elements().unwrap(), 2);
        assert_eq!(diagonal.element_value_or_default(&0).unwrap(), 0);
        assert_eq!(diagonal.element_value_or_default(&2).unwrap(), 4);

        let diagonal = SparseVector::from_sparse_matrix_diagonal(&matrix, &2).unwrap();
        assert_eq!(diagonal.length().unwrap(), 10);
        assert_eq!(diagonal.number_of_stored_elements().unwrap(), 2);
        assert_eq!(diagonal.element_value_or_default(&0).unwrap(), 2);
        assert_eq!(diagonal.element_value_or_default(&2).unwrap(), 6);

        let diagonal = SparseVector::from_sparse_matrix_diagonal(&matrix, &-2).unwrap();
        assert_eq!(diagonal.length().unwrap(), 8);
        assert_eq!(diagonal.number_of_stored_elements().unwrap(), 1);
        assert_eq!(diagonal.element_value_or_default(&1).unwrap(), 4);
    }

    #[test]
    fn clone_vector() {
        let context = Context::init_ready(Mode::NonBlocking).unwrap();

        let length: ElementIndex = 10;

        let sparse_vector = SparseVector::<f32>::new(&context, &length).unwrap();

        let clone_of_sparse_vector = sparse_vector.to_owned();

        // TODO: implement and test equality operator
        assert_eq!(length, sparse_vector.length().unwrap());
        assert_eq!(
            0,
            clone_of_sparse_vector.number_of_stored_elements().unwrap()
        );
    }

    #[test]
    fn resize_vector() {
        let context = Context::init_ready(Mode::NonBlocking).unwrap();

        let length: ElementIndex = 10;

        let mut sparse_vector = SparseVector::<i32>::new(&context, &length).unwrap();

        let new_length: ElementIndex = 5;
        sparse_vector.resize(new_length.to_owned()).unwrap();

        assert_eq!(new_length, sparse_vector.length().unwrap());

        // TODO: make this a meaningful test by inserting actual values
        assert_eq!(0, sparse_vector.number_of_stored_elements().unwrap());
    }

    #[test]
    fn build_vector() {
        let context = Context::init_ready(Mode::NonBlocking).unwrap();
        let element_list = VectorElementList::<u8>::from_element_vector(vec![
            (1, 1).into(),
            (4, 2).into(),
            (2, 10).into(),
            (2, 11).into(), // duplicate
                            // (10, 10, 10).into(), // out-of-bounds
        ]);
        // println!("{:?}", element_list.to_owned());

        let vector = SparseVector::<u8>::from_element_list(
            &context,
            &10,
            &element_list,
            &First::<u8>::new(),
        )
        .unwrap();

        // println!("{:?}",matrix.get_element_list().unwrap());
        // println!("{:?}", vector.number_of_stored_elements().unwrap());
        // println!("{:?}", vector.number_of_stored_elements().unwrap());
        // println!("{:?}", vector.number_of_stored_elements().unwrap());
        assert_eq!(vector.number_of_stored_elements().unwrap(), 3);
    }

    #[test]
    fn set_element_in_vector() {
        let context = Context::init_ready(Mode::NonBlocking).unwrap();

        let length: ElementIndex = 10;

        let mut sparse_vector = SparseVector::<i32>::new(&context, &length).unwrap();

        sparse_vector
            .set_element(&VectorElement::from_pair(1, 2))
            .unwrap();

        assert_eq!(1, sparse_vector.number_of_stored_elements().unwrap());

        sparse_vector
            .set_element(&VectorElement::from_pair(3, 3))
            .unwrap();

        assert_eq!(2, sparse_vector.number_of_stored_elements().unwrap());

        match sparse_vector.set_element(&VectorElement::from_pair(15, 3)) {
            Err(error) => {
                match error.error_type() {
                    SparseLinearAlgebraErrorType::LogicErrorType(LogicErrorType::GraphBlas(
                        error_type,
                    )) => {
                        assert_eq!(error_type, GraphblasErrorType::InvalidIndex)
                    }
                    _ => assert!(false),
                }
                // match error.error_type() {
                //     SparseLinearAlgebraErrorType::LogicErrorType(error_type) => {
                //         match error_type {
                //             LogicErrorType::GraphBlas(error_type) => {
                //                 assert_eq!(error_type, GraphBlasErrorType::InvalidIndex)
                //             }
                //             _ => assert!(false)
                //         }
                //     }
                //     _ => assert!(false)
                // }
                // assert_eq!(error.error_type(), SparseLinearAlgebraErrorType::LogicErrorType)
            }
            Ok(_) => assert!(false),
        }
    }

    // #[test]
    // fn set_element_in_vector_custom_type() {
    //     let context = Context::init_ready(Mode::NonBlocking).unwrap();

    //     #[repr(C)]
    //     #[derive(Clone, Debug, PartialEq)]
    //     struct CustomType {
    //         prop_1: u64,
    //         prop_2: i16,
    //     }
    //     impl CustomType {
    //         pub fn new(prop_1: u64, prop_2: i16) -> Self {
    //             CustomType {prop_1, prop_2}
    //         }
    //     }

    //     crate::implement_value_type_for_custom_type!(CustomType);
    //     implement_set_element_for_custom_type!(CustomType);

    //     let value_type_i128 = CustomType::register(context).unwrap();
    //     println!("size in Graphblas: {}",value_type_i128.size_in_graphblas().unwrap());

    //     let length: ElementIndex = 10;

    //     let mut sparse_vector = SparseVector::<CustomType>::new(value_type_i128, length.to_owned()).unwrap();

    //     sparse_vector
    //         .set_element(VectorElement::from_pair(1, CustomType::new(2,2)))
    //         .unwrap();

    //     assert_eq!(1, sparse_vector.number_of_stored_elements().unwrap());

    //     sparse_vector
    //         .set_element(VectorElement::from_pair(3, CustomType::new(3,3)))
    //         .unwrap();

    //     assert_eq!(2, sparse_vector.number_of_stored_elements().unwrap());

    //     match sparse_vector.set_element(VectorElement::from_pair(15, CustomType::new(4,2))) {
    //         Err(error) => {
    //             match error.error_type() {
    //                 SparseLinearAlgebraErrorType::LogicErrorType(LogicErrorType::GraphBlas(
    //                     error_type,
    //                 )) => {
    //                     assert_eq!(error_type, GraphBlasErrorType::InvalidIndex)
    //                 }
    //                 _ => assert!(false),
    //             }
    //             // match error.error_type() {
    //             //     SparseLinearAlgebraErrorType::LogicErrorType(error_type) => {
    //             //         match error_type {
    //             //             LogicErrorType::GraphBlas(error_type) => {
    //             //                 assert_eq!(error_type, GraphBlasErrorType::InvalidIndex)
    //             //             }
    //             //             _ => assert!(false)
    //             //         }
    //             //     }
    //             //     _ => assert!(false)
    //             // }
    //             // assert_eq!(error.error_type(), SparseLinearAlgebraErrorType::LogicErrorType)
    //         }
    //         Ok(_) => assert!(false),
    //     }
    // }

    #[test]
    fn remove_element_from_vector() {
        let context = Context::init_ready(Mode::NonBlocking).unwrap();

        let length: ElementIndex = 10;

        let mut sparse_vector = SparseVector::<i64>::new(&context, &length).unwrap();

        sparse_vector
            .set_element(&VectorElement::from_pair(2, 3))
            .unwrap();
        sparse_vector
            .set_element(&VectorElement::from_pair(4, 4))
            .unwrap();

        sparse_vector.drop_element(2).unwrap();

        assert_eq!(sparse_vector.number_of_stored_elements().unwrap(), 1)
    }

    #[test]
    fn get_element_from_vector() {
        let context = Context::init_ready(Mode::NonBlocking).unwrap();

        let length: ElementIndex = 10;

        let mut sparse_vector = SparseVector::<u8>::new(&context, &length).unwrap();

        let element_1 = VectorElement::from_pair(1, 2);
        let element_2 = VectorElement::from_pair(2, 3);

        sparse_vector.set_element(&element_1).unwrap();
        sparse_vector.set_element(&element_2).unwrap();

        assert_eq!(
            element_1,
            sparse_vector
                .get_element_or_default(element_1.index())
                .unwrap()
        );
        assert_eq!(
            element_2,
            sparse_vector
                .get_element_or_default(element_2.index())
                .unwrap()
        );
    }

    // #[test]
    // fn get_element_from_vector_custom_type() {
    // let context = Context::init_ready(Mode::NonBlocking).unwrap();
    // let custom_u128 = u128::register(context).unwrap();

    // let length: ElementIndex = 10;

    // let mut sparse_vector = SparseVector::<u128>::new(custom_u128, length.to_owned()).unwrap();

    // let element_1 = VectorElement::from_pair(1, 2);
    // let element_2 = VectorElement::from_pair(2, 3);

    // sparse_vector.set_element(element_1).unwrap();
    // sparse_vector.set_element(element_2).unwrap();

    // assert_eq!(
    //     element_1,
    //     sparse_vector.get_element(element_1.index()).unwrap()
    // );
    // assert_eq!(
    //     element_2,
    //     sparse_vector.get_element(element_2.index()).unwrap()
    // );
    // }

    #[test]
    fn get_element_list_from_matrix() {
        // TODO: check for a size of zero
        let context = Context::init_ready(Mode::NonBlocking).unwrap();

        let element_list = VectorElementList::<u8>::from_element_vector(vec![
            (1, 1).into(),
            (2, 2).into(),
            (4, 4).into(),
            (5, 5).into(),
        ]);

        let vector = SparseVector::<u8>::from_element_list(
            &context.to_owned(),
            &10,
            &element_list,
            &First::<u8>::new(),
        )
        .unwrap();

        // println!("original element list: {:?}", element_list);
        // println!(
        //     "stored element list: {:?}",
        //     vector.get_element_list().unwrap()
        // );
        assert_eq!(
            vector.number_of_stored_elements().unwrap(),
            element_list.length()
        );

        assert_eq!(vector.get_element_list().unwrap(), element_list);

        let empty_element_list = VectorElementList::<u8>::new();
        let _empty_matrix = SparseVector::<u8>::from_element_list(
            &context,
            &10,
            &empty_element_list,
            &First::<u8>::new(),
        )
        .unwrap();
        assert_eq!(
            vector.number_of_stored_elements().unwrap(),
            element_list.length()
        );
    }
}