-
Notifications
You must be signed in to change notification settings - Fork 11
/
vector.rs
1448 lines (1329 loc) · 47 KB
/
vector.rs
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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This module is provides wrappers around the contents of [`crate::vector_inner`]. The main
//! purpose is to put [`FpVectorP`] for different `p` into a single enum. It does the same for the
//! various slice structs.
//!
//! The main magic occurs in the macro `dispatch_vector_inner`, which we use to provide wrapper
//! functions around the `FpVectorP` functions.
//!
//! This module is only used when the `odd-primes` feature is enabled.
use crate::limb::{entries_per_limb, Limb};
use crate::prime::ValidPrime;
use crate::vector_inner::{
FpVectorIterator, FpVectorNonZeroIteratorP, FpVectorP, SliceMutP, SliceP,
};
use itertools::Itertools;
#[cfg(feature = "json")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::convert::TryInto;
use std::io::{Read, Write};
use std::mem::size_of;
macro_rules! dispatch_vector_inner {
// other is a type, but marking it as a :ty instead of :tt means we cannot use it to access its
// enum variants.
($vis:vis fn $method:ident(&self, other: &$other:tt $(, $arg:ident: $ty:ty )* ) $(-> $ret:ty)?) => {
$vis fn $method(&self, other: &$other, $($arg: $ty),* ) $(-> $ret)* {
match (self, other) {
(Self::_2(ref x), $other::_2(ref y)) => x.$method(y, $($arg),*),
(Self::_3(ref x), $other::_3(ref y)) => x.$method(y, $($arg),*),
(Self::_5(ref x), $other::_5(ref y)) => x.$method(y, $($arg),*),
(Self::_7(ref x), $other::_7(ref y)) => x.$method(y, $($arg),*),
(l, r) => {
panic!("Applying {} to vectors over different primes ({} and {})", stringify!($method), l.prime(), r.prime());
}
}
}
};
($vis:vis fn $method:ident(&mut self, other: &$other:tt $(, $arg:ident: $ty:ty )* ) $(-> $ret:ty)?) => {
#[allow(unused_parens)]
$vis fn $method(&mut self, other: &$other, $($arg: $ty),* ) $(-> $ret)* {
match (self, other) {
(Self::_2(ref mut x), $other::_2(ref y)) => x.$method(y, $($arg),*),
(Self::_3(ref mut x), $other::_3(ref y)) => x.$method(y, $($arg),*),
(Self::_5(ref mut x), $other::_5(ref y)) => x.$method(y, $($arg),*),
(Self::_7(ref mut x), $other::_7(ref y)) => x.$method(y, $($arg),*),
(l, r) => {
panic!("Applying {} to vectors over different primes ({} and {})", stringify!($method), l.prime(), r.prime());
}
}
}
};
($vis:vis fn $method:ident(&mut self, other: $other:tt $(, $arg:ident: $ty:ty )* ) $(-> $ret:ty)?) => {
$vis fn $method(&mut self, other: $other, $($arg: $ty),* ) $(-> $ret)* {
match (self, other) {
(Self::_2(ref mut x), $other::_2(y)) => x.$method(y, $($arg),*),
(Self::_3(ref mut x), $other::_3(y)) => x.$method(y, $($arg),*),
(Self::_5(ref mut x), $other::_5(y)) => x.$method(y, $($arg),*),
(Self::_7(ref mut x), $other::_7(y)) => x.$method(y, $($arg),*),
(l, r) => {
panic!("Applying {} to vectors over different primes ({} and {})", stringify!($method), l.prime(), r.prime());
}
}
}
};
($vis:vis fn $method:ident(&mut self $(, $arg:ident: $ty:ty )* ) -> (dispatch $ret:tt)) => {
$vis fn $method(&mut self, $($arg: $ty),* ) -> $ret {
match self {
Self::_2(ref mut x) => $ret::_2(x.$method($($arg),*)),
Self::_3(ref mut x) => $ret::_3(x.$method($($arg),*)),
Self::_5(ref mut x) => $ret::_5(x.$method($($arg),*)),
Self::_7(ref mut x) => $ret::_7(x.$method($($arg),*)),
}
}
};
($vis:vis fn $method:ident(&self $(, $arg:ident: $ty:ty )* ) -> (dispatch $ret:tt)) => {
$vis fn $method(&self, $($arg: $ty),* ) -> $ret {
match self {
Self::_2(ref x) => $ret::_2(x.$method($($arg),*)),
Self::_3(ref x) => $ret::_3(x.$method($($arg),*)),
Self::_5(ref x) => $ret::_5(x.$method($($arg),*)),
Self::_7(ref x) => $ret::_7(x.$method($($arg),*)),
}
}
};
($vis:vis fn $method:ident(self $(, $arg:ident: $ty:ty )* ) -> (dispatch $ret:tt)) => {
$vis fn $method(self, $($arg: $ty),* ) -> $ret {
match self {
Self::_2(x) => $ret::_2(x.$method($($arg),*)),
Self::_3(x) => $ret::_3(x.$method($($arg),*)),
Self::_5(x) => $ret::_5(x.$method($($arg),*)),
Self::_7(x) => $ret::_7(x.$method($($arg),*)),
}
}
};
($vis:vis fn $method:ident(self $(, $arg:ident: $ty:ty )* ) -> (dispatch $ret:tt $lifetime:tt)) => {
$vis fn $method(self, $($arg: $ty),* ) -> $ret<$lifetime> {
match self {
Self::_2(x) => $ret::_2(x.$method($($arg),*)),
Self::_3(x) => $ret::_3(x.$method($($arg),*)),
Self::_5(x) => $ret::_5(x.$method($($arg),*)),
Self::_7(x) => $ret::_7(x.$method($($arg),*)),
}
}
};
($vis:vis fn $method:ident(&mut self $(, $arg:ident: $ty:ty )* ) $(-> $ret:ty)?) => {
#[allow(unused_parens)]
$vis fn $method(&mut self, $($arg: $ty),* ) $(-> $ret)* {
match self {
Self::_2(ref mut x) => x.$method($($arg),*),
Self::_3(ref mut x) => x.$method($($arg),*),
Self::_5(ref mut x) => x.$method($($arg),*),
Self::_7(ref mut x) => x.$method($($arg),*),
}
}
};
($vis:vis fn $method:ident(&self $(, $arg:ident: $ty:ty )* ) $(-> $ret:ty)?) => {
#[allow(unused_parens)]
$vis fn $method(&self, $($arg: $ty),* ) $(-> $ret)* {
match self {
Self::_2(ref x) => x.$method($($arg),*),
Self::_3(ref x) => x.$method($($arg),*),
Self::_5(ref x) => x.$method($($arg),*),
Self::_7(ref x) => x.$method($($arg),*),
}
}
};
($vis:vis fn $method:ident(self $(, $arg:ident: $ty:ty )* ) $(-> $ret:ty)?) => {
#[allow(unused_parens)]
$vis fn $method(self, $($arg: $ty),* ) $(-> $ret)* {
match self {
Self::_2(x) => x.$method($($arg),*),
Self::_3(x) => x.$method($($arg),*),
Self::_5(x) => x.$method($($arg),*),
Self::_7(x) => x.$method($($arg),*),
}
}
}
}
macro_rules! dispatch_vector {
() => {};
($vis:vis fn $method:ident $tt:tt $(-> $ret:tt)?; $($tail:tt)*) => {
dispatch_vector_inner! {
$vis fn $method $tt $(-> $ret)*
}
dispatch_vector!{$($tail)*}
}
}
macro_rules! match_p {
($p:ident, $($val:tt)*) => {
match *$p {
2 => Self::_2($($val)*),
3 => Self::_3($($val)*),
5 => Self::_5($($val)*),
7 => Self::_7($($val)*),
_ => panic!("Prime not supported: {}", *$p)
}
}
}
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
pub enum FpVector {
_2(FpVectorP<2>),
_3(FpVectorP<3>),
_5(FpVectorP<5>),
_7(FpVectorP<7>),
}
#[derive(Debug, Copy, Clone)]
pub enum Slice<'a> {
_2(SliceP<'a, 2>),
_3(SliceP<'a, 3>),
_5(SliceP<'a, 5>),
_7(SliceP<'a, 7>),
}
#[derive(Debug)]
pub enum SliceMut<'a> {
_2(SliceMutP<'a, 2>),
_3(SliceMutP<'a, 3>),
_5(SliceMutP<'a, 5>),
_7(SliceMutP<'a, 7>),
}
pub enum FpVectorNonZeroIterator<'a> {
_2(FpVectorNonZeroIteratorP<'a, 2>),
_3(FpVectorNonZeroIteratorP<'a, 3>),
_5(FpVectorNonZeroIteratorP<'a, 5>),
_7(FpVectorNonZeroIteratorP<'a, 7>),
}
impl FpVector {
pub fn new(p: ValidPrime, len: usize) -> FpVector {
match_p!(p, FpVectorP::new_(len))
}
pub fn new_with_capacity(p: ValidPrime, len: usize, capacity: usize) -> FpVector {
match_p!(p, FpVectorP::new_with_capacity_(len, capacity))
}
pub fn from_slice(p: ValidPrime, slice: &[u32]) -> Self {
match_p!(p, FpVectorP::from(&slice))
}
pub fn num_limbs(p: ValidPrime, len: usize) -> usize {
let entries_per_limb = entries_per_limb(p);
(len + entries_per_limb - 1) / entries_per_limb
}
pub fn padded_len(p: ValidPrime, len: usize) -> usize {
Self::num_limbs(p, len) * entries_per_limb(p)
}
pub fn from_bytes(p: ValidPrime, len: usize, data: &mut impl Read) -> std::io::Result<Self> {
let num_limbs = Self::num_limbs(p, len);
let mut limbs: Vec<Limb>;
cfg_if::cfg_if! {
if #[cfg(target_endian = "little")] {
limbs = vec![0; num_limbs];
let num_bytes = num_limbs * size_of::<Limb>();
unsafe {
let buf: &mut [u8] = std::slice::from_raw_parts_mut(limbs.as_mut_ptr() as *mut u8, num_bytes);
data.read_exact(buf).unwrap();
}
} else {
limbs = Vec::with_capacity(num_limbs);
for _ in 0..num_limbs {
let mut bytes: [u8; size_of::<Limb>()] = [0; size_of::<Limb>()];
data.read_exact(&mut bytes)?;
limbs.push(Limb::from_le_bytes(bytes));
}
}
};
Ok(match_p!(p, FpVectorP::from_raw_parts(len, limbs)))
}
pub fn to_bytes(&self, buffer: &mut impl Write) -> std::io::Result<()> {
let num_limbs = Self::num_limbs(self.prime(), self.len());
// self.limbs is allowed to have more limbs than necessary, but we only save the
// necessary ones.
for limb in &self.limbs()[0..num_limbs] {
let bytes = limb.to_le_bytes();
buffer.write_all(&bytes)?;
}
Ok(())
}
dispatch_vector! {
pub fn prime(&self) -> ValidPrime;
pub fn len(&self) -> usize;
pub fn is_empty(&self) -> bool;
pub fn scale(&mut self, c: u32);
pub fn set_to_zero(&mut self);
pub fn entry(&self, index: usize) -> u32;
pub fn set_entry(&mut self, index: usize, value: u32);
pub fn assign(&mut self, other: &Self);
pub fn assign_partial(&mut self, other: &Self);
pub fn add(&mut self, other: &Self, c: u32);
pub fn add_nosimd(&mut self, other: &Self, c: u32);
pub fn add_offset(&mut self, other: &Self, c: u32, offset: usize);
pub fn add_offset_nosimd(&mut self, other: &Self, c: u32, offset: usize);
pub fn slice(&self, start: usize, end: usize) -> (dispatch Slice);
pub fn as_slice(&self) -> (dispatch Slice);
pub fn slice_mut(&mut self, start: usize, end: usize) -> (dispatch SliceMut);
pub fn as_slice_mut(&mut self) -> (dispatch SliceMut);
pub fn is_zero(&self) -> bool;
pub fn iter(&self) -> FpVectorIterator;
pub fn iter_nonzero(&self) -> (dispatch FpVectorNonZeroIterator);
pub fn extend_len(&mut self, dim: usize);
pub fn set_scratch_vector_size(&mut self, dim: usize);
pub fn add_basis_element(&mut self, index: usize, value: u32);
pub fn copy_from_slice(&mut self, slice: &[u32]);
pub(crate) fn trim_start(&mut self, n: usize);
pub fn add_truncate(&mut self, other: &Self, c: u32) -> (Option<()>);
pub fn sign_rule(&self, other: &Self) -> bool;
pub fn add_carry(&mut self, other: &Self, c: u32, rest: &mut [FpVector]) -> bool;
pub fn first_nonzero(&mut self) -> (Option<(usize, u32)>);
pub(crate) fn limbs(&self) -> (&[Limb]);
pub(crate) fn limbs_mut(&mut self) -> (&mut [Limb]);
}
}
impl<'a> Slice<'a> {
dispatch_vector! {
pub fn prime(&self) -> ValidPrime;
pub fn len(&self) -> usize;
pub fn is_empty(&self) -> bool;
pub fn entry(&self, index: usize) -> u32;
pub fn iter(self) -> (FpVectorIterator<'a>);
pub fn iter_nonzero(self) -> (dispatch FpVectorNonZeroIterator 'a);
pub fn is_zero(&self) -> bool;
pub fn slice(self, start: usize, end: usize) -> (dispatch Slice 'a);
pub fn to_owned(self) -> (dispatch FpVector);
}
}
impl<'a> SliceMut<'a> {
dispatch_vector! {
pub fn prime(&self) -> ValidPrime;
pub fn scale(&mut self, c: u32);
pub fn set_to_zero(&mut self);
pub fn add(&mut self, other: Slice, c: u32);
pub fn assign(&mut self, other: Slice);
pub fn set_entry(&mut self, index: usize, value: u32);
pub fn as_slice(&self) -> (dispatch Slice);
pub fn slice_mut(&mut self, start: usize, end: usize) -> (dispatch SliceMut);
pub fn add_basis_element(&mut self, index: usize, value: u32);
pub fn copy(&mut self) -> (dispatch SliceMut);
}
pub fn add_tensor(&mut self, offset: usize, coeff: u32, left: Slice, right: Slice) {
match (self, left, right) {
(SliceMut::_2(ref mut x), Slice::_2(y), Slice::_2(z)) => {
x.add_tensor(offset, coeff, y, z)
}
(SliceMut::_3(ref mut x), Slice::_3(y), Slice::_3(z)) => {
x.add_tensor(offset, coeff, y, z)
}
(SliceMut::_5(ref mut x), Slice::_5(y), Slice::_5(z)) => {
x.add_tensor(offset, coeff, y, z)
}
(SliceMut::_7(ref mut x), Slice::_7(y), Slice::_7(z)) => {
x.add_tensor(offset, coeff, y, z)
}
_ => {
panic!("Applying add_tensor to vectors over different primes");
}
}
}
}
impl<'a> FpVectorNonZeroIterator<'a> {
dispatch_vector! {
fn next(&mut self) -> (Option<(usize, u32)>);
}
}
impl std::fmt::Display for FpVector {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.as_slice().fmt(f)
}
}
impl<'a> std::fmt::Display for Slice<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "[{}]", self.iter().format(", "))?;
Ok(())
}
}
impl From<&FpVector> for Vec<u32> {
fn from(v: &FpVector) -> Vec<u32> {
v.iter().collect()
}
}
impl std::ops::AddAssign<&FpVector> for FpVector {
fn add_assign(&mut self, other: &FpVector) {
self.add(other, 1);
}
}
impl<'a> Iterator for FpVectorNonZeroIterator<'a> {
type Item = (usize, u32);
fn next(&mut self) -> Option<Self::Item> {
self.next()
}
}
impl<'a> IntoIterator for &'a FpVector {
type IntoIter = FpVectorIterator<'a>;
type Item = u32;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
macro_rules! impl_try_into {
($var:tt, $p:literal) => {
impl<'a> TryInto<&'a mut FpVectorP<$p>> for &'a mut FpVector {
type Error = ();
fn try_into(self) -> Result<&'a mut FpVectorP<$p>, ()> {
match self {
FpVector::$var(ref mut x) => Ok(x),
_ => Err(()),
}
}
}
};
}
impl_try_into!(_2, 2);
impl_try_into!(_3, 3);
impl_try_into!(_5, 5);
impl_try_into!(_7, 7);
#[cfg(feature = "json")]
impl Serialize for FpVector {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
Vec::<u32>::from(self).serialize(serializer)
}
}
#[cfg(feature = "json")]
impl<'de> Deserialize<'de> for FpVector {
fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
panic!("Deserializing FpVector not supported");
// This is needed for ext-websocket/actions to be happy
}
}
impl<'a, 'b> From<&'a mut SliceMut<'b>> for SliceMut<'a> {
fn from(slice: &'a mut SliceMut<'b>) -> SliceMut<'a> {
slice.copy()
}
}
impl<'a, 'b> From<&'a Slice<'b>> for Slice<'a> {
fn from(slice: &'a Slice<'b>) -> Slice<'a> {
*slice
}
}
impl<'a, 'b> From<&'a SliceMut<'b>> for Slice<'a> {
fn from(slice: &'a SliceMut<'b>) -> Slice<'a> {
slice.as_slice()
}
}
impl<'a> From<&'a FpVector> for Slice<'a> {
fn from(v: &'a FpVector) -> Slice<'a> {
v.as_slice()
}
}
impl<'a> From<&'a mut FpVector> for SliceMut<'a> {
fn from(v: &'a mut FpVector) -> SliceMut<'a> {
v.as_slice_mut()
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::limb;
use rand::Rng;
use rstest::rstest;
pub struct VectorDiffEntry {
pub index: usize,
pub left: u32,
pub right: u32,
}
impl FpVector {
pub fn diff_list(&self, other: &[u32]) -> Vec<VectorDiffEntry> {
assert!(self.len() == other.len());
let mut result = Vec::new();
#[allow(clippy::needless_range_loop)]
for index in 0..self.len() {
let left = self.entry(index);
let right = other[index];
if left != right {
result.push(VectorDiffEntry { index, left, right });
}
}
result
}
pub fn diff_vec(&self, other: &FpVector) -> Vec<VectorDiffEntry> {
assert!(self.len() == other.len());
let mut result = Vec::new();
for index in 0..self.len() {
let left = self.entry(index);
let right = other.entry(index);
if left != right {
result.push(VectorDiffEntry { index, left, right });
}
}
result
}
pub fn format_diff(diff: Vec<VectorDiffEntry>) -> String {
let data_formatter =
diff.iter()
.format_with("\n ", |VectorDiffEntry { index, left, right }, f| {
f(&format_args!(" At index {}: {}!={}", index, left, right))
});
format!("{}", data_formatter)
}
pub fn assert_list_eq(&self, other: &[u32]) {
let diff = self.diff_list(other);
if diff.is_empty() {
return;
}
panic!(
"assert {} == {:?}\n{}",
self,
other,
FpVector::format_diff(diff)
);
}
pub fn assert_vec_eq(&self, other: &FpVector) {
let diff = self.diff_vec(other);
if diff.is_empty() {
return;
}
panic!(
"assert {} == {:?}\n{}",
self,
other,
FpVector::format_diff(diff)
);
}
}
fn random_vector(p: impl Into<u32>, dimension: usize) -> Vec<u32> {
let p: u32 = p.into();
let mut result = Vec::with_capacity(dimension);
let mut rng = rand::thread_rng();
for _ in 0..dimension {
result.push(rng.gen::<u32>() % p);
}
result
}
macro_rules! test_dim {
() => {};
(fn $name:ident($p:ident: ValidPrime) $body:tt $($rest:tt)*) => {
#[rstest]
#[trace]
fn $name(#[values(2, 3, 5, 7)] p: u32) {
let $p = ValidPrime::new(p);
$body
}
test_dim! { $($rest)* }
};
(fn $name:ident($p:ident: ValidPrime, $dim:ident: usize) $body:tt $($rest:tt)*) => {
#[rstest]
#[trace]
fn $name(#[values(2, 3, 5, 7)] p: u32, #[values(10, 20, 70, 100, 1000)] $dim: usize) {
let $p = ValidPrime::new(p);
$body
}
test_dim! { $($rest)* }
};
(fn $name:ident($p:ident: ValidPrime, $dim:ident: usize, $slice_start:ident: usize, $slice_end:ident: usize) $body:tt $($rest:tt)*) => {
#[rstest]
#[trace]
fn $name(#[values(2, 3, 5, 7)] p: u32, #[values(10, 20, 70, 100, 1000)] $dim: usize) {
let $p = ValidPrime::new(p);
let $slice_start = match $dim {
10 => 5,
20 => 10,
70 => 20,
100 => 30,
1000 => 290,
_ => unreachable!(),
};
let $slice_end = ($dim + $slice_start) / 2;
$body
}
test_dim! { $($rest)* }
};
}
test_dim! {
fn test_serialize(p: ValidPrime, dim: usize) {
use std::io::{Seek, Cursor, SeekFrom};
let v_arr = random_vector(p, dim);
let v = FpVector::from_slice(p, &v_arr);
let mut cursor = Cursor::new(Vec::<u8>::new());
v.to_bytes(&mut cursor).unwrap();
cursor.seek(SeekFrom::Start(0)).unwrap();
let w = FpVector::from_bytes(p, dim, &mut cursor).unwrap();
v.assert_vec_eq(&w);
}
fn test_add(p: ValidPrime, dim: usize) {
let mut v_arr = random_vector(p, dim);
let w_arr = random_vector(p, dim);
let mut v = FpVector::from_slice(p, &v_arr);
let w = FpVector::from_slice(p, &w_arr);
v.add(&w, 1);
for i in 0..dim {
v_arr[i] = (v_arr[i] + w_arr[i]) % *p;
}
v.assert_list_eq(&v_arr);
}
fn test_scale(p: ValidPrime, dim: usize) {
let mut v_arr = random_vector(p, dim);
let mut rng = rand::thread_rng();
let c = rng.gen::<u32>() % *p;
let mut v = FpVector::from_slice(p, &v_arr);
v.scale(c);
for entry in &mut v_arr {
*entry = (*entry * c) % *p;
}
v.assert_list_eq(&v_arr);
}
fn test_scale_slice(p: ValidPrime, dim: usize, slice_start: usize, slice_end: usize) {
let mut v_arr = random_vector(p, dim);
let mut rng = rand::thread_rng();
let c = rng.gen::<u32>() % *p;
let mut v = FpVector::from_slice(p, &v_arr);
v.slice_mut(slice_start, slice_end).scale(c);
for entry in &mut v_arr[slice_start .. slice_end] {
*entry = (*entry * c) % *p;
}
v.assert_list_eq(&v_arr);
}
fn test_entry(p: ValidPrime, dim: usize) {
let v_arr = random_vector(p, dim);
let v = FpVector::from_slice(p, &v_arr);
let mut diffs = Vec::new();
for (i, val) in v.iter().enumerate() {
if v.entry(i) != val {
diffs.push((i, val, v.entry(i)));
}
}
assert_eq!(diffs, []);
}
fn test_entry_slice(p: ValidPrime, dim: usize, slice_start: usize, slice_end: usize) {
let v_arr = random_vector(p, dim);
let v = FpVector::from_slice(p, &v_arr);
let v = v.slice(slice_start, slice_end);
println!(
"slice_start: {}, slice_end: {}, slice: {}",
slice_start, slice_end, v
);
let mut diffs = Vec::new();
for i in 0..v.len() {
if v.entry(i) != v_arr[i + slice_start] {
diffs.push((i, v_arr[i + slice_start], v.entry(i)));
}
}
assert_eq!(diffs, []);
}
fn test_set_entry(p: ValidPrime, dim: usize) {
let mut v = FpVector::new(p, dim);
let v_arr = random_vector(p, dim);
for (i, &val) in v_arr.iter().enumerate() {
v.set_entry(i, val);
}
v.assert_list_eq(&v_arr);
}
fn test_set_entry_slice(p: ValidPrime, dim: usize, slice_start: usize, slice_end: usize) {
let mut v = FpVector::new(p, dim);
let mut v = v.slice_mut(slice_start, slice_end);
let slice_dim = v.as_slice().len();
let v_arr = random_vector(p, slice_dim);
for (i, &val) in v_arr.iter().enumerate() {
v.set_entry(i, val);
}
let v = v.as_slice();
// println!("slice_start: {}, slice_end: {}, slice: {}", slice_start, slice_end, v);
let mut diffs = Vec::new();
for (i, &val) in v_arr.iter().enumerate() {
if v.entry(i) != val {
diffs.push((i, val, v.entry(i)));
}
}
assert_eq!(diffs, []);
}
fn test_set_to_zero_slice(p: ValidPrime, dim: usize, slice_start: usize, slice_end: usize) {
println!("slice_start : {}, slice_end : {}", slice_start, slice_end);
let mut v_arr = random_vector(p, dim);
v_arr[0] = 1; // make sure that v isn't zero
let mut v = FpVector::from_slice(p, &v_arr);
v.slice_mut(slice_start, slice_end).set_to_zero();
assert!(v.slice(slice_start, slice_end).is_zero());
assert!(!v.is_zero()); // The first entry is 1, so it's not zero.
for entry in &mut v_arr[slice_start..slice_end] {
*entry = 0;
}
v.assert_list_eq(&v_arr);
}
fn test_add_slice_to_slice(p: ValidPrime, dim: usize, slice_start: usize, slice_end: usize) {
let mut v_arr = random_vector(p, dim);
let w_arr = random_vector(p, dim);
let mut v = FpVector::from_slice(p, &v_arr);
let w = FpVector::from_slice(p, &w_arr);
v.slice_mut(slice_start, slice_end)
.add(w.slice(slice_start, slice_end), 1);
for i in slice_start..slice_end {
v_arr[i] = (v_arr[i] + w_arr[i]) % *p;
}
v.assert_list_eq(&v_arr);
}
fn test_assign(p: ValidPrime, dim: usize) {
let v_arr = random_vector(p, dim);
let w_arr = random_vector(p, dim);
let mut v = FpVector::from_slice(p, &v_arr);
let w = FpVector::from_slice(p, &w_arr);
v.assign(&w);
v.assert_vec_eq(&w);
}
fn test_assign_partial(p: ValidPrime, dim: usize) {
let v_arr = random_vector(p, dim);
let w_arr = random_vector(p, dim / 2);
let mut v = FpVector::from_slice(p, &v_arr);
let w = FpVector::from_slice(p, &w_arr);
v.assign_partial(&w);
assert!(v.slice(dim / 2, dim).is_zero());
assert_eq!(v.len(), dim);
v.slice(0, dim / 2).to_owned().assert_vec_eq(&w);
}
fn test_assign_slice_to_slice(p: ValidPrime, dim: usize, slice_start: usize, slice_end: usize) {
let mut v_arr = random_vector(p, dim);
let mut w_arr = random_vector(p, dim);
v_arr[0] = 1; // Ensure v != w.
w_arr[0] = 0; // Ensure v != w.
let mut v = FpVector::from_slice(p, &v_arr);
let w = FpVector::from_slice(p, &w_arr);
v.slice_mut(slice_start, slice_end)
.assign(w.slice(slice_start, slice_end));
v_arr[slice_start..slice_end].clone_from_slice(&w_arr[slice_start..slice_end]);
v.assert_list_eq(&v_arr);
}
fn test_add_shift_right(p: ValidPrime, dim: usize, slice_start: usize, slice_end: usize) {
let mut v_arr = random_vector(p, dim);
let w_arr = random_vector(p, dim);
let mut v = FpVector::from_slice(p, &v_arr);
let w = FpVector::from_slice(p, &w_arr);
v.slice_mut(slice_start + 2, slice_end + 2)
.add(w.slice(slice_start, slice_end), 1);
println!("v : {}", v);
for i in slice_start + 2..slice_end + 2 {
v_arr[i] = (v_arr[i] + w_arr[i - 2]) % *p;
}
v.assert_list_eq(&v_arr);
}
fn test_add_shift_left(p: ValidPrime, dim: usize, slice_start: usize, slice_end: usize) {
let mut v_arr = random_vector(p, dim);
let w_arr = random_vector(p, dim);
let mut v = FpVector::from_slice(p, &v_arr);
let w = FpVector::from_slice(p, &w_arr);
v.slice_mut(slice_start - 2, slice_end - 2)
.add(w.slice(slice_start, slice_end), 1);
for i in slice_start - 2..slice_end - 2 {
v_arr[i] = (v_arr[i] + w_arr[i + 2]) % *p;
}
v.assert_list_eq(&v_arr);
}
fn test_iterator_slice(p: ValidPrime) {
let ep = entries_per_limb(p);
for &dim in &[5, 10, ep, ep - 1, ep + 1, 3 * ep, 3 * ep - 1, 3 * ep + 1] {
let v_arr = random_vector(p, dim);
let v = FpVector::from_slice(p, &v_arr);
let v = v.slice(3, dim - 1);
println!("v: {:?}", v_arr);
let w = v.iter();
let mut counter = 0;
for (i, x) in w.enumerate() {
println!("i: {}, dim : {}", i, dim);
assert_eq!(v.entry(i), x);
counter += 1;
}
assert_eq!(counter, v.len());
}
}
fn test_iterator_skip(p: ValidPrime) {
let ep = entries_per_limb(p);
let dim = 5 * ep;
for &num_skip in &[ep, ep - 1, ep + 1, 3 * ep, 3 * ep - 1, 3 * ep + 1, 6 * ep] {
let v_arr = random_vector(p, dim);
let v = FpVector::from_slice(p, &v_arr);
let mut w = v.iter();
w.skip_n(num_skip);
let mut counter = 0;
for (i, x) in w.enumerate() {
assert_eq!(v.entry(i + num_skip), x);
counter += 1;
}
if num_skip == 6 * ep {
assert_eq!(counter, 0);
} else {
assert_eq!(counter, v.len() - num_skip);
}
}
}
fn test_iterator(p: ValidPrime) {
let ep = entries_per_limb(p);
for &dim in &[0, 5, 10, ep, ep - 1, ep + 1, 3 * ep, 3 * ep - 1, 3 * ep + 1] {
let v_arr = random_vector(p, dim);
let v = FpVector::from_slice(p, &v_arr);
let w = v.iter();
let mut counter = 0;
for (i, x) in w.enumerate() {
assert_eq!(v.entry(i), x);
counter += 1;
}
assert_eq!(counter, v.len());
}
}
fn test_iter_nonzero_empty(p: ValidPrime) {
let v = FpVector::new(p, 0);
for (_, _) in v.iter_nonzero() {
panic!();
}
}
fn test_iter_nonzero_slice(p: ValidPrime) {
let mut v = FpVector::new(p, 5);
v.set_entry(0, 1);
v.set_entry(1, 1);
v.set_entry(2, 1);
for (i, _) in v.slice(0, 1).iter_nonzero() {
assert_eq!(i, 0);
}
}
fn test_iter_nonzero(p: ValidPrime, dim: usize, slice_start: usize, slice_end: usize) {
let v_arr = random_vector(p, dim);
let v = FpVector::from_slice(p, &v_arr);
println!("v: {}", v);
println!("v_arr: {:?}", v_arr);
let result: Vec<_> = v.slice(slice_start, slice_end).iter_nonzero().collect();
let comparison_result: Vec<_> = (&v_arr[slice_start..slice_end])
.iter()
.copied()
.enumerate()
.filter(|&(_, x)| x != 0)
.collect();
let mut i = 0;
let mut j = 0;
let mut diffs_str = String::new();
while i < result.len() && j < comparison_result.len() {
if result[i] != comparison_result[j] {
if result[i].0 < comparison_result[j].0 {
diffs_str.push_str(&format!(
"\n({:?}) present in result, missing from comparison_result",
result[i]
));
i += 1;
} else {
diffs_str.push_str(&format!(
"\n({:?}) present in comparison_result, missing from result",
comparison_result[j]
));
j += 1;
}
} else {
i += 1;
j += 1;
}
}
// for i in 0 .. std::cmp::min(result.len(), comparison_result.len()) {
// println!("res : {:?}, comp : {:?}", result[i], comparison_result[i]);
// }
assert!(diffs_str.is_empty(), "{}", diffs_str);
}
}
#[rstest]
#[trace]
fn test_add_carry(#[values(2)] p: u32, #[values(10, 20, 70, 100, 1000)] dim: usize) {
let p = ValidPrime::new(p);
const E_MAX: usize = 4;
let pto_the_e_max = (*p * *p * *p * *p) * *p;
let mut v = Vec::with_capacity(E_MAX + 1);
let mut w = Vec::with_capacity(E_MAX + 1);
for _ in 0..=E_MAX {
v.push(FpVector::new(p, dim));
w.push(FpVector::new(p, dim));
}
let v_arr = random_vector(pto_the_e_max, dim);
let w_arr = random_vector(pto_the_e_max, dim);
for i in 0..dim {
let mut ev = v_arr[i];
let mut ew = w_arr[i];
for e in 0..=E_MAX {
v[e].set_entry(i, ev % *p);
w[e].set_entry(i, ew % *p);
ev /= *p;
ew /= *p;
}
}
println!("in : {:?}", v_arr);
for (e, val) in v.iter().enumerate() {
println!("in {}: {}", e, val);
}
println!();
println!("in : {:?}", w_arr);
for (e, val) in w.iter().enumerate() {
println!("in {}: {}", e, val);
}
println!();
for e in 0..=E_MAX {
let (first, rest) = v[e..].split_at_mut(1);
first[0].add_carry(&w[e], 1, rest);
}
let mut vec_result = vec![0; dim];
for (i, entry) in vec_result.iter_mut().enumerate() {
for e in (0..=E_MAX).rev() {
*entry *= *p;
*entry += v[e].entry(i);
}
}
for (e, val) in v.iter().enumerate() {
println!("out{}: {}", e, val);
}
println!();
let mut comparison_result = vec![0; dim];
for i in 0..dim {
comparison_result[i] = (v_arr[i] + w_arr[i]) % pto_the_e_max;
}
println!("out : {:?}", comparison_result);
let mut diffs = Vec::new();
let mut diffs_str = String::new();
for i in 0..dim {
if vec_result[i] != comparison_result[i] {
diffs.push((i, comparison_result[i], vec_result[i]));
diffs_str.push_str(&format!(
"\nIn position {} expected {} got {}. v[i] = {}, w[i] = {}.",
i, comparison_result[i], vec_result[i], v_arr[i], w_arr[i]
));
}
}
assert!(diffs.is_empty(), "{}", diffs_str);
}
#[test]