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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
use std::iter::FromIterator;
use std::ops::{
    Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign,
    Mul, MulAssign, Neg, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign,
};
use std::slice::SliceIndex;

use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use crate::zip;

use super::{AsMutSlice, AsMutTensor, AsRefSlice, AsRefTensor, LoadError, SaveError};

use concrete_commons::numeric::{CastFrom, UnsignedInteger};
#[cfg(feature = "multithread")]
use rayon::{iter::IndexedParallelIterator, prelude::*};

/// A generic type to perform operations on collections of scalar values.
///
/// See the [module-level](`super`) documentation for more explanations on the logic of this type.
///
/// # Naming convention
///
/// The methods that may mutate the values of a `Tensor`, follow a convention:
///
/// + Methods prefixed with `update_with` use the current values of `self` when performing the
/// operation.
/// + Methods prefixed with `fill_with` discard the current vales of `self`, and overwrite it with
/// the result of an operation on other values.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
#[repr(transparent)]
pub struct Tensor<Container: ?Sized>(Container);

impl<Element> Tensor<Vec<Element>> {
    /// Allocates a new `Tensor<Vec<T>>` whose values are all `value`.
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let tensor = Tensor::allocate(9 as u8, 1000);
    /// assert_eq!(tensor.len(), 1000);
    /// assert_eq!(*tensor.get_element(0), 9);
    /// assert_eq!(*tensor.get_element(1), 9);
    /// ```
    pub fn allocate(value: Element, size: usize) -> Self
    where
        Element: Copy,
    {
        Tensor(vec![value; size])
    }

    /// Saves a tensor to a binary file.
    ///
    /// # Note
    /// The file format does not contain a type signature that guarantees that the file was
    /// restored to the same type it was saved.
    ///
    /// # Example
    /// ```rust
    /// use concrete_core::math::tensor::Tensor;
    /// use std::path::PathBuf;
    /// let t = Tensor::allocate(66 as u8, 10_000);
    /// let path = PathBuf::from("/tmp/test_save_tensor.ts");
    /// # if path.exists() {std::fs::remove_file(&path);}
    /// assert!(!path.exists());
    /// t.save_to_file(&path);
    /// assert!(path.exists());
    /// ```
    pub fn save_to_file<Path: AsRef<std::path::Path>>(&self, path: Path) -> Result<(), SaveError>
    where
        Self: Serialize,
    {
        let file =
            std::fs::File::create(path.as_ref()).map_err(|source| SaveError::CreatingFile {
                filename: path.as_ref().to_owned().to_str().unwrap().into(),
                source,
            })?;
        bincode::serialize_into(file, self).map_err(|source| SaveError::WritingFile {
            filename: path.as_ref().to_owned().to_str().unwrap().into(),
            source,
        })
    }

    /// Loads a tensor from a binary file.
    ///
    /// # Note
    /// The file format does not contain a type signature that guarantees that the file was
    /// restored to the same type it was saved.
    ///
    /// # Example
    /// ```rust
    /// use concrete_core::math::tensor::Tensor;
    /// use std::path::PathBuf;
    /// let t_initial = Tensor::allocate(66 as u8, 10_000);
    /// let path = PathBuf::from("/tmp/test_save_tensor.ts");
    /// # if path.exists() {std::fs::remove_file(&path);}
    /// t_initial.save_to_file(&path);
    /// let t_recovered = Tensor::load_from_file(&path).unwrap();
    /// assert_eq!(t_initial, t_recovered);
    /// ```
    pub fn load_from_file<Path: AsRef<std::path::Path>>(path: Path) -> Result<Self, LoadError>
    where
        Self: DeserializeOwned,
    {
        let file = std::fs::File::open(path.as_ref()).map_err(|source| LoadError::OpeningFile {
            filename: path.as_ref().to_owned().to_str().unwrap().into(),
            source,
        })?;
        bincode::deserialize_from(file).map_err(|source| LoadError::ReadingFile {
            filename: path.as_ref().to_owned().to_str().unwrap().into(),
            source,
        })
    }
}

macro_rules! fill_with {
    ($Trait:ident, $name: ident, $($func:tt)*) => {
            pub fn $name<Lhs, Rhs>(
                &mut self,
                lhs: &Tensor<Lhs>,
                rhs: &Tensor<Rhs>,
            ) where
                Tensor<Lhs>: AsRefSlice,
                Tensor<Rhs>: AsRefSlice,
                Self: AsMutSlice,
                <Tensor<Lhs> as AsRefSlice>::Element: $Trait<<Tensor<Rhs> as AsRefSlice>::Element,
                Output=<Self as AsMutSlice>::Element>,
                <Tensor<Lhs> as AsRefSlice>::Element: Copy,
                <Tensor<Rhs> as AsRefSlice>::Element: Copy
            {
                ck_dim_eq!(self.len() => lhs.len());
                ck_dim_eq!(self.len() => rhs.len());
                Tensor::fill_with_two(self, lhs, rhs, $($func)*);
            }
    };
}

macro_rules! fill_with_wrapping {
    ($name: ident, $($func:tt)*) => {
            pub fn $name<Lhs, Rhs, Element>(
                &mut self,
                lhs: &Tensor<Lhs>,
                rhs: &Tensor<Rhs>,
            ) where
                Tensor<Lhs>: AsRefSlice<Element=Element>,
                Tensor<Rhs>: AsRefSlice<Element=Element>,
                Self: AsMutSlice<Element=Element>,
                Element: UnsignedInteger
            {
                ck_dim_eq!(self.len() => lhs.len());
                ck_dim_eq!(self.len() => rhs.len());
                Tensor::fill_with_two(self, lhs, rhs, $($func)*);
            }
    };
}

macro_rules! update_with {
    ($Trait:ident, $name: ident, $($func:tt)*) => {
            pub fn $name<Other>(
                &mut self,
                other: &Tensor<Other>,
            ) where
                Self: AsMutSlice,
                Tensor<Other>: AsRefSlice,
                <Self as AsMutSlice>::Element: $Trait<<Tensor<Other> as AsRefSlice>::Element>,
                <Tensor<Other> as AsRefSlice>::Element: Copy
            {
                ck_dim_eq!(self.len() => other.len());
                self.update_with_one(other, $($func)*);
            }
    };
}

macro_rules! update_with_wrapping {
    ($name: ident, $($func:tt)*) => {
            pub fn $name<Other, Element>(
                &mut self,
                other: &Tensor<Other>,
            ) where
                Self: AsMutSlice<Element=Element>,
                Tensor<Other>: AsRefSlice<Element=Element>,
                Element: UnsignedInteger
            {
                ck_dim_eq!(self.len() => other.len());
                self.update_with_one(other, $($func)*);
            }
    };
}

macro_rules! update_with_scalar {
    ($Trait:ident, $name: ident, $($func:tt)*) => {
            pub fn $name<Element>(
                &mut self,
                element: &Element,
            ) where
                Self: AsMutSlice,
                <Self as AsMutSlice>::Element: $Trait<Element>,
                Element: Copy
            {
                self.update_with_element(element, $($func)*);
            }
    };
}

macro_rules! update_with_wrapping_scalar {
    ($name: ident, $($func:tt)*) => {
            pub fn $name<Element>(
                &mut self,
                element: &Element,
            ) where
                Self: AsMutSlice<Element=Element>,
                Element: UnsignedInteger
            {
                self.update_with_element(element, $($func)*);
            }
    };
}

impl<Container> Tensor<Container> {
    /// Creates a new tensor from a container.
    ///
    /// # Example
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let vec = vec![9 as u8; 1000];
    /// let view = vec.as_slice();
    /// let tensor = Tensor::from_container(view);
    /// assert_eq!(tensor.len(), 1000);
    /// assert_eq!(*tensor.get_element(0), 9);
    /// assert_eq!(*tensor.get_element(1), 9);
    /// ```
    pub fn from_container(cont: Container) -> Self {
        Tensor(cont)
    }

    /// Consumes a tensor and returns its container.
    ///
    /// # Example
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let tensor = Tensor::allocate(9 as u8, 1000);
    /// let vec = tensor.into_container();
    /// assert_eq!(vec.len(), 1000);
    /// assert_eq!(vec[0], 9);
    /// assert_eq!(vec[1], 9);
    /// ```
    pub fn into_container(self) -> Container {
        self.0
    }

    /// Returns a reference to the tensor container.
    ///
    /// # Example
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let tensor = Tensor::allocate(9 as u8, 1000);
    /// let vecref: &Vec<_> = tensor.as_container();
    /// ```
    pub fn as_container(&self) -> &Container {
        &self.0
    }

    /// Returns a mutable reference to the tensor container.
    ///
    /// # Example
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// let vecmut: &mut Vec<_> = tensor.as_mut_container();
    /// ```
    pub fn as_mut_container(&mut self) -> &mut Container {
        &mut self.0
    }

    /// Returns the length of the tensor.
    ///
    /// # Example
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let tensor = Tensor::allocate(9 as u8, 1000);
    /// assert_eq!(tensor.len(), 1000);
    /// ```
    pub fn len(&self) -> usize
    where
        Self: AsRefSlice,
    {
        self.as_slice().len()
    }

    /// Returns whether the tensor is empty.
    ///
    /// # Example
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let tensor = Tensor::allocate(9 as u8, 1000);
    /// assert_eq!(tensor.is_empty(), false);
    /// ```
    pub fn is_empty(&self) -> bool
    where
        Self: AsRefSlice,
    {
        self.as_slice().len() == 0
    }

    /// Returns an iterator over `&Scalar` elements.
    ///
    /// # Example
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let tensor = Tensor::allocate(9 as u8, 1000);
    /// for scalar in tensor.iter() {
    ///     assert_eq!(*scalar, 9);
    /// }
    /// ```
    pub fn iter(
        &self,
    ) -> impl DoubleEndedIterator<Item = &<Self as AsRefSlice>::Element> + ExactSizeIterator
    where
        Self: AsRefSlice,
    {
        self.as_slice().iter()
    }

    /// Returns a parallel iterator over `&Scalar` elements.
    ///
    /// # Notes:
    /// This iterator is hidden behind the "multithread" feature gate.
    ///
    /// # Example
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// use rayon::iter::ParallelIterator;
    /// let tensor = Tensor::allocate(9 as u8, 1000);
    /// tensor.par_iter().for_each(|scalar| {
    ///     assert_eq!(*scalar, 9);
    /// });
    /// ```
    #[cfg(feature = "multithread")]
    pub fn par_iter(&self) -> impl IndexedParallelIterator<Item = &<Self as AsRefSlice>::Element>
    where
        Self: AsRefSlice,
        <Self as AsRefSlice>::Element: Sync,
    {
        self.as_slice().as_parallel_slice().par_iter()
    }

    /// Returns an iterator over `&mut T` elements.
    ///
    /// # Example:
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// for mut scalar in tensor.iter_mut() {
    ///     *scalar = 8;
    /// }
    /// for scalar in tensor.iter() {
    ///     assert_eq!(*scalar, 8);
    /// }
    /// ```
    pub fn iter_mut(
        &mut self,
    ) -> impl DoubleEndedIterator<Item = &mut <Self as AsMutSlice>::Element> + ExactSizeIterator
    where
        Self: AsMutSlice,
    {
        self.as_mut_slice().iter_mut()
    }

    /// Returns a parallel iterator over `&mut T` elements.
    ///
    /// # Notes:
    /// This iterator is hidden behind the "multithread" feature gate.
    ///
    /// # Example:
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// tensor.iter_mut().for_each(|mut scalar| {
    ///     *scalar = 8;
    /// });
    /// for scalar in tensor.iter() {
    ///     assert_eq!(*scalar, 8);
    /// }
    /// ```
    #[cfg(feature = "multithread")]
    pub fn par_iter_mut(
        &mut self,
    ) -> impl IndexedParallelIterator<Item = &mut <Self as AsMutSlice>::Element>
    where
        Self: AsMutSlice,
        <Self as AsMutSlice>::Element: Sync + Send,
    {
        self.as_mut_slice().as_parallel_slice_mut().par_iter_mut()
    }

    /// Returns an iterator over sub tensors `Tensor<&[Scalar]>`.
    ///
    /// # Note:
    /// The length of the sub-tensors must divide the size of the tensor.
    ///
    /// # Example:
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// for sub in tensor.subtensor_iter(10) {
    ///     assert_eq!(sub.len(), 10);
    /// }
    /// ```
    pub fn subtensor_iter(
        &self,
        size: usize,
    ) -> impl DoubleEndedIterator<Item = Tensor<&[<Self as AsRefSlice>::Element]>> + ExactSizeIterator
    where
        Self: AsRefSlice,
    {
        debug_assert!(self.as_slice().len() % size == 0, "Uneven chunks size");
        self.as_slice().chunks(size).map(Tensor::from_container)
    }

    /// Returns a parallel iterator over sub tensors `Tensor<&[Scalar]>`.
    ///
    /// # Note:
    /// The length of the sub-tensors must divide the size of the tensor.
    /// This iterator is hidden behind the "multithread" feature gate.
    ///
    /// # Example:
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// use rayon::iter::ParallelIterator;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// tensor.par_subtensor_iter(10).for_each(|sub| {
    ///     assert_eq!(sub.len(), 10);
    /// });
    /// ```
    #[cfg(feature = "multithread")]
    pub fn par_subtensor_iter(
        &self,
        size: usize,
    ) -> impl IndexedParallelIterator<Item = Tensor<&[<Self as AsRefSlice>::Element]>>
    where
        Self: AsRefSlice,
        <Self as AsRefSlice>::Element: Sync,
    {
        debug_assert!(self.as_slice().len() % size == 0, "Uneven chunks size");
        self.as_slice().par_chunks(size).map(Tensor::from_container)
    }

    /// Returns an iterator over mutable sub tensors `Tensor<&mut [Scalar]>`.
    ///
    /// # Note:
    /// The length of the sub-tensors must divide the size of the tensor.
    ///
    /// # Example:
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// for mut sub in tensor.subtensor_iter_mut(10) {
    ///     assert_eq!(sub.len(), 10);
    ///     *sub.get_element_mut(0) = 1;
    /// }
    /// for sub in tensor.subtensor_iter(20) {
    ///     assert_eq!(*sub.get_element(0), 1);
    ///     assert_eq!(*sub.get_element(10), 1);
    /// }
    /// ```
    pub fn subtensor_iter_mut(
        &mut self,
        size: usize,
    ) -> impl DoubleEndedIterator<Item = Tensor<&mut [<Self as AsMutSlice>::Element]>> + ExactSizeIterator
    where
        Self: AsMutSlice,
    {
        debug_assert!(self.as_slice().len() % size == 0, "Uneven chunks size");
        self.as_mut_slice()
            .chunks_mut(size)
            .map(Tensor::from_container)
    }

    /// Returns a parallel iterator over mutable sub tensors `Tensor<&mut [Scalar]>`.
    ///
    /// # Note:
    ///
    /// The length of the sub-tensors must divide the size of the tensor.
    /// This iterator is hidden behind the "multithread" feature gate.
    ///
    /// # Example:
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// use rayon::iter::ParallelIterator;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// tensor.par_subtensor_iter_mut(10).for_each(|mut sub| {
    ///     assert_eq!(sub.len(), 10);
    ///     *sub.get_element_mut(0) = 1;
    /// });
    /// for sub in tensor.subtensor_iter(20) {
    ///     assert_eq!(*sub.get_element(0), 1);
    ///     assert_eq!(*sub.get_element(10), 1);
    /// }
    /// ```
    #[cfg(feature = "multithread")]
    pub fn par_subtensor_iter_mut(
        &mut self,
        size: usize,
    ) -> impl IndexedParallelIterator<Item = Tensor<&mut [<Self as AsMutSlice>::Element]>>
    where
        Self: AsMutSlice,
        <Self as AsMutSlice>::Element: Sync + Send,
    {
        debug_assert!(self.as_slice().len() % size == 0, "Uneven chunks size");
        self.as_mut_slice()
            .par_chunks_mut(size)
            .map(Tensor::from_container)
    }

    /// Returns a reference to the first element.
    ///
    /// # Note:
    ///
    /// Panics if the tensor is empty.
    ///
    /// # Example:
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// assert_eq!(*tensor.first(), 9);
    /// ```
    pub fn first<Element>(&self) -> &Element
    where
        Self: AsRefSlice<Element = Element>,
    {
        self.as_slice().first().unwrap()
    }

    /// Returns a reference to the last element.
    ///
    /// # Note:
    ///
    /// Panics if the tensor is empty.
    ///
    /// # Example:
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// assert_eq!(*tensor.last(), 9);
    /// ```
    pub fn last<Element>(&self) -> &Element
    where
        Self: AsRefSlice<Element = Element>,
    {
        self.as_slice().last().unwrap()
    }

    /// Returns a mutable reference to the first element.
    ///
    /// # Note:
    ///
    /// Panics if the tensor is empty.
    ///
    /// # Example:
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// *tensor.first_mut() = 8;
    /// assert_eq!(*tensor.get_element(0), 8);
    /// assert_eq!(*tensor.get_element(1), 9);
    /// ```
    pub fn first_mut<Element>(&mut self) -> &mut Element
    where
        Self: AsMutSlice<Element = Element>,
    {
        self.as_mut_slice().first_mut().unwrap()
    }

    /// Returns a mutable reference to the last element.
    ///
    /// # Note:
    ///
    /// Panics if the tensor is empty.
    ///
    /// # Example:
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// *tensor.last_mut() = 8;
    /// assert_eq!(*tensor.get_element(999), 8);
    /// assert_eq!(*tensor.get_element(1), 9);
    /// ```
    pub fn last_mut<Element>(&mut self) -> &mut Element
    where
        Self: AsMutSlice<Element = Element>,
    {
        self.as_mut_slice().last_mut().unwrap()
    }

    /// Returns a reference to the first element, and a ref tensor for the rest of the values.
    ///
    /// # Note:
    ///
    /// Panics if the tensor is empty.
    ///
    /// # Example:
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let tensor = Tensor::allocate(9 as u8, 1000);
    /// let (first, end) = tensor.split_first();
    /// assert_eq!(*first, 9);
    /// assert_eq!(end.len(), 999);
    /// ```
    pub fn split_first<Element>(&self) -> (&Element, Tensor<&[Element]>)
    where
        Self: AsRefSlice<Element = Element>,
    {
        self.as_slice()
            .split_first()
            .map(|(f, r)| (f, Tensor(r)))
            .unwrap()
    }

    /// Returns a reference to the last element, and a ref tensor to the rest of the values.
    ///
    /// # Note:
    ///
    /// Panics if the tensor is empty.
    ///
    /// # Example:
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let tensor = Tensor::allocate(9 as u8, 1000);
    /// let (last, beginning) = tensor.split_last();
    /// assert_eq!(*last, 9);
    /// assert_eq!(beginning.len(), 999);
    /// ```
    pub fn split_last<Element>(&self) -> (&Element, Tensor<&[Element]>)
    where
        Self: AsRefSlice<Element = Element>,
    {
        self.as_slice()
            .split_last()
            .map(|(f, r)| (f, Tensor(r)))
            .unwrap()
    }

    /// Returns a mutable reference to the first element, and a mut tensor for the rest of the
    /// values.
    ///
    /// # Note:
    ///
    /// Panics if the tensor is empty.
    ///
    /// # Example:
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// let (mut first, mut end) = tensor.split_first_mut();
    /// *first = 8;
    /// *end.get_element_mut(0) = 7;
    /// assert_eq!(*tensor.get_element(0), 8);
    /// assert_eq!(*tensor.get_element(1), 7);
    /// assert_eq!(*tensor.get_element(2), 9);
    /// ```
    pub fn split_first_mut<Element>(&mut self) -> (&mut Element, Tensor<&mut [Element]>)
    where
        Self: AsMutSlice<Element = Element>,
    {
        self.as_mut_slice()
            .split_first_mut()
            .map(|(f, r)| (f, Tensor(r)))
            .unwrap()
    }

    /// Returns a mutable reference to the last element, and a mut tensor for the rest of the
    /// values.
    ///
    /// # Note:
    ///
    /// Panics if the tensor is empty.
    ///
    /// # Example:
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// let (mut last, mut beginning) = tensor.split_last_mut();
    /// *last = 8;
    /// *beginning.get_element_mut(0) = 7;
    /// assert_eq!(*tensor.get_element(0), 7);
    /// assert_eq!(*tensor.get_element(999), 8);
    /// assert_eq!(*tensor.get_element(2), 9);
    /// ```
    pub fn split_last_mut<Element>(&mut self) -> (&mut Element, Tensor<&mut [Element]>)
    where
        Self: AsMutSlice<Element = Element>,
    {
        self.as_mut_slice()
            .split_last_mut()
            .map(|(f, r)| (f, Tensor(r)))
            .unwrap()
    }

    /// Returns a sub tensor from a range of indices.
    ///
    /// # Note:
    ///
    /// Panics if the indices are out of range.
    ///
    /// # Example:
    ///
    /// ```rust
    /// use concrete_core::math::tensor::Tensor;
    /// let tensor = Tensor::allocate(9 as u8, 1000);
    /// let sub = tensor.get_sub(0..3);
    /// assert_eq!(sub.len(), 3);
    /// ```
    pub fn get_sub<Index>(&self, index: Index) -> Tensor<&[<Self as AsRefSlice>::Element]>
    where
        Self: AsRefSlice,
        Index:
            SliceIndex<[<Self as AsRefSlice>::Element], Output = [<Self as AsRefSlice>::Element]>,
    {
        Tensor(&self.as_slice()[index])
    }

    /// Returns a mutable sub tensor from a range of indices.
    ///
    /// # Note:
    ///
    /// Panics if the indices are out of range.
    ///
    /// # Example:
    ///
    /// ```rust
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// let mut sub = tensor.get_sub_mut(0..3);
    /// sub.fill_with_element(0);
    /// assert_eq!(*tensor.get_element(0), 0);
    /// assert_eq!(*tensor.get_element(3), 9);
    /// ```
    pub fn get_sub_mut<Index>(
        &mut self,
        index: Index,
    ) -> Tensor<&mut [<Self as AsMutSlice>::Element]>
    where
        Self: AsMutSlice,
        Index:
            SliceIndex<[<Self as AsMutSlice>::Element], Output = [<Self as AsMutSlice>::Element]>,
    {
        Tensor(&mut self.as_mut_slice()[index])
    }

    /// Returns a reference to an element from an index.
    ///
    /// # Note:
    ///
    /// Panics if the index is out of range.
    ///
    /// # Example:
    ///
    /// ```rust
    /// use concrete_core::math::tensor::Tensor;
    /// let tensor = Tensor::allocate(9 as u8, 1000);
    /// assert_eq!(*tensor.get_element(0), 9);
    /// ```
    pub fn get_element(&self, index: usize) -> &<Self as AsRefSlice>::Element
    where
        Self: AsRefSlice,
    {
        &self.as_slice()[index]
    }

    /// Returns a mutable reference to an element from an index.
    ///
    /// # Note:
    ///
    /// Panics if the index is out of range.
    ///
    /// # Example:
    ///
    /// ```rust
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// *tensor.get_element_mut(0) = 8;
    /// assert_eq!(*tensor.get_element(0), 8);
    /// assert_eq!(*tensor.get_element(1), 9);
    /// ```
    pub fn get_element_mut(&mut self, index: usize) -> &mut <Self as AsMutSlice>::Element
    where
        Self: AsMutSlice,
    {
        &mut self.as_mut_slice()[index]
    }

    /// Sets the value of an element at a given index.
    ///
    /// # Note:
    ///
    /// Panics if the index is out of range.
    ///
    /// # Example:
    ///
    /// ```rust
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// *tensor.get_element_mut(0) = 8;
    /// assert_eq!(*tensor.get_element(0), 8);
    /// assert_eq!(*tensor.get_element(1), 9);
    /// ```
    pub fn set_element(&mut self, index: usize, val: <Self as AsMutSlice>::Element)
    where
        Self: AsMutSlice,
    {
        self.as_mut_slice()[index] = val;
    }

    /// Fills a tensor with the values of another tensor, using memcpy.
    ///
    /// # Example
    ///
    /// ```rust
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor1 = Tensor::allocate(9 as u8, 1000);
    /// let tensor2 = Tensor::allocate(10 as u8, 1000);
    /// tensor1.fill_with_copy(&tensor2);
    /// assert_eq!(*tensor2.get_element(0), 10);
    /// ```
    pub fn fill_with_copy<InputCont, Element>(&mut self, other: &Tensor<InputCont>)
    where
        Self: AsMutSlice<Element = Element>,
        Tensor<InputCont>: AsRefSlice<Element = Element>,
        Element: Copy,
    {
        ck_dim_eq!(self.len() => other.len());
        self.as_mut_slice().copy_from_slice(other.as_slice());
    }

    /// Fills two tensors with the result of the operation on a single one.
    ///
    /// # Example:
    ///
    /// ```rust
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor1 = Tensor::allocate(9 as u8, 1000);
    /// let mut tensor2 = Tensor::allocate(9 as u8, 1000);
    /// let tensor3 = Tensor::allocate(10 as u8, 1000);
    /// Tensor::fill_two_with_one(&mut tensor1, &mut tensor2, &tensor3, |a| (*a, *a));
    /// assert_eq!(*tensor1.get_element(0), 10);
    /// assert_eq!(*tensor2.get_element(0), 10);
    /// ```
    pub fn fill_two_with_one<Cont1, Cont2>(
        first: &mut Self,
        second: &mut Tensor<Cont1>,
        one: &Tensor<Cont2>,
        ope: impl Fn(
            &<Tensor<Cont2> as AsRefSlice>::Element,
        ) -> (
            <Self as AsRefSlice>::Element,
            <Tensor<Cont1> as AsRefSlice>::Element,
        ),
    ) where
        Self: AsMutSlice,
        Tensor<Cont1>: AsMutSlice,
        Tensor<Cont2>: AsRefSlice,
    {
        ck_dim_eq!(first.len() => one.len());
        ck_dim_eq!(second.len() => one.len());
        for (first_i, (second_i, one_i)) in zip!(first.iter_mut(), second.iter_mut(), one.iter()) {
            let (f, s) = ope(one_i);
            *first_i = f;
            *second_i = s;
        }
    }

    /// Fills a mutable tensor with the result of an element-wise operation on two other tensors of
    /// the same size
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut t1 = Tensor::allocate(9 as u8, 1000);
    /// let t2 = Tensor::allocate(1 as u8, 1000);
    /// let t3 = Tensor::allocate(2 as u8, 1000);
    /// t1.fill_with_two(&t2, &t3, |t2, t3| t3 + t2);
    /// for scalar in t1.iter() {
    ///     assert_eq!(*scalar, 3);
    /// }
    /// ```
    pub fn fill_with_two<Cont1, Cont2>(
        &mut self,
        lhs: &Tensor<Cont1>,
        rhs: &Tensor<Cont2>,
        ope: impl Fn(
            &<Tensor<Cont1> as AsRefSlice>::Element,
            &<Tensor<Cont2> as AsRefSlice>::Element,
        ) -> <Self as AsMutSlice>::Element,
    ) where
        Tensor<Cont1>: AsRefSlice,
        Tensor<Cont2>: AsRefSlice,
        Self: AsMutSlice,
    {
        ck_dim_eq!(self.len() => lhs.len());
        ck_dim_eq!(self.len() => rhs.len());
        for (output_i, (lhs_i, rhs_i)) in zip!(
            self.iter_mut(),
            lhs.as_slice().iter(),
            rhs.as_slice().iter()
        ) {
            *output_i = ope(lhs_i, rhs_i);
        }
    }

    /// Fills a mutable tensor with the result of an element-wise operation on one other tensor of
    /// the same size
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut t1 = Tensor::allocate(9 as u8, 1000);
    /// let t2 = Tensor::allocate(2 as u8, 1000);
    /// t1.fill_with_one(&t2, |t2| t2.pow(2));
    /// for scalar in t1.iter() {
    ///     assert_eq!(*scalar, 4);
    /// }
    /// ```
    pub fn fill_with_one<Cont>(
        &mut self,
        other: &Tensor<Cont>,
        ope: impl Fn(&<Tensor<Cont> as AsRefSlice>::Element) -> <Self as AsMutSlice>::Element,
    ) where
        Tensor<Cont>: AsRefSlice,
        Self: AsMutSlice,
    {
        ck_dim_eq!(self.len() => other.len());
        for (output_i, other_i) in zip!(self.iter_mut(), other.as_slice().iter()) {
            *output_i = ope(other_i);
        }
    }

    /// Fills a mutable tensor with an element.
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// tensor.fill_with_element(8);
    /// for scalar in tensor.iter() {
    ///     assert_eq!(*scalar, 8);
    /// }
    /// ```
    pub fn fill_with_element(&mut self, element: <Self as AsMutSlice>::Element)
    where
        Self: AsMutSlice,
        <Self as AsMutSlice>::Element: Copy,
    {
        for output_i in self.iter_mut() {
            *output_i = element;
        }
    }

    /// Fills a mutable tensor by repeatedly calling a closure.
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// use std::cell::RefCell;
    /// let mut tensor = Tensor::allocate(9 as u16, 1000);
    /// let mut boxed = RefCell::from(0);
    /// tensor.fill_with(|| {
    ///     *boxed.borrow_mut() += 1;
    ///     *boxed.borrow()
    /// });
    /// assert_eq!(*tensor.get_element(0), 1);
    /// assert_eq!(*tensor.get_element(1), 2);
    /// assert_eq!(*tensor.get_element(2), 3);
    /// ```
    pub fn fill_with(&mut self, ope: impl Fn() -> <Self as AsMutSlice>::Element)
    where
        Self: AsMutSlice,
    {
        for output_i in self.iter_mut() {
            *output_i = ope();
        }
    }

    /// Fills a mutable tensor by casting elements of another one.
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut t1 = Tensor::allocate(9 as u16, 1000);
    /// let mut t2 = Tensor::allocate(8. as f32, 1000);
    /// t1.fill_with_cast(&t2);
    /// for scalar in t1.iter() {
    ///     assert_eq!(*scalar, 8);
    /// }
    /// ```
    pub fn fill_with_cast<Cont>(&mut self, other: &Tensor<Cont>)
    where
        Self: AsMutSlice,
        Tensor<Cont>: AsRefSlice,
        <Self as AsMutSlice>::Element: CastFrom<<Tensor<Cont> as AsRefSlice>::Element>,
        <Tensor<Cont> as AsRefSlice>::Element: Copy,
    {
        ck_dim_eq!(self.len() => other.len());
        self.fill_with_one(other, |a| <Self as AsMutSlice>::Element::cast_from(*a));
    }

    fill_with!(Add, fill_with_add, |l, r| *l + *r);
    fill_with!(Sub, fill_with_sub, |l, r| *l - *r);
    fill_with!(Mul, fill_with_mul, |l, r| *l * *r);
    fill_with!(Div, fill_with_div, |l, r| *l / *r);
    fill_with!(Rem, fill_with_rem, |l, r| *l % *r);
    fill_with!(BitAnd, fill_with_bit_and, |l, r| *l & *r);
    fill_with!(BitOr, fill_with_bit_or, |l, r| *l | *r);
    fill_with!(BitXor, fill_with_bit_xor, |l, r| *l ^ *r);
    fill_with!(Shl, fill_with_bit_shl, |l, r| *l << *r);
    fill_with!(Shr, fill_with_bit_shr, |l, r| *l >> *r);

    fill_with_wrapping!(fill_with_wrapping_add, |l, r| l.wrapping_add(*r));
    fill_with_wrapping!(fill_with_wrapping_sub, |l, r| l.wrapping_sub(*r));
    fill_with_wrapping!(fill_with_wrapping_mul, |l, r| l.wrapping_mul(*r));
    fill_with_wrapping!(fill_with_wrapping_div, |l, r| l.wrapping_div(*r));

    /// Updates two tensors with the result of the operation with a single one.
    ///
    /// # Example:
    ///
    /// ```rust
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor1 = Tensor::allocate(9 as u8, 1000);
    /// let mut tensor2 = Tensor::allocate(9 as u8, 1000);
    /// let tensor3 = Tensor::allocate(10 as u8, 1000);
    /// Tensor::update_two_with_one(&mut tensor1, &mut tensor2, &tensor3, |a, b, c| {
    ///     *a += *c;
    ///     *b += *c + 1;
    /// });
    /// assert_eq!(*tensor1.get_element(0), 19);
    /// assert_eq!(*tensor2.get_element(0), 20);
    /// ```
    pub fn update_two_with_one<Cont1, Cont2>(
        first: &mut Self,
        second: &mut Tensor<Cont1>,
        one: &Tensor<Cont2>,
        ope: impl Fn(
            &mut <Self as AsRefSlice>::Element,
            &mut <Tensor<Cont1> as AsRefSlice>::Element,
            &<Tensor<Cont2> as AsRefSlice>::Element,
        ),
    ) where
        Self: AsMutSlice,
        Tensor<Cont1>: AsMutSlice,
        Tensor<Cont2>: AsRefSlice,
    {
        ck_dim_eq!(first.len() => one.len());
        ck_dim_eq!(second.len() => one.len());
        for (first_i, (second_i, one_i)) in zip!(first.iter_mut(), second.iter_mut(), one.iter()) {
            ope(first_i, second_i, one_i);
        }
    }

    /// Updates a mutable tensor with the result of an element-wise operation with two other
    /// tensors of the same size.
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut t1 = Tensor::allocate(9 as u8, 1000);
    /// let t2 = Tensor::allocate(1 as u8, 1000);
    /// let t3 = Tensor::allocate(2 as u8, 1000);
    /// t1.update_with_two(&t2, &t3, |t1, t2, t3| *t1 += t3 + t2);
    /// for scalar in t1.iter() {
    ///     assert_eq!(*scalar, 12);
    /// }
    /// ```
    pub fn update_with_two<Cont1, Cont2>(
        &mut self,
        first: &Tensor<Cont1>,
        second: &Tensor<Cont2>,
        ope: impl Fn(
            &mut <Self as AsMutSlice>::Element,
            &<Tensor<Cont1> as AsRefSlice>::Element,
            &<Tensor<Cont2> as AsRefSlice>::Element,
        ),
    ) where
        Self: AsMutSlice,
        Tensor<Cont1>: AsRefSlice,
        Tensor<Cont2>: AsRefSlice,
    {
        ck_dim_eq!(self.len() => first.len());
        ck_dim_eq!(self.len() => second.len());
        for (self_i, (first_i, second_i)) in zip!(
            self.iter_mut(),
            first.as_slice().iter(),
            second.as_slice().iter()
        ) {
            ope(self_i, first_i, second_i);
        }
    }

    /// Updates a mutable tensor with the result of an element-wise operation with one other tensor
    /// of the same size
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut t1 = Tensor::allocate(9 as u8, 1000);
    /// let t2 = Tensor::allocate(2 as u8, 1000);
    /// t1.update_with_one(&t2, |t1, t2| *t1 += t2.pow(2));
    /// for scalar in t1.iter() {
    ///     assert_eq!(*scalar, 13);
    /// }
    /// ```
    pub fn update_with_one<Cont>(
        &mut self,
        other: &Tensor<Cont>,
        ope: impl Fn(&mut <Self as AsMutSlice>::Element, &<Tensor<Cont> as AsRefSlice>::Element),
    ) where
        Self: AsMutSlice,
        Tensor<Cont>: AsRefSlice,
    {
        ck_dim_eq!(self.len() => other.len());
        for (self_i, other_i) in zip!(self.iter_mut(), other.as_slice().iter()) {
            ope(self_i, other_i);
        }
    }

    /// Updates a mutable tensor with an element.
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// tensor.update_with_element(8, |t, s| *t += s);
    /// for scalar in tensor.iter() {
    ///     assert_eq!(*scalar, 17);
    /// }
    /// ```
    pub fn update_with_element<Element>(
        &mut self,
        scalar: Element,
        ope: impl Fn(&mut <Self as AsMutSlice>::Element, Element),
    ) where
        Self: AsMutSlice,
        Element: Copy,
    {
        for self_i in self.iter_mut() {
            ope(self_i, scalar);
        }
    }

    /// Updates a mutable tensor by repeatedly calling a closure.
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// use std::cell::RefCell;
    /// let mut tensor = Tensor::allocate(9 as u16, 1000);
    /// let mut boxed = RefCell::from(0);
    /// tensor.update_with(|t| {
    ///     *boxed.borrow_mut() += 1;
    ///     *t += *boxed.borrow()
    /// });
    /// assert_eq!(*tensor.get_element(0), 10);
    /// assert_eq!(*tensor.get_element(1), 11);
    /// assert_eq!(*tensor.get_element(2), 12);
    /// ```
    pub fn update_with(&mut self, ope: impl Fn(&mut <Self as AsMutSlice>::Element))
    where
        Self: AsMutSlice,
    {
        for self_i in self.iter_mut() {
            ope(self_i);
        }
    }

    update_with!(AddAssign, update_with_add, |s, a| *s += *a);
    update_with!(SubAssign, update_with_sub, |s, a| *s -= *a);
    update_with!(MulAssign, update_with_mul, |s, a| *s *= *a);
    update_with!(DivAssign, update_with_div, |s, a| *s /= *a);
    update_with!(RemAssign, update_with_rem, |s, a| *s %= *a);
    update_with!(BitAndAssign, update_with_and, |s, a| *s &= *a);
    update_with!(BitOrAssign, update_with_or, |s, a| *s |= *a);
    update_with!(BitXorAssign, update_with_xor, |s, a| *s ^= *a);
    update_with!(ShlAssign, update_with_shl, |s, a| *s <<= *a);
    update_with!(ShrAssign, update_with_shr, |s, a| *s >>= *a);

    update_with_wrapping!(update_with_wrapping_add, |s, a| *s = s.wrapping_add(*a));
    update_with_wrapping!(update_with_wrapping_sub, |s, a| *s = s.wrapping_sub(*a));
    update_with_wrapping!(update_with_wrapping_mul, |s, a| *s = s.wrapping_mul(*a));
    update_with_wrapping!(update_with_wrapping_div, |s, a| *s = s.wrapping_div(*a));

    update_with_scalar!(AddAssign, update_with_scalar_add, |s, a| *s += *a);
    update_with_scalar!(SubAssign, update_with_scalar_sub, |s, a| *s -= *a);
    update_with_scalar!(MulAssign, update_with_scalar_mul, |s, a| *s *= *a);
    update_with_scalar!(DivAssign, update_with_scalar_div, |s, a| *s /= *a);
    update_with_scalar!(RemAssign, update_with_scalar_rem, |s, a| *s %= *a);
    update_with_scalar!(BitAndAssign, update_with_scalar_and, |s, a| *s &= *a);
    update_with_scalar!(BitOrAssign, update_with_scalar_or, |s, a| *s |= *a);
    update_with_scalar!(BitXorAssign, update_with_scalar_xor, |s, a| *s ^= *a);
    update_with_scalar!(ShlAssign, update_with_scalar_shl, |s, a| *s <<= *a);
    update_with_scalar!(ShrAssign, update_with_scalar_shr, |s, a| *s >>= *a);

    update_with_wrapping_scalar!(update_with_wrapping_scalar_add, |s, a| *s =
        s.wrapping_add(*a));
    update_with_wrapping_scalar!(update_with_wrapping_scalar_sub, |s, a| *s =
        s.wrapping_sub(*a));
    update_with_wrapping_scalar!(update_with_wrapping_scalar_mul, |s, a| *s =
        s.wrapping_mul(*a));
    update_with_wrapping_scalar!(update_with_wrapping_scalar_div, |s, a| *s =
        s.wrapping_div(*a));

    /// Sets each value of `self` to its own opposite.
    ///
    /// # Example
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as i16, 1000);
    /// tensor.update_with_neg();
    /// for scalar in tensor.iter() {
    ///     assert_eq!(*scalar, -9);
    /// }
    /// ```
    pub fn update_with_neg(&mut self)
    where
        Self: AsMutSlice,
        <Self as AsMutSlice>::Element: Neg<Output = <Self as AsMutSlice>::Element> + Copy,
    {
        self.update_with(|a| *a = -*a);
    }

    /// Sets each value of `self` to its own wrapping opposite.
    ///
    /// # Example
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::allocate(9 as u8, 1000);
    /// tensor.update_with_wrapping_neg();
    /// for scalar in tensor.iter() {
    ///     assert_eq!(*scalar, 247);
    /// }
    /// ```
    pub fn update_with_wrapping_neg(&mut self)
    where
        Self: AsMutSlice,
        <Self as AsMutSlice>::Element: UnsignedInteger,
    {
        self.update_with(|a| *a = a.wrapping_neg());
    }

    /// Fills a mutable tensor with the result of the multiplication of elements of another tensor
    /// by an element.
    ///
    /// # Example
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut t1 = Tensor::allocate(9 as u8, 1000);
    /// let t2 = Tensor::allocate(3 as u8, 1000);
    /// t1.fill_with_element_mul(&t2, 2);
    /// for scalar in t1.iter() {
    ///     assert_eq!(*scalar, 6);
    /// }
    /// ```
    pub fn fill_with_element_mul<Cont, Element>(&mut self, tensor: &Tensor<Cont>, element: Element)
    where
        Self: AsMutSlice,
        Tensor<Cont>: AsRefSlice,
        <Tensor<Cont> as AsRefSlice>::Element: Mul<Element, Output = <Self as AsMutSlice>::Element>,
        Element: Copy,
        <Tensor<Cont> as AsRefSlice>::Element: Copy,
    {
        ck_dim_eq!(self.len() => tensor.len());
        self.fill_with_one(tensor, |t| *t * element);
    }

    /// Fills a mutable tensor with the result of the wrapping multiplication of elements of
    /// another tensor by an element.
    ///
    /// # Example
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut t1 = Tensor::allocate(9 as u8, 1000);
    /// let t2 = Tensor::allocate(3 as u8, 1000);
    /// t1.fill_with_wrapping_element_mul(&t2, 250);
    /// for scalar in t1.iter() {
    ///     assert_eq!(*scalar, 238);
    /// }
    /// ```
    pub fn fill_with_wrapping_element_mul<Cont, Element>(
        &mut self,
        tensor: &Tensor<Cont>,
        element: Element,
    ) where
        Self: AsMutSlice<Element = Element>,
        Tensor<Cont>: AsRefSlice<Element = Element>,
        Element: UnsignedInteger,
    {
        ck_dim_eq!(self.len() => tensor.len());
        self.fill_with_one(tensor, |t| t.wrapping_mul(element));
    }

    /// Updates the values of a mutable tensor by subtracting the product of the element of
    /// another tensor and an element.
    ///
    /// # Example
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut t1 = Tensor::allocate(9 as u8, 1000);
    /// let t2 = Tensor::allocate(2 as u8, 1000);
    /// t1.update_with_sub_element_mul(&t2, 4);
    /// for scalar in t1.iter() {
    ///     assert_eq!(*scalar, 1);
    /// }
    /// ```
    pub fn update_with_sub_element_mul<Cont, Element>(
        &mut self,
        tensor: &Tensor<Cont>,
        scalar: Element,
    ) where
        Self: AsMutSlice,
        Tensor<Cont>: AsRefSlice,
        <Tensor<Cont> as AsRefSlice>::Element: Copy,
        Element: Copy,
        <Tensor<Cont> as AsRefSlice>::Element: Mul<Element, Output = <Self as AsMutSlice>::Element>,
        <Self as AsMutSlice>::Element: SubAssign<<Self as AsMutSlice>::Element>,
    {
        ck_dim_eq!(self.len() => tensor.len());
        self.update_with_one(tensor, |s, t| *s -= *t * scalar);
    }

    /// Updates the values of a mutable tensor by wrap-subtracting the wrapping product of the
    /// elements of another tensor and an element.
    ///
    /// # Example
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut t1 = Tensor::allocate(9 as u8, 1000);
    /// let t2 = Tensor::allocate(2 as u8, 1000);
    /// t1.update_with_wrapping_sub_element_mul(&t2, 250);
    /// for scalar in t1.iter() {
    ///     assert_eq!(*scalar, 21);
    /// }
    /// ```
    pub fn update_with_wrapping_sub_element_mul<Cont, Element>(
        &mut self,
        tensor: &Tensor<Cont>,
        scalar: Element,
    ) where
        Self: AsMutSlice<Element = Element>,
        Tensor<Cont>: AsRefSlice<Element = Element>,
        Element: UnsignedInteger,
    {
        ck_dim_eq!(self.len() => tensor.len());
        self.update_with_one(tensor, |s, t| *s = s.wrapping_sub(t.wrapping_mul(scalar)));
    }

    /// Updates the values of a mutable tensor by adding the product of the element of another
    /// tensor and an element.
    ///
    /// # Example
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut t1 = Tensor::allocate(9 as u8, 1000);
    /// let t2 = Tensor::allocate(2 as u8, 1000);
    /// t1.update_with_add_element_mul(&t2, 4);
    /// for scalar in t1.iter() {
    ///     assert_eq!(*scalar, 17);
    /// }
    /// ```
    pub fn update_with_add_element_mul<Cont, Element>(
        &mut self,
        tensor: &Tensor<Cont>,
        scalar: Element,
    ) where
        Self: AsMutSlice,
        Tensor<Cont>: AsRefSlice,
        <Tensor<Cont> as AsRefSlice>::Element: Copy,
        Element: Copy,
        <Tensor<Cont> as AsRefSlice>::Element: Mul<Element, Output = <Self as AsMutSlice>::Element>,
        <Self as AsMutSlice>::Element: AddAssign<<Self as AsMutSlice>::Element>,
    {
        ck_dim_eq!(self.len() => tensor.len());
        self.update_with_one(tensor, |s, t| *s += *t * scalar);
    }

    /// Updates the values of a mutable tensor by wrap-adding the wrapping product of the elements
    /// of another tensor and an element.
    ///
    /// # Example
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut t1 = Tensor::allocate(9 as u8, 1000);
    /// let t2 = Tensor::allocate(2 as u8, 1000);
    /// t1.update_with_wrapping_add_element_mul(&t2, 250);
    /// for scalar in t1.iter() {
    ///     assert_eq!(*scalar, 253);
    /// }
    /// ```
    pub fn update_with_wrapping_add_element_mul<Cont, Element>(
        &mut self,
        tensor: &Tensor<Cont>,
        element: Element,
    ) where
        Self: AsMutSlice<Element = Element>,
        Tensor<Cont>: AsRefSlice<Element = Element>,
        Element: UnsignedInteger,
    {
        ck_dim_eq!(self.len() => tensor.len());
        self.update_with_one(tensor, |s, t| *s = s.wrapping_add(t.wrapping_mul(element)));
    }

    /// Computes a value by folding a tensor with another.
    ///
    /// # Example
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let t1 = Tensor::allocate(10 as u16, 10);
    /// let t2 = Tensor::allocate(2 as u16, 10);
    /// let val = t1.fold_with_one(&t2, 0, |mut a, t1, t2| {
    ///     a += t1 + t2;
    ///     a
    /// });
    /// assert_eq!(val, 120);
    /// ```
    pub fn fold_with_one<Cont, Output>(
        &self,
        other: &Tensor<Cont>,
        acc: Output,
        ope: impl Fn(
            Output,
            &<Self as AsRefSlice>::Element,
            &<Tensor<Cont> as AsRefSlice>::Element,
        ) -> Output,
    ) -> Output
    where
        Self: AsRefSlice,
        Tensor<Cont>: AsRefSlice,
    {
        ck_dim_eq!(self.len() => other.len());
        self.iter()
            .zip(other.as_slice().iter())
            .fold(acc, |acc, (s_i, o_i)| ope(acc, s_i, o_i))
    }

    /// Reverses the elements of the tensor inplace.
    ///
    /// # Example
    ///  
    /// ```rust
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::from_container(vec![1u8, 2, 3, 4]);
    /// tensor.reverse();
    /// assert_eq!(*tensor.get_element(0), 4);
    /// ```
    pub fn reverse(&mut self)
    where
        Self: AsMutSlice,
    {
        self.as_mut_slice().reverse()
    }

    /// Rotates the elements of the tensor to the right, inplace.
    ///
    /// # Example
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::from_container(vec![1u8, 2, 3, 4]);
    /// tensor.rotate_right(2);
    /// assert_eq!(*tensor.get_element(0), 3);
    /// ```
    pub fn rotate_right(&mut self, n: usize)
    where
        Self: AsMutSlice,
    {
        self.as_mut_slice().rotate_right(n)
    }

    /// Rotates the elements of the tensor to the left, inplace.
    ///
    /// # Example
    ///
    /// ```
    /// use concrete_core::math::tensor::Tensor;
    /// let mut tensor = Tensor::from_container(vec![1u8, 2, 3, 4]);
    /// tensor.rotate_left(2);
    /// assert_eq!(*tensor.get_element(0), 3);
    /// ```
    pub fn rotate_left(&mut self, n: usize)
    where
        Self: AsMutSlice,
    {
        self.as_mut_slice().rotate_left(n)
    }
}

impl<Element> FromIterator<Element> for Tensor<Vec<Element>> {
    fn from_iter<I: IntoIterator<Item = Element>>(iter: I) -> Self {
        let mut v = Vec::new();
        for i in iter {
            v.push(i);
        }
        Tensor(v)
    }
}

impl<Cont> AsRefSlice for Tensor<Cont>
where
    Cont: AsRefSlice,
{
    type Element = Cont::Element;
    fn as_slice(&self) -> &[Self::Element] {
        self.0.as_slice()
    }
}

impl<Cont> AsMutSlice for Tensor<Cont>
where
    Cont: AsMutSlice,
{
    type Element = <Cont as AsMutSlice>::Element;
    fn as_mut_slice(&mut self) -> &mut [<Self as AsMutSlice>::Element] {
        self.0.as_mut_slice()
    }
}

impl<Cont> AsRefTensor for Tensor<Cont>
where
    Cont: AsRefSlice,
{
    type Element = Cont::Element;
    type Container = Cont;
    fn as_tensor(&self) -> &Tensor<Cont> {
        self
    }
}

impl<Cont> AsMutTensor for Tensor<Cont>
where
    Cont: AsMutSlice,
{
    type Element = <Cont as AsMutSlice>::Element;
    type Container = Cont;
    fn as_mut_tensor(&mut self) -> &mut Tensor<Cont> {
        self
    }
}