tfhe 1.6.1

TFHE-rs is a fully homomorphic encryption (FHE) library that implements Zama's variant of TFHE.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
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
mod add;
mod bitwise_op;
mod comparison;
mod mul;
pub(crate) mod neg;
mod scalar_add;
pub(super) mod scalar_mul;
pub(super) mod scalar_sub;
mod shift;
pub(super) mod slice;
mod sub;

use super::ServerKey;
use crate::integer::block_decomposition::DecomposableInto;
use crate::integer::ciphertext::{IntegerCiphertext, IntegerRadixCiphertext, RadixCiphertext};
use crate::integer::encryption::encrypt_words_radix_impl;
use crate::integer::{BooleanBlock, SignedRadixCiphertext};

mod even_odd;
#[cfg(test)]
mod tests;

impl ServerKey {
    pub fn create_trivial_zero_assign_radix<T>(&self, ctxt: &mut T)
    where
        T: IntegerRadixCiphertext,
    {
        for block in ctxt.blocks_mut() {
            self.key.create_trivial_assign(block, 0);
        }
    }

    /// Create a ciphertext filled with zeros
    ///
    /// # Example
    ///
    /// ```rust
    /// use tfhe::integer::{gen_keys_radix, RadixCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let ctxt: RadixCiphertext = sks.create_trivial_zero_radix(num_blocks);
    ///
    /// // Decrypt:
    /// let dec: u64 = cks.decrypt(&ctxt);
    /// assert_eq!(0, dec);
    /// ```
    pub fn create_trivial_zero_radix<T>(&self, num_blocks: usize) -> T
    where
        T: IntegerRadixCiphertext,
    {
        let mut vec_res = Vec::with_capacity(num_blocks);
        for _ in 0..num_blocks {
            vec_res.push(self.key.create_trivial(0_u64));
        }

        T::from_blocks(vec_res)
    }

    pub fn create_trivial_boolean_block(&self, value: bool) -> BooleanBlock {
        BooleanBlock::new_unchecked(self.key.create_trivial(u64::from(value)))
    }

    pub fn create_trivial_max_radix<T>(&self, num_blocks: usize) -> T
    where
        T: IntegerRadixCiphertext,
    {
        let block_with_all_ones = self.key.create_trivial(self.key.message_modulus.0 - 1);
        if T::IS_SIGNED {
            // The max of a two's complement number is a 0 in msb and then only 1
            let mut trivial_blocks = vec![block_with_all_ones; num_blocks - 1];
            // msb blocks has its last bit set to 0, the rest are 1
            trivial_blocks.push(self.key.create_trivial((self.message_modulus().0 >> 1) - 1));
            T::from_blocks(trivial_blocks)
        } else {
            // Max value is simply all bits set to one
            T::from_blocks(vec![block_with_all_ones; num_blocks])
        }
    }

    pub fn create_trivial_min_radix<T>(&self, num_blocks: usize) -> T
    where
        T: IntegerRadixCiphertext,
    {
        if T::IS_SIGNED {
            // create num_blocks -1 blocks containing 0
            let mut trivial_blocks = vec![self.key.create_trivial(0); num_blocks - 1];
            // msb block has its msb set to 1, rest is 0
            let num_bits_of_message = self.message_modulus().0.ilog2();
            trivial_blocks.push(
                self.key
                    .create_trivial((self.message_modulus().0 - 1) << (num_bits_of_message - 1)),
            );
            T::from_blocks(trivial_blocks)
        } else {
            // Min value is simply 0
            self.create_trivial_zero_radix(num_blocks)
        }
    }

    /// Create a trivial radix ciphertext
    ///
    /// Trivial means that the value is not encrypted
    ///
    /// # Example
    ///
    /// ```rust
    /// use tfhe::integer::{gen_keys_radix, RadixCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let ctxt: RadixCiphertext = sks.create_trivial_radix(212u64, num_blocks);
    ///
    /// // Decrypt:
    /// let dec: u64 = cks.decrypt(&ctxt);
    /// assert_eq!(212, dec);
    /// ```
    pub fn create_trivial_radix<T, C>(&self, value: T, num_blocks: usize) -> C
    where
        T: DecomposableInto<u64>,
        C: IntegerRadixCiphertext + From<Vec<crate::shortint::Ciphertext>>,
    {
        encrypt_words_radix_impl(
            &self.key,
            value,
            num_blocks,
            crate::shortint::ServerKey::create_trivial,
        )
    }

    /// Prepend trivial zero LSB blocks to an existing [`RadixCiphertext`]. This can be useful for
    /// casting operations.
    ///
    /// # Example
    ///
    ///```rust
    /// use tfhe::integer::{gen_keys_radix, IntegerCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let msg = 7u64;
    ///
    /// let mut ct1 = cks.encrypt(msg);
    /// assert_eq!(ct1.blocks().len(), 4);
    ///
    /// let added_blocks = 2;
    /// sks.extend_radix_with_trivial_zero_blocks_lsb_assign(&mut ct1, added_blocks);
    /// assert_eq!(ct1.blocks().len(), 6);
    ///
    /// // Decrypt
    /// let res: u64 = cks.decrypt(&ct1);
    /// assert_eq!(
    ///     7 * (PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128
    ///         .message_modulus
    ///         .0)
    ///         .pow(added_blocks as u32),
    ///     res
    /// );
    /// ```
    pub fn extend_radix_with_trivial_zero_blocks_lsb_assign(
        &self,
        ct: &mut RadixCiphertext,
        num_blocks: usize,
    ) {
        self.extend_radix_with_trivial_zero_blocks_msb_assign(ct, num_blocks);
        ct.blocks.rotate_right(num_blocks);
    }

    /// Prepend trivial zero LSB blocks to an existing [`RadixCiphertext`] and returns the result as
    /// a new [`RadixCiphertext`]. This can be useful for casting operations.
    ///
    /// # Example
    ///
    ///```rust
    /// use tfhe::integer::{gen_keys_radix, IntegerCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let msg = 7u64;
    ///
    /// let ct1 = cks.encrypt(msg);
    /// assert_eq!(ct1.blocks().len(), 4);
    ///
    /// let added_blocks = 2;
    /// let ct_res = sks.extend_radix_with_trivial_zero_blocks_lsb(&ct1, added_blocks);
    /// assert_eq!(ct_res.blocks().len(), 6);
    ///
    /// // Decrypt
    /// let res: u64 = cks.decrypt(&ct_res);
    /// assert_eq!(
    ///     7 * (PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128
    ///         .message_modulus
    ///         .0)
    ///         .pow(added_blocks as u32),
    ///     res
    /// );
    /// ```
    pub fn extend_radix_with_trivial_zero_blocks_lsb(
        &self,
        ct: &RadixCiphertext,
        num_blocks: usize,
    ) -> RadixCiphertext {
        let mut ct_res = ct.clone();
        self.extend_radix_with_trivial_zero_blocks_lsb_assign(&mut ct_res, num_blocks);
        ct_res
    }

    /// Append trivial zero MSB blocks to an existing [`RadixCiphertext`]. This can be useful for
    /// casting operations.
    ///
    /// # Example
    ///
    ///```rust
    /// use tfhe::integer::{gen_keys_radix, IntegerCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let msg = 7u64;
    ///
    /// let mut ct1 = cks.encrypt(msg);
    /// assert_eq!(ct1.blocks().len(), 4);
    ///
    /// sks.extend_radix_with_trivial_zero_blocks_msb_assign(&mut ct1, 2);
    /// assert_eq!(ct1.blocks().len(), 6);
    ///
    /// // Decrypt
    /// let res: u64 = cks.decrypt(&ct1);
    /// assert_eq!(7, res);
    /// ```
    pub fn extend_radix_with_trivial_zero_blocks_msb_assign(
        &self,
        ct: &mut RadixCiphertext,
        num_blocks: usize,
    ) {
        let block_trivial_zero = self.key.create_trivial(0);
        ct.blocks
            .resize(ct.blocks.len() + num_blocks, block_trivial_zero);
    }

    /// Append trivial zero MSB blocks to an existing [`RadixCiphertext`] and returns the result as
    /// a new [`RadixCiphertext`]. This can be useful for casting operations.
    ///
    /// # Example
    ///
    ///```rust
    /// use tfhe::integer::{gen_keys_radix, IntegerCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let msg = 7u64;
    ///
    /// let ct1 = cks.encrypt(msg);
    /// assert_eq!(ct1.blocks().len(), 4);
    ///
    /// let ct_res = sks.extend_radix_with_trivial_zero_blocks_msb(&ct1, 2);
    /// assert_eq!(ct_res.blocks().len(), 6);
    ///
    /// // Decrypt
    /// let res: u64 = cks.decrypt(&ct_res);
    /// assert_eq!(7, res);
    /// ```
    pub fn extend_radix_with_trivial_zero_blocks_msb(
        &self,
        ct: &RadixCiphertext,
        num_blocks: usize,
    ) -> RadixCiphertext {
        let mut ct_res = ct.clone();
        self.extend_radix_with_trivial_zero_blocks_msb_assign(&mut ct_res, num_blocks);
        ct_res
    }

    /// Remove LSB blocks from an existing [`RadixCiphertext`]. This can be useful for casting
    /// operations.
    ///
    /// # Example
    ///
    ///```rust
    /// use tfhe::integer::{gen_keys_radix, IntegerCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let msg = 119u64;
    ///
    /// let mut ct1 = cks.encrypt(msg);
    /// assert_eq!(ct1.blocks().len(), 4);
    ///
    /// sks.trim_radix_blocks_lsb_assign(&mut ct1, 2);
    /// assert_eq!(ct1.blocks().len(), 2);
    ///
    /// // Decrypt
    /// let res: u64 = cks.decrypt(&ct1);
    /// assert_eq!(7, res);
    /// ```
    pub fn trim_radix_blocks_lsb_assign(&self, ct: &mut RadixCiphertext, num_blocks: usize) {
        ct.blocks.rotate_left(num_blocks);
        self.trim_radix_blocks_msb_assign(ct, num_blocks);
    }

    /// Remove LSB blocks from an existing [`RadixCiphertext`] and returns the result as a new
    /// [`RadixCiphertext`]. This can be useful for casting operations.
    ///
    /// # Example
    ///
    ///```rust
    /// use tfhe::integer::{gen_keys_radix, IntegerCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let msg = 119u64;
    ///
    /// let ct1 = cks.encrypt(msg);
    /// assert_eq!(ct1.blocks().len(), 4);
    ///
    /// let ct_res = sks.trim_radix_blocks_lsb(&ct1, 2);
    /// assert_eq!(ct_res.blocks().len(), 2);
    ///
    /// // Decrypt
    /// let res: u64 = cks.decrypt(&ct_res);
    /// assert_eq!(7, res);
    /// ```
    pub fn trim_radix_blocks_lsb(
        &self,
        ct: &RadixCiphertext,
        num_blocks: usize,
    ) -> RadixCiphertext {
        let mut ct_res = ct.clone();
        self.trim_radix_blocks_lsb_assign(&mut ct_res, num_blocks);
        ct_res
    }

    /// Remove MSB blocks from an existing [`RadixCiphertext`]. This can be useful for
    /// casting operations.
    ///
    /// # Example
    ///
    ///```rust
    /// use tfhe::integer::{gen_keys_radix, IntegerCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let msg = 119u64;
    ///
    /// let mut ct1 = cks.encrypt(msg);
    /// assert_eq!(ct1.blocks().len(), 4);
    ///
    /// sks.trim_radix_blocks_msb_assign(&mut ct1, 2);
    /// assert_eq!(ct1.blocks().len(), 2);
    ///
    /// // Decrypt
    /// let res: u64 = cks.decrypt(&ct1);
    /// assert_eq!(7, res);
    /// ```
    pub fn trim_radix_blocks_msb_assign(&self, ct: &mut RadixCiphertext, num_blocks: usize) {
        let len = ct.blocks.len();
        ct.blocks.truncate(len - num_blocks);
        if !ct.block_carries_are_empty() {
            self.full_propagate_parallelized(ct);
        }
    }

    /// Remove MSB blocks from an existing [`RadixCiphertext`] and returns the result as a new
    /// [`RadixCiphertext`]. This can be useful for casting operations.
    ///
    /// # Example
    ///
    ///```rust
    /// use tfhe::integer::{gen_keys_radix, IntegerCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let msg = 119u64;
    ///
    /// let ct1 = cks.encrypt(msg);
    /// assert_eq!(ct1.blocks().len(), 4);
    ///
    /// let ct_res = sks.trim_radix_blocks_msb(&ct1, 2);
    /// assert_eq!(ct_res.blocks().len(), 2);
    ///
    /// // Decrypt
    /// let res: u64 = cks.decrypt(&ct_res);
    /// assert_eq!(7, res);
    /// ```
    pub fn trim_radix_blocks_msb(
        &self,
        ct: &RadixCiphertext,
        num_blocks: usize,
    ) -> RadixCiphertext {
        let mut ct_res = ct.clone();
        self.trim_radix_blocks_msb_assign(&mut ct_res, num_blocks);
        ct_res
    }

    /// Extends the most significant blocks using the sign bit.
    /// Used to cast [SignedRadixCiphertext]
    ///
    /// # Example
    ///
    ///```rust
    /// use tfhe::integer::{gen_keys_radix, IntegerCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let msg = -1i8;
    ///
    /// let mut ct1 = cks.encrypt_signed(msg);
    /// assert_eq!(ct1.blocks().len(), 4);
    ///
    /// sks.extend_radix_with_sign_msb_assign(&mut ct1, 4);
    /// assert_eq!(ct1.blocks().len(), 8);
    ///
    /// // Decrypt
    /// let res: i16 = cks.decrypt_signed(&ct1);
    /// assert_eq!(-1, res);
    /// ```
    pub fn extend_radix_with_sign_msb_assign(
        &self,
        ct: &mut SignedRadixCiphertext,
        num_blocks: usize,
    ) {
        if !ct.block_carries_are_empty() {
            self.full_propagate_parallelized(ct)
        }
        let message_modulus = self.key.message_modulus.0;
        let num_bits_in_block = message_modulus.ilog2();
        let padding_block_creator_lut = self.key.generate_lookup_table(|x| {
            let x = x % message_modulus;
            let x_sign_bit = (x >> (num_bits_in_block - 1)) & 1;
            // padding is a message full of 1 if sign bit is one
            // else padding is a zero message
            (message_modulus - 1) * x_sign_bit
        });
        let last_block = ct
            .blocks
            .last()
            .expect("Cannot sign extend an empty ciphertext");
        let padding_block = self
            .key
            .apply_lookup_table(last_block, &padding_block_creator_lut);

        let new_len = num_blocks + ct.blocks.len();
        ct.blocks.resize(new_len, padding_block);
    }

    /// Extends the most significant blocks using the sign bit.
    /// Used to cast [SignedRadixCiphertext]
    ///
    /// # Example
    ///
    ///```rust
    /// use tfhe::integer::{gen_keys_radix, IntegerCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let msg = -2i8;
    ///
    /// let ct1 = cks.encrypt_signed(msg);
    /// assert_eq!(ct1.blocks().len(), 4);
    ///
    /// let ct_res = sks.extend_radix_with_sign_msb(&ct1, 4);
    /// assert_eq!(ct_res.blocks().len(), 8);
    ///
    /// // Decrypt
    /// let res: i16 = cks.decrypt_signed(&ct_res);
    /// assert_eq!(-2, res);
    /// ```
    pub fn extend_radix_with_sign_msb(
        &self,
        ct: &SignedRadixCiphertext,
        num_blocks: usize,
    ) -> SignedRadixCiphertext {
        let mut result = ct.clone();
        self.extend_radix_with_sign_msb_assign(&mut result, num_blocks);
        result
    }

    /// Cast a RadixCiphertext or SignedRadixCiphertext to a RadixCiphertext
    /// with a possibly different number of blocks
    ///
    /// # Example
    ///
    ///```rust
    /// use tfhe::integer::{gen_keys_radix, IntegerCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let msg = -2i8;
    ///
    /// let ct1 = cks.encrypt_signed(msg);
    /// assert_eq!(ct1.blocks().len(), 4);
    ///
    /// let ct_res = sks.cast_to_unsigned(ct1, 8);
    /// assert_eq!(ct_res.blocks().len(), 8);
    ///
    /// // Decrypt
    /// let res: u16 = cks.decrypt(&ct_res);
    /// assert_eq!(msg as u16, res);
    /// ```
    pub fn cast_to_unsigned<T: IntegerRadixCiphertext>(
        &self,
        mut source: T,
        target_num_blocks: usize,
    ) -> RadixCiphertext {
        if !source.block_carries_are_empty() {
            self.full_propagate_parallelized(&mut source);
        }

        let blocks = source.into_blocks();
        let current_num_blocks = blocks.len();

        let blocks = if T::IS_SIGNED {
            // Casting from signed to unsigned
            // We have to trim or sign extend first
            if target_num_blocks > current_num_blocks {
                let mut ct_as_signed_radix = SignedRadixCiphertext::from_blocks(blocks);
                let num_blocks_to_add = target_num_blocks - current_num_blocks;
                self.extend_radix_with_sign_msb_assign(&mut ct_as_signed_radix, num_blocks_to_add);
                ct_as_signed_radix.blocks
            } else {
                let mut ct_as_unsigned_radix = crate::integer::RadixCiphertext::from_blocks(blocks);
                let num_blocks_to_remove = current_num_blocks - target_num_blocks;
                self.trim_radix_blocks_msb_assign(&mut ct_as_unsigned_radix, num_blocks_to_remove);
                ct_as_unsigned_radix.blocks
            }
        } else {
            // Casting from unsigned to unsigned, this is just about trimming/extending with zeros
            let mut ct_as_unsigned_radix = crate::integer::RadixCiphertext::from_blocks(blocks);
            if target_num_blocks > current_num_blocks {
                let num_blocks_to_add = target_num_blocks - current_num_blocks;
                self.extend_radix_with_trivial_zero_blocks_msb_assign(
                    &mut ct_as_unsigned_radix,
                    num_blocks_to_add,
                );
            } else {
                let num_blocks_to_remove = current_num_blocks - target_num_blocks;
                self.trim_radix_blocks_msb_assign(&mut ct_as_unsigned_radix, num_blocks_to_remove);
            }
            ct_as_unsigned_radix.blocks
        };

        assert_eq!(
            blocks.len(),
            target_num_blocks,
            "internal error, wrong number of blocks after casting"
        );
        crate::integer::RadixCiphertext::from(blocks)
    }

    /// Cast a RadixCiphertext or SignedRadixCiphertext to a SignedRadixCiphertext
    /// with a possibly different number of blocks
    ///
    /// # Example
    ///
    ///```rust
    /// use tfhe::integer::{gen_keys_radix, IntegerCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 8;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let msg = u16::MAX;
    ///
    /// let ct1 = cks.encrypt(msg);
    /// assert_eq!(ct1.blocks().len(), num_blocks);
    ///
    /// let ct_res = sks.cast_to_signed(ct1, 4);
    /// assert_eq!(ct_res.blocks().len(), 4);
    ///
    /// // Decrypt
    /// let res: i8 = cks.decrypt_signed(&ct_res);
    /// assert_eq!(msg as i8, res);
    /// ```
    pub fn cast_to_signed<T: IntegerRadixCiphertext>(
        &self,
        mut source: T,
        target_num_blocks: usize,
    ) -> SignedRadixCiphertext {
        if !source.block_carries_are_empty() {
            self.full_propagate_parallelized(&mut source);
        }

        let current_num_blocks = source.blocks().len();

        let blocks = if T::IS_SIGNED {
            // Casting from signed to signed
            if target_num_blocks > current_num_blocks {
                let mut ct_as_signed_radix =
                    SignedRadixCiphertext::from_blocks(source.into_blocks());
                let num_blocks_to_add = target_num_blocks - current_num_blocks;
                self.extend_radix_with_sign_msb_assign(&mut ct_as_signed_radix, num_blocks_to_add);
                ct_as_signed_radix.blocks
            } else {
                let mut ct_as_unsigned_radix = RadixCiphertext::from_blocks(source.into_blocks());
                let num_blocks_to_remove = current_num_blocks - target_num_blocks;
                self.trim_radix_blocks_msb_assign(&mut ct_as_unsigned_radix, num_blocks_to_remove);
                ct_as_unsigned_radix.blocks
            }
        } else {
            // casting from unsigned to signed
            let mut ct_as_unsigned_radix = RadixCiphertext::from_blocks(source.into_blocks());
            if target_num_blocks > current_num_blocks {
                let num_blocks_to_add = target_num_blocks - current_num_blocks;
                self.extend_radix_with_trivial_zero_blocks_msb_assign(
                    &mut ct_as_unsigned_radix,
                    num_blocks_to_add,
                );
            } else {
                let num_blocks_to_remove = current_num_blocks - target_num_blocks;
                self.trim_radix_blocks_msb_assign(&mut ct_as_unsigned_radix, num_blocks_to_remove);
            }
            ct_as_unsigned_radix.blocks
        };

        assert_eq!(
            blocks.len(),
            target_num_blocks,
            "internal error, wrong number of blocks after casting"
        );
        SignedRadixCiphertext::from_blocks(blocks)
    }

    /// Propagate the carry of the 'index' block to the next one.
    ///
    /// # Example
    ///
    ///```rust
    /// use tfhe::integer::{gen_keys_radix, IntegerCiphertext};
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let msg = 7u64;
    ///
    /// let ct1 = cks.encrypt(msg);
    /// let ct2 = cks.encrypt(msg);
    ///
    /// // Compute homomorphically an addition:
    /// let mut ct_res = sks.unchecked_add(&ct1, &ct2);
    /// sks.propagate(&mut ct_res, 0);
    ///
    /// // Decrypt one block:
    /// let res: u64 = cks.decrypt_one_block(&ct_res.blocks()[1]);
    /// assert_eq!(3, res);
    /// ```
    pub fn propagate<T>(&self, ctxt: &mut T, index: usize)
    where
        T: IntegerRadixCiphertext,
    {
        let carry = self.key.carry_extract(&ctxt.blocks()[index]);

        ctxt.blocks_mut()[index] = self.key.message_extract(&ctxt.blocks()[index]);

        //add the carry to the next block
        if index < ctxt.blocks().len() - 1 {
            let next_block = &mut ctxt.blocks_mut()[index + 1];
            if self
                .key
                .max_noise_level
                .validate(next_block.noise_level() + carry.noise_level())
                .is_err()
            {
                let id_lut = self.key.generate_lookup_table(|x| x);
                self.key.apply_lookup_table_assign(next_block, &id_lut);
            }
            self.key
                .unchecked_add_assign(&mut ctxt.blocks_mut()[index + 1], &carry);
        }
    }

    /// Propagate all the carries.
    ///
    /// # Example
    ///
    ///```rust
    /// use tfhe::integer::gen_keys_radix;
    /// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128;
    ///
    /// let num_blocks = 4;
    ///
    /// // Generate the client key and the server key:
    /// let (cks, sks) = gen_keys_radix(PARAM_MESSAGE_2_CARRY_2_KS_PBS_GAUSSIAN_2M128, num_blocks);
    ///
    /// let msg = 10;
    ///
    /// let ct1 = cks.encrypt(msg);
    /// let ct2 = cks.encrypt(msg);
    ///
    /// // Compute homomorphically an addition:
    /// let mut ct_res = sks.unchecked_add(&ct1, &ct2);
    /// sks.full_propagate(&mut ct_res);
    ///
    /// // Decrypt:
    /// let res: u64 = cks.decrypt(&ct_res);
    /// assert_eq!(msg + msg, res);
    /// ```
    pub fn full_propagate<T>(&self, ctxt: &mut T)
    where
        T: IntegerRadixCiphertext,
    {
        self.partial_propagate(ctxt, 0);
    }

    /// Propagates carries from
    /// start_index to then end.
    ///
    /// Last carry is not propagated as
    /// it has nothing to propagate to.
    fn partial_propagate<T>(&self, ctxt: &mut T, start_index: usize)
    where
        T: IntegerRadixCiphertext,
    {
        let len = ctxt.blocks().len();
        for i in start_index..len {
            self.propagate(ctxt, i);
        }
    }
}