std.convert

Explicit conversions between primitive values.

Importuse std.convert

Functions

fn float_to_int(x: float) -> int#

Truncates toward zero (1.99 -> 1, -1.99 -> -1).

  • x: Value to truncate.
println(std.convert.float_to_int(1.99))  // 1
println(std.convert.float_to_int(-1.99)) // -1
fn int_to_float(x: int) -> float#

The nearest IEEE double to x (exact for |x| < 2^53).

  • x: Value to widen.
let half = std.convert.int_to_float(5) / 2.0
println(half) // 2.5
fn bool_to_int(b: bool) -> int#

true -> 1, false -> 0.

  • b: Value to encode.
println(std.convert.bool_to_int(true)) // 1
println(std.convert.int_to_bool(0))    // false
println(std.convert.int_to_bool(2))    // true
fn int_to_bool(x: int) -> bool#

0 -> false, anything else -> true.

  • x: Value to test against zero.
fn parse_on(value: string) -> bool#

Whether an environment-variable value reads as "on".

The set every service ends up writing for itself: 1, true, yes, on, case-insensitively and after trimming. Anything else — including the empty string an unset variable reads as — is off, so a flag that is not understood stays off rather than becoming on by accident.

  • value: Raw environment-variable text, trimmed and matched case-insensitively.
println(std.convert.parse_on(" YES "))   // true
println(std.convert.parse_on("on"))      // true
println(std.convert.parse_on("enabled")) // false — unknown spellings stay off
fn parse_env_int(value: string) -> Optional<int>#

A base-10 integer, or none — Go's strconv.ParseInt(value, 10, 64).

Stricter than strings.try_parse_int in the way an environment parser has to be: only [+-]?\d+ is a number (no whitespace, no 0x, no trailing text), and the magnitude must fit in an i64 rather than wrapping. A configuration value that is out of range is a misconfiguration, and reading it as some unrelated number is the worst available answer.

  • value: Raw environment-variable text, which must be [+-]?\d+ and fit in an i64.
println(std.convert.parse_env_int("8080")) // some(8080)
println(std.convert.parse_env_int("0x10")) // none — base 10 only
let port = std.convert.parse_env_int("").unwrap_or(3000)
println(port) // 3000