Math, Money & Time
Hale provides standard arithmetic and bitwise operators alongside first-class types for exact fixed-point decimals (Decimal), nanosecond time spans…
Hale provides standard arithmetic and bitwise operators alongside first-class types for exact fixed-point decimals (Decimal), nanosecond time spans (Duration), UTC timestamps (Time), and bounded or distinct integers. Financial calculations, unit conversions, and time arithmetic are checked at compile time with explicit rounding policies.
fn main() { let unit_price: Decimal<2> = 19.99d; let total = unit_price * 3d; // 59.97 (exact Decimal<2>)
let start = `2026-05-08T12:00:00Z`; let deadline = start + 1h + 30min; // 2026-05-08T13:30:00Z println(f"total={std::decimal::format(total, 2)} deadline={deadline}");}Numeric, Logical, and Bitwise Operators
Section titled “Numeric, Logical, and Bitwise Operators”| Category | Operators | Supported Types | Behavior & Notes |
|---|---|---|---|
| Arithmetic | +, -, *, / |
Int, U64, I32…U8, Float, Decimal, U256, I256, Duration (restricted) |
Integer / truncates toward zero; String also supports +; a fixed-width integer’s (U64, I32…U8) or a 256-bit integer’s overflow stops the process |
| Remainder | % |
Int, U64, I32…U8, Decimal, U256, I256 |
Not defined on Float |
| Equality | ==, != |
Int, U64, I32…U8, Float, Decimal, U256, I256, Bool, String, Duration, Time, enum, distinct Int |
Not defined on structs, tuples, or arrays (compare field by field) |
| Ordering | <, <=, >, >= |
Int, U64, I32…U8, Float, Decimal, U256, I256, String, Duration, Time |
Does not chain; write a < b && b < c |
| Logical | &&, ||, ! |
Bool |
&& and || short-circuit |
| Bitwise | &, |, ^, <<, >>, ~ |
Int, U64, I32…U8, U256, I256 |
Bitwise AND, OR, XOR, shifts (by an Int count), and NOT |
let a = 7 + 3; // 10let d = 7 / 3; // 2 (integer division)let e = 7 % 3; // 1 (remainder)
let between = a > 0 && a < 100; // chained comparisons require &&let safe = d != 0 && a / d > 2; // short-circuits before division when d == 0let masked = (a << 2) & 0xFF; // bitwise operations on IntInt, Float, and Decimal Overview
Section titled “Int, Float, and Decimal Overview”| Type | Representation | Implicit Conversions | Primary Use Case |
|---|---|---|---|
Int |
64-bit signed integer (i64) |
Widens to Float in unambiguous contexts |
Counts, indices, bitwise logic |
U64 |
64-bit unsigned integer, 0 to 2^64 - 1 |
None (U64::from_int(n)); an integer literal takes it from its place |
Hashes, counters past 2^63, uint64 IDs and protocol fields |
I32, U32, I16, U16, I8, U8 |
32-, 16- and 8-bit signed and unsigned integers, stored at that width | Widen where nothing is lost (U8 into U32, I32 into Int); narrow with T(x) or ... |
Dense buffers and records, vectorized kernels, binary protocols and C types |
Float |
64-bit IEEE-754 double (f64) |
None | Scientific math, ratios, physical measurements |
Decimal (Decimal<9>) |
128-bit fixed-point, 9 fractional places | Widens to Decimal<S> where S > 9 via .rescale(S) |
General exact decimal arithmetic |
Decimal<S> (S in 0..=18) |
128-bit fixed-point, S fractional places |
None (distinct per scale S) |
Currency (Decimal<2>), high-precision tokens (Decimal<18>) |
U256 / I256 |
256-bit unsigned / two’s complement signed integer | None (U256::from_int(n)) |
Chain values: balances, token amounts, ABI words, fixed-point prices |
Int and Float Conversions and Math
Section titled “Int and Float Conversions and Math”Implicit Widening and Explicit Casts
Section titled “Implicit Widening and Explicit Casts”Hale automatically widens Int to Float in five unambiguous contexts:
- At a
letbinding with a: Floattype annotation (let x: Float = n;). - When passing an
Intargument to aFloatfunction parameter (std::math::sqrt(16)). - In binary arithmetic or comparisons where the other operand is already
Float(2.0 * 3). - In a
Floatfield of atypestruct literal. - When returning an
Intfrom an infallible-> Floatfunction (fn f(n: Int) -> Float { return n; }).
Where both operands are Int or when converting Float to Int, use the built-in Float(x) and Int(x) casts or their std::math equivalents:
let hits = 3;let total = 8;let rate = Float(hits) / Float(total); // 0.375 (widens before division)let truncated = Int(3.9); // 3 (truncates toward zero)Int(x) and Float(x) are the only primitive cast expressions in the language; type names like String(x), Bool(x), and Bytes(x) are not casts and are rejected at compile time. Neither cast takes a Decimal<S>: Int(d) is refused by hale check (a Decimal has no Int; d.rescale(0) or trunc is its whole part as a Decimal<0>, and Int(std::decimal::to_float(d)) its nearest Int through Float), and Float(d) points at std::decimal::to_float(d).
std::math Functions and IEEE-754 Semantics
Section titled “std::math Functions and IEEE-754 Semantics”| Function | Signature | Description |
|---|---|---|
abs(x) |
(T) -> T (builtin) |
Absolute value (Int, Float, Decimal, Duration) |
min(a, b) / max(a, b) |
(T, T) -> T (builtin) |
Minimum / maximum; returns NaN if either Float argument is NaN. T may also be a quantity or point type (min(100ms, lo) over two Millis, two Prices); both operands must be one type at one unit |
std::math::int_to_float(n) |
(Int) -> Float |
Converts Int to Float (equivalent to Float(n)) |
std::math::float_to_int(x) |
(Float) -> Int |
Truncates Float toward zero (equivalent to Int(x)) |
std::math::round(x) |
(Float) -> Int |
Rounds half away from zero (2.5 -> 3, -2.5 -> -3) |
std::math::trunc(x) |
(Float) -> Int |
Truncates toward zero to Int |
std::math::floor(x) / ceil(x) |
(Float) -> Float |
Rounds down / up to nearest whole Float |
std::math::sqrt(x) / pow(x, y) |
(Float, ...) -> Float |
Square root and exponentiation |
std::math::exp(x) / log(x) |
(Float) -> Float |
Natural exponential and logarithm |
std::math::nan() / is_nan(x) |
() -> Float / (Float) -> Bool |
Produces or tests IEEE-754 NaN |
Float comparisons follow IEEE-754 rules:
NaNis unequal to everything, including itself (nan != nanistrue;==,<,<=,>,>=arefalse).-0.0 == 0.0evaluates totrue.- Printing a
Floatviaprintlnorto_stringoutputs the shortest decimal representation that round-trips back to the exact same IEEE-754 double viastd::str::parse_float. Usef"{x:.2}"when formatting for display.
Exact Fixed-Point Numbers (Decimal and Decimal<S>)
Section titled “Exact Fixed-Point Numbers (Decimal and Decimal<S>)”Use Decimal for prices, balances, and financial quantities where binary floating-point drift (0.1 + 0.2 != 0.3) is unacceptable. Write Decimal literals with a d suffix:
let price: Decimal<2> = 19.99d;let wei: Decimal<18> = 0.000000000000000001d;let total = price * 3d; // 59.97 (Decimal<2>)Scale Rules and .rescale(S)
Section titled “Scale Rules and .rescale(S)”- Parameterized scale:
Decimal<S>storesSdigits after the decimal point (0 <= S <= 18). UnparameterizedDecimalis an alias forDecimal<9>. - Compile-time scale checking: A
dliteral adopts the scale expected by its context (type annotation, parameter, struct field, binary operator, orif/matcharm). If the literal has nonzero digits beyond scaleS(such aslet p: Decimal<2> = 1.505d;or0.1234567891dforDecimal<9>), compilation fails at the literal. Similarly,std::str::parse_decimalfails into itsorbranch if the input string has more fractional digits than the target scale. - No implicit scale or type mixing:
Decimal<2>,Decimal<9>, andDecimal<18>are distinct types, andDecimalnever mixes implicitly withIntorFloat(multiply by3d, not3). - Arithmetic truncation: Arithmetic within
Decimal<S>truncates toward zero past theSth fractional digit (1.0d / 3.0dis0.333333333d). - Rescaling: Use
.rescale(S)to convert between scales. Widening to a largerSis exact; narrowing to a smallerScan drop nonzero digits and requires anorrounding or failure policy:
let precise: Decimal<18> = 1d / 3d; // 0.333333333333333333let cents = precise.rescale(2) or half_even; // 0.33 (rounded)let exact = precise.rescale(2) or raise; // fails if nonzero digits are droppedlet wide = cents.rescale(18); // exact widening, no `or` neededSupported narrowing policies on .rescale(S) are or trunc, or floor, or ceil, or half_up, or half_even, or <fallback>, or raise, and or handler(err).
Formatting and Converting Decimal
Section titled “Formatting and Converting Decimal”Printing a Decimal<S> trims trailing fractional zeros (12.50d prints as 12.5), serializes exact digits in JSON, and occupies 16 bytes on the bus regardless of scale.
| Function | Signature | Description |
|---|---|---|
std::decimal::format(d, places) |
(Decimal<S>, Int) -> String |
Formats with exact fractional places using half_up rounding |
std::decimal::from_int(n) |
(Int) -> Decimal<9> |
Exact conversion from Int (chain .rescale(S) for other scales) |
std::decimal::from_float(x) |
(Float) -> Decimal<9> fallible(...) |
Converts Float rounded half-away-from-zero at the 9th place; fails on NaN, Inf, or |x| > ~1.7e29 |
std::decimal::to_float(d) |
(Decimal<S>) -> Float |
Converts Decimal to closest IEEE-754 Float |
Unsigned 64-bit Integers (U64)
Section titled “Unsigned 64-bit Integers (U64)”U64 holds 0 through 2^64 - 1: a hash, a sequence number that runs past 2^63, an identifier or a protocol field another system hands out as a uint64. It is the same 8 bytes as an Int, read as unsigned. An integer literal is a U64 wherever its place is one, so there is no conversion to write for one:
fn fnv1a(text: String) -> U64 { let bytes = std::bytes::from_string(text); let mut h: U64 = 14695981039346656037; // a literal past Int's max let mut i = 0; while i < len(bytes) { h = h ^ U64::from_int(std::bytes::read_u8(bytes, i) or 0); h = U64::wrapping_mul(h, 1099511628211); // a hash wants wrapping i = i + 1; } return h;}
fn main() { let seq: U64 = 18446744073709551615; // 2^64 - 1 let next = U64::checked_add(seq, 1) or 0; // overflow fails into the `or` println(fnv1a("a"), " ", next, " ", seq / 2, " ", seq >> 60); let n = U64::to_int(seq) or -1; // past Int's max: -1 let f = Float(seq); // the nearest double}- Literals. An integer literal is a
U64where its place is: aletascription, an argument, a return, a field, the other side of an operator,min/max, an array, a match arm or pattern. A decimal literal pastInt’s max (9223372036854775808and up) is aU64by itself and is refused anywhere else; past2^64 - 1it does not lex. A negative literal where aU64is expected is refused where it is written. - Arithmetic never wraps unless you ask.
+ - *past either end and/or%by zero stop the process with a violation, as aU256does, where anIntwould wrap.U64::wrapping_add,wrapping_subandwrapping_mulwrap modulo2^64;U64::checked_add,checked_sub,checked_mulandchecked_divfail into anor(ArithError). - Unsigned all the way.
/,%, the comparisons,minandmaxtreat the value as unsigned, and>>fills with zeros. There is no unary-. - Bits.
& | ^ ~are bitwise;x << nandx >> nshift by anIntcount from 0 to 63, and any other count stops the process.U64::wrapping_shl/wrapping_shrtake the count modulo 64. - No mixing. A
U64never mixes with anInt, aFloator another width: writeU64::from_int(n)(a negativenstops the process),U64::to_int(x) or ...,Float(x),U64::from_float(f) or ....U64::from_bits(n)/to_bits(x)reinterpret the 64 bits. The check names the conversion. - Text and bytes.
to_string(x),println, f-strings and+with aStringprint unsigned decimal;U64::to_hex(x)is0xand lowercase digits;U64::parsereads either;to_be_bytes/to_le_bytesandfrom_be_bytes/from_le_bytesare its 8 bytes. - Where it goes. Record and locus fields,
boundedlists, fixed arrays, enum payloads, hashmap cells,Box<U64>, bus payloads,@ffi("c")(auint64_t), and the JSON codecs, which always write a JSON string (see JSON Encoding & Decoding); protobuf carries auint64. A unit-dialect scalar (quantity U64 in wei,distinct U64,U64 { range: … }) may count aU64and has its arithmetic (see Units, End to End).
Fixed-width Integers (I32, U32, I16, U16, I8, U8)
Section titled “Fixed-width Integers (I32, U32, I16, U16, I8, U8)”Int is 64 bits everywhere. When a value has a known, smaller range (a byte of a frame, a pixel channel, a 16-bit sample, a 32-bit ID another system hands out) a fixed-width integer stores it at its own width: a bounded[U8; 1024] field is 1024 bytes, not 8192, and a loop over U32s works four lanes of a 128-bit vector register where an Int loop works two. I is signed, U unsigned; I32 holds -2147483648 through 2147483647, U8 0 through 255.
type Frame { kind: U8; samples: bounded[I16; 256]; }
fn checksum(f: Frame) -> U32 { let mut h: U32 = 2166136261; // a literal takes its place's type for s in f.samples { h = U32::wrapping_mul(h ^ (U32(Int(s) & 0xFFFF) or 0), 16777619); } return h;}
fn main() { let mut f = Frame { kind: 3 }; push(f.samples, -32768) or discard; push(f.samples, 1200) or discard; let peak: Int = at(f.samples, 1) or 0; // an I16 widens into an Int let level = U8(peak / 8) or clamp; // a narrowing says what happens outside 0..255 let total = U32::checked_add(checksum(f), 1) or 0; // overflow fails into the `or` println(f.kind, " ", level, " ", total);}- Literals are typed from their place, as a
U64’s are, and must fit:let b: U8 = 256;is refused where it is written, and so is-1where an unsigned one is expected. - Arithmetic never wraps unless you ask.
+ - *past either end,/or%by zero, and-of a signed one’s minimum stop the process with a violation.T::wrapping_add,wrapping_subandwrapping_mulwrap modulo the width;T::checked_add,checked_sub,checked_mulandchecked_divfail into anor(ArithError).T::max()andT::min()are the ends. - Widening is implicit where nothing is lost: into a wider type of the same signedness, an unsigned one into a strictly wider signed one, and anything into
Int, wherever a value flows (alet, an argument, a return, a field, an element). An operator never widens:a + bof aU8and aU32is refused, naming the conversion (U32(a)). - Narrowing is a cast with an
or, as for a range type:U8(n) or clamp,or wrap(the low bits),or 0,or handler(err)(aRangeError),or raise. Without theorit is refused. - Bits.
& | ^ ~work at the width;<<and>>shift by anIntcount below the width, and>>keeps the sign of a signed one.T::wrapping_shl/wrapping_shrtake the count modulo the width. - Vectorized kernels. A checked
+has an overflow branch per element, which keeps a loop scalar. A kernel that wants vector lanes says so withwrapping_*:acc = U32::wrapping_add(acc, U32::wrapping_mul(x, 3));over abounded[U32; N]is fouri32lanes a NEON instruction on aarch64. The chain’s.sum(seed)sums in its seed’s type:.sum(U32(0)). - Where it goes. Everywhere
Intgoes, at its own width: record and locus fields,boundedlists, fixed arrays, enum payloads, hashmap cells,Box<U8>, bus payloads (taggedu8,i32, … in a topic’s shape),@ffi("c")(the Cint8_t…uint32_t), the JSON codecs (a number, its range checked on read) and protobuf (int32/uint32, range-checked on decode). A unit-dialect scalar may count one:type Ticks = quantity U32 in tick;.
256-bit Integers (U256 and I256)
Section titled “256-bit Integers (U256 and I256)”U256 (0 through 2^256 - 1) and I256 (-2^255 through 2^255 - 1) carry the values chain APIs speak in: balances, token amounts, ABI words, and the fixed-point numbers of AMM price math, all past the range of Decimal’s 128-bit mantissa. They have no literal; U256:: and I256:: functions make and take them:
fn quote(amount_in: U256, reserve_in: U256, reserve_out: U256) -> U256 fallible(ArithError) { // a * b / c with the product exact in 512 bits: no overflow in between return U256::mul_div(amount_in, reserve_out, reserve_in) or raise;}
fn main() { let wei = U256::parse("1000000000000000000") or raise; // decimal or 0x hex let fee = U256::from_int(3); let out = quote(wei, U256::from_int(5000), U256::from_int(7000)) or raise; println(out, " ", U256::to_hex(wei * fee)); // 1400000000000000000 0x29a2241af62c0000 let bytes = U256::to_be_bytes(wei); // 32 big-endian bytes let back = U256::from_be_bytes(bytes) or raise; let small = U256::to_int(back / U256::from_int(1000000000)) or raise; // 1000000000}- Arithmetic never wraps.
+ - * / %(and anI256’s unary-) stop the process with a violation on an overflow or a division by zero, where anIntwould wrap.U256::checked_add,checked_sub,checked_mul,checked_divandmul_divreturnfallible(ArithError)instead, so the failure goes through anor(ArithError { kind, op },kindoverflowordivision_by_zero). - Division rounds as
Int’s does:/toward zero,%taking the dividend’s sign. - Bits.
& | ^ ~are bitwise;x << nandx >> nshift by anIntcount, dropping the bits shifted out (anI256’s>>keeps the sign). - No mixing. A 256-bit integer never mixes with an
Int, aDecimalor the other width: writeU256::from_int(n),U256::to_int(x) or ...,I256::from_u256(x) or .... The check names the conversion. - Text and bytes.
to_string(x)(andprintln, f-strings,+with aString) is decimal;U256::to_hex(x)is0xand lowercase digits;U256::parsereads either;to_be_bytes/from_be_bytesare the 32-byte big-endian word. - Where they go. Record and locus fields,
boundedlists, fixed arrays, enum payloads, hashmap cells, bus payloads, and the JSON codecs, which write a JSON string (see JSON Encoding & Decoding).
Duration and Time
Section titled “Duration and Time”Duration and Time are defined by the standard library using Hale’s unit system: Duration is quantity Int in ns, and Time is point Duration (nanoseconds since the Unix epoch in UTC).
Time Units and std::time Reference
Section titled “Time Units and std::time Reference”| Unit / Function | Definition / Signature | Description |
|---|---|---|
ns, us, ms, s, min, h, day |
1us = 1000ns, 1ms = 1000us, 1s = 1000ms, 1min = 60s, 1h = 60min, 1day = 24h |
Duration literal suffixes (write 1h + 30min, never 1h30m, 5m, or 3d) |
std::time::sleep(d) |
(Duration) -> () |
Sleeps for duration d |
std::time::monotonic() |
() -> Duration |
Monotonic elapsed time since boot (never jumps backward; use for benchmarks/timers) |
std::time::current() |
() -> Time |
Current UTC wall-clock instant (Time) |
std::time::now() |
() -> Int |
Current UTC Unix timestamp in whole seconds (Int) |
std::time::iso8601(t) |
(Time) -> String |
Formats Time as an ISO-8601 UTC string |
std::time::parse_time(s) |
(String) -> Time fallible(ParseError) |
Parses an ISO-8601 UTC string (validates leap years and calendar dates) |
std::time::parse_rfc3339(s) |
(String) -> Time fallible(ParseError) |
Parses an RFC 3339 timestamp with its offset (Z, +02:00, -05:30) and applies the offset: 2026-11-15T10:00:00+02:00 is 08:00:00Z |
std::time::parse_iso8601(s) |
(String) -> Int fallible(ParseError) |
Parses an ISO-8601 string to Unix epoch seconds (Int), supporting dates outside 1677–2262 |
std::time::unix(t) / nanos(t) |
(Time) -> Int |
Extracts Unix seconds or epoch nanoseconds from Time |
std::time::time_from_unix(secs) / from_nanos(n) |
(Int) -> Time |
Constructs Time from seconds or nanoseconds |
Duration Arithmetic
Section titled “Duration Arithmetic”Every Duration counts nanoseconds (println(16ms) outputs 16000000ns). Durations support addition, subtraction, comparison, and integer scaling:
let timeout = 5s;let frame = 16ms;let compound = 1h + 30min;
let backoff = tries * 100ms; // Int * Duration -> Durationlet slice = timeout / workers; // Duration / runtime Int -> Duration (integer division)let half = timeout / 2 or floor; // Duration / literal Int -> requires rounding policylet frames = timeout / frame; // Duration / Duration -> IntDividing a Duration by a compile-time integer literal requires an explicit remainder policy (or floor, or ceil, or trunc, or half_up, or half_even, or or <fallback>). Multiplying two durations (Duration * Duration) is a compile error.
Time Instants
Section titled “Time Instants”Write Time literals as UTC ISO-8601 timestamps enclosed in backticks:
let launch = `2026-05-08T12:00:00Z`;let precise = `2026-09-14T08:30:15.25Z`;let deadline = launch + 30min;let slack = deadline - std::time::current(); // Duration- UTC-only literals: Non-UTC offsets (such as
`2026-05-08T12:00:00+01:00`) are rejected at compile time, andparse_timerefuses them at run time rather than drop them. Text that carries an offset (an RFC 3339 timestamp from another system) is read withstd::time::parse_rfc3339, which applies it. - 64-bit nanosecond range (1677–2262):
Timespans years1677through2262. Out-of-range literals fail at compile time,parse_timetakes itsorbranch, and runtime arithmetic (t + dortime_from_unix) that overflows halts with aviolation:. Usestd::time::parse_iso8601(s)when working with calendar timestamps outside 1677–2262 asIntseconds.
Distinct Identities, Bounded Ranges, and Custom Units
Section titled “Distinct Identities, Bounded Ranges, and Custom Units”Identities (distinct Int) and Ranges (range:)
Section titled “Identities (distinct Int) and Ranges (range:)”Use distinct Int to create strongly typed integer IDs that cannot be added or mixed with plain Int, and { range: low..high; } to constrain valid integer bounds:
type OrderId = distinct Int;type Byte = Int { range: 0..256; }type Session = distinct Int { range: 0..64; }
fn main() { let id: OrderId = 4; let b: Byte = 200; let total: Int = b + 55; // range types widen to Int automatically let slot = Session(70) or 0; // 70 is out of range 0..64 -> substitutes 0 let top = Byte(total + 10) or clamp; let raw: Int = Int(id); // explicit unwrap of distinct Int println(id, " ", total, " ", slot, " ", top, " ", raw);}Narrowing an integer into a ranged type requires an or clause (or <fallback>, or clamp, or wrap, or handler(err), or or raise). Out-of-range literals (let b: Byte = 300;) fail at compile time.
Custom Units and Quantities
Section titled “Custom Units and Quantities”You can declare domain-specific units (cents, dollars, basis points, bytes, ticks) with unit, quantity, and point:
unit cent;unit USD = 100 cent;unit pct = 1/100;unit bp = 1/100 pct;
type Money = quantity Int in cent;type Ledger = Money { round: half_even; }type Rate = quantity Int in bp;
fn main() { let fee = 1_250_000USD * 3bp; // exact: 375000000 Money in 1/10000 cent (375 USD) let odd = 1_234_567USD * 3bp; // exact: 370.3701 USD in 1/10000 cent let paid: Ledger = odd; // rounds via Ledger's half_even policy let cents = odd.in(cent) or ceil; // explicit site-level rounding println(fee, " ", odd, " ", paid, " ", cents);}See Units, End to End for the complete guide to custom units, affine points, unit splitting (.split(u)), and hale check --units.
Next: Units of Measure.