Pudu programming language
Menu
Package

@chrismichaelps / pudu-lang-resilience

Resilience pipelines for Pudu: retry, circuit breaker, timeout, fallback, hedging, rate limiting, and chaos injection

0.1.0Apache-2.01

InstallClose

Numeric.pudu

Pudu40 lines1.5 KB

GitHub ↗
1/** @Utils.Numeric.Module — saturating integers and float conversion */2module PuduLangResilience.Utils.Numeric34import Std.Decimal as Decimal5import Std.Math.Float as Float6import Std.Option as Option78/// The largest count or duration the package represents.9export const LARGEST: Int = 92233720368547758071011/// `left + right`, or `LARGEST` when the sum would exceed it. Both are at least zero.12export fn add(left: Int, right: Int) -> Int {13  if left > LARGEST - right { LARGEST } else { left + right }14}1516/// `left * right`, or `LARGEST` when the product would exceed it. Both are at least zero.17export fn multiply(left: Int, right: Int) -> Int {18  if left == 0 || right == 0 { return 0 }19  if left > LARGEST / right { LARGEST } else { left * right }20}2122/// The float nearest to an integer.23export fn toFloat(value: Int) -> Float { Decimal.toFloat64(Decimal.fromInt(value)) }2425/// The whole part of a float, clamped to zero below and to `LARGEST` above; `LARGEST` for a26/// value that is not finite.27export fn toInt(value: Float) -> Int {28  if !Float.isFinite(value) { return LARGEST }29  if value <= 0.0 { return 0 }30  if value >= 9.0e18 { return LARGEST }31  let whole = Float.floor(value)32  let parsed = Option.andThen(Decimal.parse(show(whole)), fn(exact: Decimal) -> Option[Int] { Decimal.toInt(Decimal.floor(exact)) })33  Option.unwrapOr(parsed, LARGEST)34}3536/// The count of parts per `whole` that `ratio` names, rounded down. `ratio` is between 0 and 1.37export fn partsOf(ratio: Decimal, whole: Int) -> Int {38  Option.unwrapOr(Decimal.toInt(Decimal.floor(ratio * Decimal.fromInt(whole))), 0)39}40