Skip to content

Commit fe6f125

Browse files
committed
fix(integer): fix StaticUnsignedBigInt cast into u128
1 parent edb435b commit fe6f125

File tree

2 files changed

+51
-3
lines changed

2 files changed

+51
-3
lines changed

tfhe/src/integer/bigint/static_signed.rs

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -504,7 +504,7 @@ impl<const N: usize> CastFrom<StaticSignedBigInt<N>> for u64 {
504504
impl<const N: usize> CastFrom<StaticSignedBigInt<N>> for u128 {
505505
fn cast_from(input: StaticSignedBigInt<N>) -> Self {
506506
let inner = &input.0;
507-
inner[0] as Self | ((inner[1] as Self) << 64)
507+
inner[0] as Self | ((inner.get(1).copied().unwrap_or(0) as Self) << 64)
508508
}
509509
}
510510

@@ -517,6 +517,37 @@ impl<const N: usize> CastFrom<super::static_unsigned::StaticUnsignedBigInt<N>>
517517
}
518518
impl<const N: usize> CastFrom<StaticSignedBigInt<N>> for i128 {
519519
fn cast_from(input: StaticSignedBigInt<N>) -> Self {
520-
input.0[0] as Self | ((input.0.get(1).copied().unwrap_or(0) as Self) << 64)
520+
let inner = &input.0;
521+
inner[0] as Self | ((inner.get(1).copied().unwrap_or(0) as Self) << 64)
521522
}
522523
}
524+
525+
526+
#[cfg(test)]
527+
mod test {
528+
use crate::core_crypto::commons::numeric::CastFrom;
529+
use crate::integer::bigint::StaticSignedBigInt;
530+
531+
#[test]
532+
fn test_u128_cast() {
533+
let a = 1_u128 << 64;
534+
535+
let b= StaticSignedBigInt::<4>::cast_from(a);
536+
537+
let c = u128::cast_from(b);
538+
539+
assert_eq!(a, c);
540+
}
541+
542+
#[test]
543+
fn test_i128_cast() {
544+
let a = 1_i128 << 64;
545+
546+
let b: StaticSignedBigInt<4> = a.into();
547+
548+
let c = i128::cast_from(b);
549+
550+
assert_eq!(a, c);
551+
}
552+
}
553+

tfhe/src/integer/bigint/static_unsigned.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -418,7 +418,7 @@ impl<const N: usize> CastFrom<u128> for StaticUnsignedBigInt<N> {
418418

419419
impl<const N: usize> CastFrom<StaticUnsignedBigInt<N>> for u128 {
420420
fn cast_from(input: StaticUnsignedBigInt<N>) -> Self {
421-
input.0[0] as Self | input.0.get(1).copied().unwrap_or(0) as Self
421+
input.0[0] as Self | ((input.0.get(1).copied().unwrap_or(0) as Self) << 64)
422422
}
423423
}
424424

@@ -496,3 +496,20 @@ impl<const N: usize> TryFrom<StaticUnsignedBigInt<N>> for u128 {
496496
}
497497
}
498498
}
499+
500+
#[cfg(test)]
501+
mod test {
502+
use crate::core_crypto::commons::numeric::CastFrom;
503+
use crate::integer::bigint::StaticUnsignedBigInt;
504+
505+
#[test]
506+
fn test_u128_cast() {
507+
let a = 1_u128 << 64;
508+
509+
let b: StaticUnsignedBigInt<4> = a.into();
510+
511+
let c = u128::cast_from(b);
512+
513+
assert_eq!(a, c);
514+
}
515+
}

0 commit comments

Comments
 (0)