Unit Built-ins
| Function | Description | OPA | Wasm | Swift | Java |
|---|---|---|---|---|---|
|
Converts strings like "10G", "5K", "4M", "1500m", and the like into a number. This number can be a non-integer, such as 1.5, 0.22, etc. Scientific notation is supported, allowing values such as "1e-3K" (1) or "2.5e6M" (2.5 million M). Supports standard metric decimal and binary SI units (e.g., K, Ki, M, Mi, G, Gi, etc.) where m, K, M, G, T, P, and E are treated as decimal units and Ki, Mi, Gi, Ti, Pi, and Ei are treated as binary units. Note that 'm' and 'M' are case-sensitive to allow distinguishing between "milli" and "mega" units respectively. Other units are case-insensitive. Arguments: Returns:x (string)the unit to parse y (number)the parsed number | v0.41.0 | SDK | 0.0.1 | ✗ |
|
Converts strings like "10GB", "5K", "4mb", or "1e6KB" into an integer number of bytes. Supports standard byte units (e.g., KB, KiB, etc.) where KB, MB, GB, and TB are treated as decimal units, and KiB, MiB, GiB, and TiB are treated as binary units. Scientific notation is supported, enabling values like "1.5e3MB" (1500MB) or "2e6GiB" (2 million GiB). The bytes symbol (b/B) in the unit is optional; omitting it will yield the same result (e.g., "Mi" and "MiB" are equivalent). Arguments: Returns:x (string)the byte unit to parse y (number)the parsed number | v0.17.0 | SDK | 0.0.1 | ✗ |
Examples
units.parse
units.parse turns a string with an optional unit suffix into a number.
It accepts decimal SI suffixes (K, M, G, …), binary suffixes
(Ki, Mi, Gi, …), and a lower-case m for milli. m and M are
case-sensitive so milli and mega stay distinct.
A common use is comparing resource limits that arrive with different suffixes in the same policy check.
Comparing memory limits with different units
Container specs often express memory with different suffixes (Mi, Gi,
bare numbers). units.parse turns those strings into numbers so a policy
can compare them. Here, a container is rejected when its memory limit is
higher than the namespace cap.
package play
# Cap for the whole namespace, normalized to a number.
max_memory := units.parse(input.namespace_memory_limit)
# Containers whose limit is above the namespace cap.
deny contains msg if {
some c in input.containers
units.parse(c.memory_limit) > max_memory
msg := sprintf(
"container %q memory limit %s exceeds namespace cap %s",
[c.name, c.memory_limit, input.namespace_memory_limit],
)
}
{
"deny": [
"container \"batch\" memory limit 2Gi exceeds namespace cap 1Gi"
],
"max_memory": 1073741824
}{
"namespace_memory_limit": "1Gi",
"containers": [
{
"name": "app",
"memory_limit": "512Mi"
},
{
"name": "batch",
"memory_limit": "2Gi"
}
]
}
{}