Search Apps Documentation Source Content File Folder Download Copy Actions Download State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

README.md

1.21 Kb · 45 lines

uint256

256-bit unsigned integer arithmetic for GnoSwap.

Overview

Fixed-size 256-bit unsigned integer library optimized for AMM calculations with precise MulDiv operations. The unsuffixed Add, Sub, and Mul methods return the low 256 bits; the corresponding AddOverflow, SubOverflow, and MulOverflow variants also report an overflow/underflow flag.

Features

  • Fixed 256-bit size (4 uint64 values)
  • Explicit overflow detection via *Overflow variants
  • Optimized MulDiv for precise calculations
  • Decimal string conversion
  • Range: 0 to 2^256-1

Usage

 1package main
 2
 3import u256 "gno.land/p/gnoswap/uint256/v1"
 4
 5func main() {
 6    a := u256.NewUint(1000)
 7    b := u256.MustFromDecimal("1000000000000000000")
 8    result, overflow := new(u256.Uint).AddOverflow(a, b)
 9    if overflow {
10        panic("unsigned addition overflow")
11    }
12    println(result.ToString()) // 1000000000000001000
13
14    // MulDiv calculates floor(a*b/c). The denominator must be non-zero,
15    // and the quotient must fit in 256 bits; otherwise it panics.
16    c := u256.NewUint(3)
17    println(u256.MulDiv(a, b, c).ToString()) // 333333333333333333333
18}

Credits

Ported from holiman/uint256