Skip to content

Instantly share code, notes, and snippets.

@ISSOtm
Created May 24, 2021 14:33
Show Gist options
  • Save ISSOtm/d4170f0d6ec7404654f6c1a0f1bb0c47 to your computer and use it in GitHub Desktop.
Save ISSOtm/d4170f0d6ec7404654f6c1a0f1bb0c47 to your computer and use it in GitHub Desktop.
Short, very incomplete implementation of u256 to showcase the use of `u128::overflowing_add`
use std::fmt::{self, Display, Formatter};
use std::ops::Add;
#[derive(Debug, Clone)]
struct u256 {
lo: u128,
hi: u128,
}
impl Add<u256> for u256 {
type Output = u256;
fn add(self, rhs: u256) -> u256 {
let (lo, carry) = self.lo.overflowing_add(rhs.lo);
u256 {
lo,
hi: self.hi + rhs.hi + if carry { 1 } else { 0 },
}
}
}
impl From<u128> for u256 {
fn from(lo: u128) -> Self {
Self { lo, hi: 0 }
}
}
impl Display for u256 {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {
// Doesn't work for non-hex, this is just an example
write!(fmt, "{:x}{:x}", self.hi, self.lo)
}
}
fn main() {
let mut x = u256::from(0x123456789ABCDEF0123456798ABCDEF0);
// Multiplication by 16, forgive my laziness to implement other operators
for _ in 0..4 {
x = x.clone() + x;
}
println!("{}", x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment