#!/usr/bin/env dub
/+ dub.sdl:
name "uom_quantity_runtime_expected"
dependency "sparkles:base" path="../../../.."
dependency "sparkles:math" path="../../../.."
dflags "-preview=in" "-preview=dip1000"
targetPath "build"
+/
/**
* Units of measure — runtime dimensions checked at runtime, failures reported
* as `Expected` (not thrown), for a raytracer whose material data is loaded at
* runtime.
*
* The compile-time prototypes in this catalog put the dimension in the *type*
* (`Quantity!dim`), so a mismatch is a build error. That is the right default
* when the units are known when the code is written. But a physically-based
* renderer often reads its spectra, BRDFs and emitters from a *material file*
* parsed at startup: the fact that a given channel is a `Radiance` and another
* is an `Irradiance` is data, not a type. So here the dimension is a plain
* runtime value — `struct Dim` — stored *inside* every quantity
* (`struct RQuantity { double value; Dim dim; }`), and the check runs when the
* data flows, not when the program is compiled.
*
* Because the check can now *fail at runtime*, arithmetic that can fail does
* not throw: `add`/`sub` return `Expected!(RQuantity, DimError)` from the
* repo's `expected` library — `add(len, len)` is `ok`, `add(radiance,
* irradiance)` and `metre + second` are `err`, and the caller branches on
* `hasError` instead of unwinding. Multiplication is *total* (any two
* dimensions combine), so `mul`/`div` return an `RQuantity` directly. The whole
* checking core is `@safe pure nothrow @nogc`; only the CTFE-flavoured
* `unitString` pretty-printer (run at runtime here, since the dims aren't known
* earlier) may GC, and the one deliberate throwing path (`mustAdd`) uses the
* `recycledErrorInstance` idiom so it stays `@nogc`.
*
* (Aside: `Dim` carries a fourth exponent, solid angle / steradian. SI treats
* `sr` as dimensionless, which is exactly why `Radiance = W·m⁻²·sr⁻¹` and
* `Irradiance = W·m⁻²` collapse to the *same* base dimensions and silently add
* — tracking `sr` is what lets the runtime check catch the confusion the
* prompt asks for.)
*
* Companion to docs/research/units-of-measure/python-pint.md (Pint's runtime
* `Quantity`/`UnitRegistry` is the canonical runtime-checking design) and
* docs/research/units-of-measure/ucum-qudt.md (UCUM/QUDT model units as runtime
* data too); the `Expected`-not-throw discipline follows
* docs/guidelines/idioms/expected/. In the comparison matrix this is the
* runtime-checking + runtime-companion cell (#4/#8) — the mirror of the
* compile-time cells the other prototypes occupy.
*
* Composition: a runtime-dim vector (`RVec3 { Vec3 value; Dim dim; }`, using
* `sparkles:math`'s `Vector`) is composition *ordering A* — one `Dim` tag wraps
* the whole `Vec3`, so a 3-component radiance sample is checked once, not thrice.
* That is memory-honest for a vector, but the per-value `Dim` (four `int`s here)
* is exactly the runtime cost the type-level prototypes erase to zero: this
* approach trades that footprint for the ability to decide units at runtime.
*
* Run with: `dub run --single quantity-runtime-expected.d`
*/
module (module) uom_quantity_runtime_expectedUnits of measure — runtime dimensions checked at runtime, failures reported
as Expected (not thrown), for a raytracer whose material data is loaded at
runtime.
The compile-time prototypes in this catalog put the dimension in the type
(Quantity!dim), so a mismatch is a build error. That is the right default
when the units are known when the code is written. But a physically-based
renderer often reads its spectra, BRDFs and emitters from a material file
parsed at startup: the fact that a given channel is a Radiance and another
is an Irradiance is data, not a type. So here the dimension is a plain
runtime value — struct Dim — stored inside every quantity
(struct RQuantity { double value; Dim dim; }), and the check runs when the
data flows, not when the program is compiled.
Because the check can now fail at runtime, arithmetic that can fail does
not throw: add/sub return Expected!(RQuantity, DimError) from the
repo's expected library — add(len, len) is ok, add(radiance,
irradiance) and metre + second are err, and the caller branches on
hasError instead of unwinding. Multiplication is total (any two
dimensions combine), so mul/div return an RQuantity directly. The whole
checking core is @safe pure nothrow @nogc; only the CTFE-flavoured
unitString pretty-printer (run at runtime here, since the dims aren't known
earlier) may GC, and the one deliberate throwing path (mustAdd) uses the
recycledErrorInstance idiom so it stays @nogc.
(Aside: Dim carries a fourth exponent, solid angle / steradian. SI treats
sr as dimensionless, which is exactly why Radiance = W·m⁻²·sr⁻¹ and
Irradiance = W·m⁻² collapse to the same base dimensions and silently add
— tracking sr is what lets the runtime check catch the confusion the
prompt asks for.)
Companion to docs/research/units-of-measure/python-pint.md (Pint's runtime
Quantity/UnitRegistry is the canonical runtime-checking design) and
docs/research/units-of-measure/ucum-qudt.md (UCUM/QUDT model units as runtime
data too); the Expected-not-throw discipline follows
docs/guidelines/idioms/expected/. In the comparison matrix this is the
runtime-checking + runtime-companion cell (#4/#8) — the mirror of the
compile-time cells the other prototypes occupy.
Composition
a runtime-dim vector (RVec3 { Vec3 value; Dim dim; }, using
sparkles:math's Vector) is composition ordering A — one Dim tag wraps
the whole Vec3, so a 3-component radiance sample is checked once, not thrice.
That is memory-honest for a vector, but the per-value Dim (four ints here)
is exactly the runtime cost the type-level prototypes erase to zero: this
approach trades that footprint for the ability to decide units at runtime.
Run with: dub run --single quantity-runtime-expected.d
uom_quantity_runtime_expected;
import (module) expectedThis module is implementing the Expected idiom.
See the $(LINK2 http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Andrei-Alexandrescu-Systematic-Error-Handling-in-C, Andrei Alexandrescu’s talk (Systematic Error Handling in C++)
and its slides.
Or more recent "Expect the Expected" by Andrei Alexandrescu for further background.
It is also inspired by C++'s proposed std::expected and Rust's Result.
Similar work is expectations by Paul Backus.
Main features
lightweight, no other external dependencies
works with pure, @safe, @nogc, nothrow, and immutable
provides methods: ok, err, consume, expect, expectErr, andThen, orElse, map, mapError, mapOrElse
type inference for ease of use with ok and err
allows to use same types for T and E
allows to define Expected without value (void for T) - can be disabled with custom Hook
provides facility to change the Expected behavior by custom Hook implementation using the Design by introspection paradigm.
can enforce result check (with a cost)
can behave like a normal Exception handled code by changing the used Hook implementation
range interface
Description
Actual Expected type is defined as Expected!(T, E, Hook), where:
T defines type of the success value
E defines type of the error
Hook defines behavior of the Expected
Default type for error is string, i.e. Expected!int is the same as Expected!(int, string).
Abort is used as a default hook.
Hooks
Expected has customizable behavior with the help of a third type parameter,
Hook. Depending on what methods Hook defines, core operations on the
Expected may be verified or completely redefined.
If Hook defines no method at all and carries no state, there is no change in
default behavior.
This module provides a few predefined hooks (below) that add useful behavior to
Expected:
| Abort | Fails every incorrect operation with a call to assert(0). It is the default third parameter, i.e. Expected!short is the same as Expected!(short, string, Abort). |
| Throw | Fails every incorrect operation by throwing an exception. |
| AsException | With this hook implementation Expected behaves just like regular Exception handled code.
That means when function returns expected value, it returns instance
of Expected with a success value.
But when it tries to return error, Exception is thrown right away,
i.e. Expected fails in constructor.
|
| RCAbort | Similar to Abort hook but uses reference counted payload instead which enables checking if the caller properly checked result of the Expected. |
The hook's members are looked up statically in a Design by Introspection manner
and are all optional. The table below illustrates the members that a hook type
may define and their influence over the behavior of the Checked type using it.
In the table, hook is an alias for Hook if the type Hook does not
introduce any state, or an object of type Hook otherwise.
Hook member
Semantics in Expected!(T, E, Hook)
-
- `enableDefaultConstructor`
- If defined, `Expected` would have enabled or disabled default constructor
based on it's `bool` value. Default constructor is disabled by default.
`opAssign` for value and error types is generated if default constructor is enabled.
-
- `enableCopyConstructor`
- If defined, `Expected` would have enabled or disabled copy constructor based
on it's `bool` value. It is enabled by default. When disabled, it enables automatic
check if the result was checked either for value or error.
When not checked it calls `hook.onUnchecked` if provided.
WARNING: As currently it's not possible to change internal state of `const`
or `immutable` object, automatic checking would't work on these. Hopefully with
`__mutable` proposal..
-
- `enableRefCountedPayload`
- Set `Expected` instances to use reference counted payload storage. It's usefull
when combined with `onUnchecked` to forcibly check that the result was checked for value
or error.
-
- `enableVoidValue`
- Defines if `Expected` supports `void` values. It's enabled by default so this
hook can be used to disable it.
-
- `onAccessEmptyValue`
- If value is accessed on unitialized `Expected` or `Expected` with error
value, `hook.onAccessEmptyValue!E(err)` is called. If hook doesn't implement the
handler, `T.init` is returned.
-
- `onAccessEmptyError`
- If error is accessed on unitialized `Expected` or `Expected` with value,
`hook.onAccessEmptyError()` is called. If hook doesn't implement the handler,
`E.init` is returned.
-
- `onUnchecked`
- If the result of `Expected` isn't checked, `hook.onUnchecked()` is called to
handle the error. If hook doesn't implement the handler, assert is thrown.
Note that `hook.enableCopyConstructor` must be `false` or `hook.enableRefCountedPayload`
must be `true` for checks to work.
-
- `onValueSet`
- `hook.onValueSet!T(val)` function is called when success value is being set to
`Expected`. It can be used for loging purposes, etc.
-
- `onErrorSet`
- `hook.onErrorSet!E(err)` function is called when error value is being set to
`Expected`. This hook function is used by `AsException` hook implementation
to change `Expected` idiom to normal `Exception` handling behavior.
Author
Tomáš Chaloupka
Examples
Basic usage
auto foo(int i) {
if (i == 0) return err!int("oops");
return ok(42 / i);
}
version (D_Exceptions)
{
auto bar(int i) {
if (i == 0) throw new Exception("err");
return i-1;
}
}
// basic checks
assert(foo(2));
assert(foo(2).hasValue);
assert(!foo(2).hasError);
assert(foo(2).value == 21);
assert(!foo(0));
assert(!foo(0).hasValue);
assert(foo(0).hasError);
assert(foo(0).error == "oops");
// void result
assert(ok()); // no error -> success
assert(!ok().hasError);
// assert(err("foo").hasValue); // doesn't have hasValue and value properties
version (D_Exceptions)
{
// expected from throwing function
assert(consume!bar(1) == 0);
assert(consume!bar(0).error.msg == "err");
}
// orElse
assert(foo(2).orElse!(() => 0) == 21);
assert(foo(0).orElse(100) == 100);
// andThen
assert(foo(2).andThen(foo(6)) == 7);
assert(foo(0).andThen(foo(6)).error == "oops");
// map
assert(foo(2).map!(a => a*2).map!(a => a - 2) == 40);
assert(foo(0).map!(a => a*2).map!(a => a - 2).error == "oops");
// mapError
assert(foo(0).mapError!(e => "OOPS").error == "OOPS");
assert(foo(2).mapError!(e => "OOPS") == 21);
// mapOrElse
assert(foo(2).mapOrElse!(v => v*2, e => 0) == 42);
assert(foo(0).mapOrElse!(v => v*2, e => 0) == 0);
Advanced usage - behavior modification
import exp = expected;
// define our Expected type using Exception as Error values
// and Throw hook, which throws when empty value or error is accessed
template Expected(T)
{
alias Expected = exp.Expected!(T, Exception, Throw);
}
// create wrappers for simplified usage of our Expected
auto ok(T)(T val) { return exp.ok!(Exception, Throw)(val); }
auto err(T)(Exception err) { return exp.err!(T, Throw)(err); }
// use it as normal
assert(ok(42) == 42);
assert(err!int(new Exception("foo")).orElse(0) == 0);
assertThrown(ok(42).error);
assertThrown(err!int(new Exception("bar")).value);
expected : (alias struct) uom_quantity_runtime_expected.Expected = expected.Expected(T, E = string, Hook = Abort) if (!is(E == void) && (isVoidValueEnabled!Hook || !is(T == void)))``Expected!(T, E) is a type that represents either success or failure.
Type T is used for success value.
If T is void, then Expected can only hold error value and is considered a success when there is no error value.
Type E is used for error value.
The default type for the error value is string.
Default behavior of Expected can be modified by the Hook template parameter.
Expected, (alias template) uom_quantity_runtime_expected.ok = expected.ok(E = string, Hook = Abort, T)(auto ref T value)Creates an Expected object from an expected value, with type inference.
ok, (alias template) uom_quantity_runtime_expected.err = expected.err(T = void, Hook = Abort, E)(auto ref E err)Creates an Expected object from an error value, with type inference.
err;
import (package) sparklessparkles.(package) sparkles.mathmath.(module) sparkles.math.vectorVector primitives for linear algebra in game and graphics code.
Provides a fixed-size numeric vector type with optional named fields,
component-wise arithmetic, scalar operations, dot product, and aliases
for common vector sizes.
vector : (alias struct) uom_quantity_runtime_expected.Vector = sparkles.math.vector.Vector(T, ulong N, string[] fieldNames = makeDefaultFieldNames!N) if (isNumeric!T && (N > 0))Fixed-size numeric vector with optional named components.
Vector;
/// The raytracer's numeric payload for a 3-vector quantity.
alias (alias) uom_quantity_runtime_expected.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])The raytracer's numeric payload for a 3-vector quantity.
Vec3 = (struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])Fixed-size numeric vector with optional named components.
Vector!(double, 3);
/// `expected` hook that keeps the results usable in `@nogc nothrow` code: a
/// result must be explicitly `ok` or `err`, never a default-constructed limbo.
struct (struct) uom_quantity_runtime_expected.NoGcHookexpected hook that keeps the results usable in @nogc nothrow code: a
result must be explicitly ok or err, never a default-constructed limbo.
NoGcHook
{
static immutable bool (immutable global) immutable(bool) uom_quantity_runtime_expected.NoGcHook.enableDefaultConstructorenableDefaultConstructor = false;
}
/// A dimension carried as a *runtime* value: an exponent vector over
/// (mass, length, time, solid-angle). Two quantities are addable iff their
/// `Dim`s are equal; `==` on the struct is the entire dimension check.
struct (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim
{
int (field) int uom_quantity_runtime_expected.Dim.massmass;
int (field) int uom_quantity_runtime_expected.Dim.lengthlength;
int (field) int uom_quantity_runtime_expected.Dim.timetime;
int (field) int uom_quantity_runtime_expected.Dim.solidAnglesolidAngle;
}
/// The group operation, component-wise: `sign = +1` for multiplication (the
/// join of two dimensions), `sign = -1` for division (the group inverse).
(struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.combine(in uom_quantity_runtime_expected.Dim a, in uom_quantity_runtime_expected.Dim b, in int sign) pure nothrow @nogc @safeThe group operation, component-wise: sign` = +1` for multiplication (the
join of two dimensions), sign = -1 for division (the group inverse).
combine(in (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim (parameter) const(uom_quantity_runtime_expected.Dim) aa, in (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim (parameter) const(uom_quantity_runtime_expected.Dim) bb, in int (parameter) const(int) signsign) @safe pure nothrow @nogc
in ((parameter) const(int) signsign == 1 || (parameter) const(int) signsign == -1)
=> (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim(
mass: (parameter) const(uom_quantity_runtime_expected.Dim) aa.(field) int uom_quantity_runtime_expected.Dim.massmass + (parameter) const(int) signsign * (parameter) const(uom_quantity_runtime_expected.Dim) bb.(field) int uom_quantity_runtime_expected.Dim.massmass,
length: (parameter) const(uom_quantity_runtime_expected.Dim) aa.(field) int uom_quantity_runtime_expected.Dim.lengthlength + (parameter) const(int) signsign * (parameter) const(uom_quantity_runtime_expected.Dim) bb.(field) int uom_quantity_runtime_expected.Dim.lengthlength,
time: (parameter) const(uom_quantity_runtime_expected.Dim) aa.(field) int uom_quantity_runtime_expected.Dim.timetime + (parameter) const(int) signsign * (parameter) const(uom_quantity_runtime_expected.Dim) bb.(field) int uom_quantity_runtime_expected.Dim.timetime,
solidAngle: (parameter) const(uom_quantity_runtime_expected.Dim) aa.(field) int uom_quantity_runtime_expected.Dim.solidAnglesolidAngle + (parameter) const(int) signsign * (parameter) const(uom_quantity_runtime_expected.Dim) bb.(field) int uom_quantity_runtime_expected.Dim.solidAnglesolidAngle,
);
/// Runtime unit label for an exponent vector (`Dim(mass: 1, time: -3)` →
/// `"kg s^-3"`). Called at runtime here — the dims are not known earlier — so
/// it may GC; that is fine off the `@nogc` checking path.
(alias) object.string = stringstring string uom_quantity_runtime_expected.unitString(in uom_quantity_runtime_expected.Dim d) pure @safeRuntime unit label for an exponent vector (Dim(mass: 1, time: -3) →
"kg s^-3"). Called at runtime here — the dims are not known earlier — so
it may GC; that is fine off the @nogc checking path.
unitString(in (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim (parameter) const(uom_quantity_runtime_expected.Dim) dd) @safe pure
{
import (package) stdstd.(module) std.convA one-stop shop for converting values from one type to another.
Category Functions Generic asOriginalType castFrom parse to toChars bitCast Strings text wtext dtext writeText writeWText writeDText hexString Numeric octal roundTo signed unsigned Exceptions ConvException ConvOverflowException
Source
std/conv.d
conv : (alias template) to = std.conv.to(T)The to template converts a value from one type _to another.
The source type is deduced and the target type must be specified, for example the
expression to!int(42.0) converts the number 42 from
double _to int. The conversion is "safe", i.e.,
it checks for overflow; to!int(4.2e10) would throw the
ConvOverflowException exception. Overflow checks are only
inserted when necessary, e.g., to!double(42) does not do
any checking because any int fits in a double.
Conversions from string _to numeric types differ from the C equivalents
atoi() and atol() by checking for overflow and not allowing whitespace.
For conversion of strings _to signed types, the grammar recognized is:
$(PRE $(I Integer):
$(I Sign UnsignedInteger)
$(I UnsignedInteger)
$(I Sign):
$(B +)
$(B -))
For conversion _to unsigned types, the grammar recognized is:
$(PRE $(I UnsignedInteger):
$(I DecimalDigit)
$(I DecimalDigit) $(I UnsignedInteger))
to;
(alias) object.string = stringstring (local variable) string resultresult;
void void uom_quantity_runtime_expected.unitString.put(in string symbol, in int exp) pure nothrow @safeput(in (alias) object.string = stringstring (parameter) const(string) symbolsymbol, in int (parameter) const(int) expexp)
{
if ((parameter) const(int) expexp == 0)
return;
if ((local variable) string resultresult.(field) ulong string.lengthlength > 0)
(local variable) string resultresult ~= ' ';
(local variable) string resultresult ~= (parameter) const(string) symbolsymbol;
if ((parameter) const(int) expexp != 1)
(local variable) string resultresult ~= "^" ~ (parameter) const(int) expexp.string std.conv.to!string.to!(const(int))(const(int) __param_0) pure nothrow @safeThe to template converts a value from one type to another.
The source type is deduced and the target type must be specified, for example the
expression to`!int(42.0)` converts the number 42 from
`double` to `int`. The conversion is "safe", i.e.,
it checks for overflow; to!int(4.2e10) would throw the
ConvOverflowException exception. Overflow checks are only
inserted when necessary, e.g., ``to!double(42) does not do
any checking because any int fits in a double.
Conversions from string to numeric types differ from the C equivalents
atoi() and atol() by checking for overflow and not allowing whitespace.
For conversion of strings to signed types, the grammar recognized is:
Integer:
Sign UnsignedInteger
UnsignedInteger
Sign:
+
-
For conversion to unsigned types, the grammar recognized is:
UnsignedInteger:
DecimalDigit
DecimalDigit UnsignedInteger
Examples
Converting a value to its own type (useful mostly for generic code)
simply returns its argument.
int a = 42;
int b = to!int(a);
double c = to!double(3.14); // c is double with value 3.14
Converting among numeric types is a safe way to cast them around.
Conversions from floating-point types to integral types allow loss of
precision (the fractional part of a floating-point number). The
conversion is truncating towards zero, the same way a cast would
truncate. (To round a floating point value when casting to an
integral, use roundTo.)
import std.exception : assertThrown;
int a = 420;
assert(to!long(a) == a);
assertThrown!ConvOverflowException(to!byte(a));
assert(to!int(4.2e6) == 4200000);
assertThrown!ConvOverflowException(to!uint(-3.14));
assert(to!uint(3.14) == 3);
assert(to!uint(3.99) == 3);
assert(to!int(-3.99) == -3);
When converting strings to numeric types, note that D hexadecimal and binary
literals are not handled. Neither the prefixes that indicate the base, nor the
horizontal bar used to separate groups of digits are recognized. This also
applies to the suffixes that indicate the type.
To work around this, you can specify a radix for conversions involving numbers.
auto str = to!string(42, 16);
assert(str == "2A");
auto i = to!int(str, 16);
assert(i == 42);
Conversions from integral types to floating-point types always
succeed, but might lose accuracy. The largest integers with a
predecessor representable in floating-point format are 2^24-1 for
float, 2^53-1 for double, and 2^64-1 for real (when
real is 80-bit, e.g. on Intel machines).
// 2^24 - 1, largest proper integer representable as float
int a = 16_777_215;
assert(to!int(to!float(a)) == a);
assert(to!int(to!float(-a)) == -a);
Conversion from string types to char types enforces the input
to consist of a single code point, and said code point must
fit in the target type. Otherwise, ConvException is thrown.
import std.exception : assertThrown;
assert(to!char("a") == 'a');
assertThrown(to!char("ñ")); // 'ñ' does not fit into a char
assert(to!wchar("ñ") == 'ñ');
assertThrown(to!wchar("😃")); // '😃' does not fit into a wchar
assert(to!dchar("😃") == '😃');
// Using wstring or dstring as source type does not affect the result
assert(to!char("a"w) == 'a');
assert(to!char("a"d) == 'a');
// Two code points cannot be converted to a single one
assertThrown(to!char("ab"));
Converting an array to another array type works by converting each
element in turn. Associative arrays can be converted to associative
arrays as long as keys and values can in turn be converted.
import std.string : split;
int[] a = [1, 2, 3];
auto b = to!(float[])(a);
assert(b == [1.0f, 2, 3]);
string str = "1 2 3 4 5 6";
auto numbers = to!(double[])(split(str));
assert(numbers == [1.0, 2, 3, 4, 5, 6]);
int[string] c;
c["a"] = 1;
c["b"] = 2;
auto d = to!(double[wstring])(c);
assert(d["a"w] == 1 && d["b"w] == 2);
Conversions operate transitively, meaning that they work on arrays and
associative arrays of any complexity.
This conversion works because to`!short` applies to an `int`, to!wstring
applies to a string, to`!string` applies to a `double`, and
to!(double[]) applies to an int[]. The conversion might throw an
exception because ``to!short might fail the range check.
int[string][double[int[]]] a;
auto b = to!(short[wstring][string[double[]]])(a);
Object-to-object conversions by dynamic casting throw exception when
the source is non-null and the target is null.
import std.exception : assertThrown;
// Testing object conversions
class A {}
class B : A {}
class C : A {}
A a1 = new A, a2 = new B, a3 = new C;
assert(to!B(a2) is a2);
assert(to!C(a3) is a3);
assertThrown!ConvException(to!B(a3));
Stringize conversion from all types is supported.
String to string conversion works for any two string types having
(char, wchar, dchar) character widths and any
combination of qualifiers (mutable, const, or immutable).
Converts array (other than strings) to string.
Each element is converted by calling ``to!T.
Associative array to string conversion.
Each element is converted by calling ``to!T.
Object to string conversion calls toString against the object or
returns "null" if the object is null.
Struct to string conversion calls toString against the struct if
it is defined.
For structs that do not define toString, the conversion to string
produces the list of fields.
Enumerated types are converted to strings as their symbolic names.
Boolean values are converted to "true" or "false".
char, wchar, dchar to a string type.
Unsigned or signed integers to strings.
: Convert integral value to string in radix radix.
radix must be a value from 2 to 36.
value is treated as a signed value only if radix is 10.
The characters A through Z are used to represent values 10 through 36
and their case is determined by the letterCase parameter.
All floating point types to all string types.
Pointer to string conversions convert the pointer to a size_t value.
If pointer is char*, treat it as C-style strings.
In that case, this function is @system.
See formatValue on how toString should be defined.
// Conversion representing dynamic/static array with string
long[] a = [ 1, 3, 5 ];
assert(to!string(a) == "[1, 3, 5]");
// Conversion representing associative array with string
int[string] associativeArray = ["0":1, "1":2];
assert(to!string(associativeArray) == `["0":1, "1":2]` ||
to!string(associativeArray) == `["1":2, "0":1]`);
// char* to string conversion
assert(to!string(cast(char*) null) == "");
assert(to!string("foo\0".ptr) == "foo");
// Conversion reinterpreting void array to string
auto w = "abcx"w;
const(void)[] b = w;
assert(b.length == 8);
auto c = to!(wchar[])(b);
assert(c == "abcx");
Strings can be converted to enum types. The enum member with the same name as the
input string is returned. The comparison is case-sensitive.
A ConvException is thrown if the enum does not have the specified member.
import std.exception : assertThrown;
enum E { a, b, c }
assert(to!E("a") == E.a);
assert(to!E("b") == E.b);
assertThrown!ConvException(to!E("A"));
to!(alias) object.string = stringstring;
}
void uom_quantity_runtime_expected.unitString.put(in string symbol, in int exp) pure nothrow @safeput("kg", (parameter) const(uom_quantity_runtime_expected.Dim) dd.(field) int uom_quantity_runtime_expected.Dim.massmass);
void uom_quantity_runtime_expected.unitString.put(in string symbol, in int exp) pure nothrow @safeput("m", (parameter) const(uom_quantity_runtime_expected.Dim) dd.(field) int uom_quantity_runtime_expected.Dim.lengthlength);
void uom_quantity_runtime_expected.unitString.put(in string symbol, in int exp) pure nothrow @safeput("s", (parameter) const(uom_quantity_runtime_expected.Dim) dd.(field) int uom_quantity_runtime_expected.Dim.timetime);
void uom_quantity_runtime_expected.unitString.put(in string symbol, in int exp) pure nothrow @safeput("sr", (parameter) const(uom_quantity_runtime_expected.Dim) dd.(field) int uom_quantity_runtime_expected.Dim.solidAnglesolidAngle);
return (local variable) string resultresult.(field) ulong string.lengthlength > 0 ? (local variable) string resultresult : "(dimensionless)";
}
/// A dimension mismatch: the two operands' dimensions, plus a fixed message.
/// It carries no heap data, so constructing one stays `@nogc nothrow`.
struct (struct) uom_quantity_runtime_expected.DimErrorA dimension mismatch: the two operands' dimensions, plus a fixed message.
It carries no heap data, so constructing one stays @nogc nothrow.
DimError
{
(struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim (field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.DimError.havethe left operand's dimension
have; /// the left operand's dimension
(struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim (field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.DimError.wantthe right operand's dimension (what have was required to match)
want; /// the right operand's dimension (what `have` was required to match)
(alias) object.string = stringstring (field) string uom_quantity_runtime_expected.DimError.messagestatic, GC-free
message = "operands have incompatible dimensions"; /// static, GC-free
/// A human-readable rendering (GC-allocating via `unitString`; used only
/// on the reporting path, never inside `@nogc` arithmetic).
(alias) object.string = stringstring string uom_quantity_runtime_expected.DimError.describe() const pure @safeA human-readable rendering (GC-allocating via unitString; used only
on the reporting path, never inside @nogc arithmetic).
describe() const @safe pure
{
import (package) stdstd.(module) std.formatThis package provides string formatting functionality using
printf style format strings.
Submodule Function Name Description package format Converts its arguments according to a format string into a string.
| package |
sformat |
Converts its arguments according to a format string into a buffer. |
| package |
FormatException |
Signals a problem while formatting. |
| write |
formattedWrite |
Converts its arguments according to a format string and writes
the result to an output range. |
| write |
formatValue |
Formats a value of any type according to a format specifier and
writes the result to an output range. |
| read |
formattedRead |
Reads an input range according to a format string and stores the read
values into its arguments. |
| read |
unformatValue |
Reads a value from the given input range and converts it according to
a format specifier. |
| spec |
FormatSpec |
A general handler for format strings. |
| spec |
singleSpec |
Helper function that returns a FormatSpec for a single format specifier. |
Limitation
This package does not support localization, but
adheres to the rounding mode of the floating point unit, if
available.
Format Strings
The functions contained in this package use format strings. A
format string describes the layout of another string for reading or
writing purposes. A format string is composed of normal text
interspersed with format specifiers. A format specifier starts
with a percentage sign '%', optionally followed by one or more
parameters and ends with a format indicator. A format
indicator may be a simple format character or a compound
indicator.
Format strings are composed according to the following grammar:
FormatString:
FormatStringItem FormatString
FormatStringItem:
Character
FormatSpecifier
FormatSpecifier:
'%' Parameters FormatIndicator
FormatIndicator:
FormatCharacter
CompoundIndicator
FormatCharacter:
see remark below
CompoundIndicator:
'(' FormatString '%)'
'(' FormatString '%|' Delimiter '%)'
Delimiter
empty
Character Delimiter
Parameters:
Position Flags Width Precision Separator
Position:
empty
Integer '$'**
*Integer* **':'** *Integer* **'$'
Integer ':' '$'**
*Flags*:
*empty*
*Flag* *Flags*
*Flag*:
**'-'**|**'+'**|**' '**|**'0'**|**'#'**|**'='**
*Width*:
*OptionalPositionalInteger*
*Precision*:
*empty*
**'.'** *OptionalPositionalInteger*
*Separator*:
*empty*
**','** *OptionalInteger*
**','** *OptionalInteger* **'?'**
*OptionalInteger*:
*empty*
*Integer*
**'*'**
*OptionalPositionalInteger*:
*OptionalInteger*
**'*'** *Integer* **'$'
Character
'%%'
AnyCharacterExceptPercent
Integer:
NonZeroDigit Digits
Digits:
empty
Digit Digits
NonZeroDigit:
'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'
Digit:
'0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'
Note
FormatCharacter is unspecified. It can be any character
that has no other purpose in this grammar, but it is
recommended to assign (lower- and uppercase) letters.
Note
The Parameters of a CompoundIndicator are currently
limited to a '-' flag.
Format Indicator
The format indicator can either be a single character or an
expression surrounded by '%(' and '%)'. It specifies the
basic manner in which a value will be formatted and is the minimum
requirement to format a value.
The following characters can be used as format characters:
FormatCharacter Semantics 's' To be formatted in a human readable format. Can be used with all types. 'c' To be formatted as a character. 'd' To be formatted as a signed decimal integer. 'u' To be formatted as a decimal image of the underlying bit representation. 'b' To be formatted as a binary image of the underlying bit representation. 'o' To be formatted as an octal image of the underlying bit representation. 'x' / 'X' To be formatted as a hexadecimal image of the underlying bit representation. 'e' / 'E' To be formatted as a real number in decimal scientific notation. 'f' / 'F' To be formatted as a real number in decimal natural notation. 'g' / 'G' To be formatted as a real number in decimal short notation. Depending on the number, a scientific notation or a natural notation is used. 'a' / 'A' To be formatted as a real number in hexadecimal scientific notation. 'r' To be formatted as raw bytes. The output may not be printable and depends on endianness.
The compound indicator can be used to describe compound types
like arrays or structs in more detail. A compound type is enclosed
within '%(' and '%)'. The enclosed sub-format string is
applied to individual elements. The trailing portion of the
sub-format string following the specifier for the element is
interpreted as the delimiter, and is therefore omitted following the
last element. The '%|' specifier may be used to explicitly
indicate the start of the delimiter, so that the preceding portion of
the string will be included following the last element.
The format string inside of the compound indicator should
contain exactly one format specifier (two in case of associative
arrays), which specifies the formatting mode of the elements of the
compound type. This format specifier can be a compound
indicator itself.
Note
Inside a compound indicator, strings and characters are
escaped automatically. To avoid this behavior, use "%-("
instead of "%(".
Flags
There are several flags that affect the outcome of the formatting.
Flag Semantics '-' When the formatted result is shorter than the value given by the width parameter, the output is left justified. Without the '-' flag, the output remains right justified.
There are two exceptions where the '-' flag has a
different meaning: (1) with 'r' it denotes to use little
endian and (2) in case of a compound indicator it means that
no special handling of the members is applied. |
| '=' |
When the formatted result is shorter than the value
given by the width parameter, the output is centered.
If the central position is not possible it is moved slightly
to the right. In this case, if '-' flag is present in
addition to the '=' flag, it is moved slightly to the left. |
| '+' / *' '* |
Applies to numerical values. By default, positive numbers are not
formatted to include the + sign. With one of these two flags present,
positive numbers are preceded by a plus sign or a space.
When both flags are present, a plus sign is used.
In case of 'r', a big endian format is used. |
| '0' |
Is applied to numerical values that are printed right justified.
If the zero flag is present, the space left to the number is
filled with zeros instead of spaces. |
| '#' |
Denotes that an alternative output must be used. This depends on the type
to be formatted and the format character used. See the
sections below for more information. |
Width, Precision and Separator
The width parameter specifies the minimum width of the result.
The meaning of precision depends on the format indicator. For
integers it denotes the minimum number of digits printed, for
real numbers it denotes the number of fractional digits and for
strings and compound types it denotes the maximum number of elements
that are included in the output.
A separator is used for formatting numbers. If it is specified,
the output is divided into chunks of three digits, separated by a ','. The number of digits in a chunk can be given explicitly by
providing a number or a ''* after the ','.
In all three cases the number of digits can be replaced by a ''*. In this scenario, the next argument is used as the number of
digits. If the argument is a negative number, the precision and
separator parameters are considered unspecified. For width,
the absolute value is used and the '-' flag is set.
The separator can also be followed by a '?'. In that case,
an additional argument is used to specify the symbol that should be
used to separate the chunks.
Position
By default, the arguments are processed in the provided order. With
the position parameter it is possible to address arguments
directly. It is also possible to denote a series of arguments with
two numbers separated by ':', that are all processed in the same
way. The second number can be omitted. In that case the series ends
with the last argument.
It's also possible to use positional arguments for width, precision and separator by adding a number and a '$' after the ''*.
Types
This section describes the result of combining types with format
characters. It is organized in 2 subsections: a list of general
information regarding the formatting of types in the presence of
format characters and a table that contains details for every
available combination of type and format character.
When formatting types, the following rules apply:
If the format character is upper case, the resulting string will
be formatted using upper case letters.
The default precision for floating point numbers is 6 digits.
Rounding of floating point numbers adheres to the rounding mode
of the floating point unit, if available.
The floating point values NaN and Infinity are formatted as
nan and inf, possibly preceded by '+' or '-' sign.
Formatting reals is only supported for 64 bit reals and 80 bit reals.
All other reals are cast to double before they are formatted. This will
cause the result to be inf for very large numbers.
Characters and strings formatted with the 's' format character
inside of compound types are surrounded by single and double quotes
and unprintable characters are escaped. To avoid this, a '-'
flag can be specified for the compound specifier
(e.g. "%-(%s%)" instead of "%(%s%)" ).
Structs, unions, classes and interfaces are formatted by calling a
toString method if available.
See module std.format.write for more
details.
Only part of these combinations can be used for reading. See
module std.format.read for more
detailed information.
This table contains descriptions for every possible combination of
type and format character:
<th scope="col" width="20%">Type</th> <th scope="col" width="20%">Format Character</th> Formatted as... <td rowspan="1">null</td> 's' null
|<td rowspan="3">bool</td> 's' |
false or true |
| 'b', 'd', 'o', 'u', 'x', 'X' |
As the integrals 0 or 1 with the same format character.
Please note, that 'o' and 'x' with '#' flag
might produce unexpected results due to special handling of
the value 0. |
| 'r' |
\0 or \1 |
|<td rowspan="4">Integral</td> 's', 'd' |
A signed decimal number. The '#' flag is ignored. |
| 'b', 'o', 'u', 'x', 'X' |
An unsigned binary, decimal, octal or hexadecimal number.
In case of 'o' and 'x', the '#' flag
denotes that the number must be preceded by 0 and 0x, with
the exception of the value 0, where this does not apply. For
'b' and 'u' the '#' flag has no effect. |
| 'e', 'E', 'f', 'F', 'g', 'G', 'a', 'A' |
As a floating point value with the same specifier.
Default precision is large enough to add all digits
of the integral value.
In case of 'a' and 'A', the integral digit can be
any hexadecimal digit.
|
| 'r' |
Characters taken directly from the binary representation. |
|<td rowspan="5">Floating Point</td> 'e', 'E' |
Scientific notation: Exactly one integral digit followed by a dot
and fractional digits, followed by the exponent.
The exponent is formatted as 'e' followed by
a '+' or '-' sign, followed by at least
two digits.
When there are no fractional digits and the '#' flag
is not present, the dot is omitted. |
| 'f', 'F' |
Natural notation: Integral digits followed by a dot and
fractional digits.
When there are no fractional digits and the '#' flag
is not present, the dot is omitted.
Please note: the difference between 'f' and 'F'
is only visible for NaN and Infinity. |
| 's', 'g', 'G' |
Short notation: If the absolute value is larger than 10 ^^ precision
or smaller than 0.0001, the scientific notation is used.
If not, the natural notation is applied.
In both cases precision denotes the count of all digits, including
the integral digits. Trailing zeros (including a trailing dot) are removed.
If '#' flag is present, trailing zeros are not removed. |
| 'a', 'A' |
Hexadecimal scientific notation: 0x followed by 1
(or 0 in case of value zero or denormalized number)
followed by a dot, fractional digits in hexadecimal
notation and an exponent. The exponent is build by p,
followed by a sign and the exponent in decimal notation.
When there are no fractional digits and the '#' flag
is not present, the dot is omitted. |
| 'r' |
Characters taken directly from the binary representation. |
|<td rowspan="3">Character</td> 's', 'c' |
As the character.
Inside of a compound indicator 's' is treated differently: The
character is surrounded by single quotes and non printable
characters are escaped. This can be avoided by preceding
the compound indicator with a '-' flag
(e.g. "%-(%s%)"). |
| 'b', 'd', 'o', 'u', 'x', 'X' |
As the integral that represents the character. |
| 'r' |
Characters taken directly from the binary representation. |
|<td rowspan="3">String</td> 's' |
The sequence of characters that form the string.
Inside of a compound indicator the string is surrounded by double quotes
and non printable characters are escaped. This can be avoided
by preceding the compound indicator with a '-' flag
(e.g. "%-(%s%)"). |
| 'r' |
The sequence of characters, each formatted with 'r'. |
| compound |
As an array of characters. |
|<td rowspan="3">Array</td> 's' |
When the elements are characters, the array is formatted as
a string. In all other cases the array is surrounded by square brackets
and the elements are separated by a comma and a space. If the elements
are strings, they are surrounded by double quotes and non
printable characters are escaped. |
| 'r' |
The sequence of the elements, each formatted with 'r'. |
| compound |
The sequence of the elements, each formatted according to the specifications
given inside of the compound specifier. |
|<td rowspan="2">Associative Array</td> 's' |
As a sequence of the elements in unpredictable order. The output is
surrounded by square brackets. The elements are separated by a
comma and a space. The elements are formatted as key:value. |
| compound |
As a sequence of the elements in unpredictable order. Each element
is formatted according to the specifications given inside of the
compound specifier. The first specifier is used for formatting
the key and the second specifier is used for formatting the value.
The order can be changed with positional arguments. For example
"%(%2$s (%1$s), %)" will write the value, followed by the key in
parenthesis. |
|<td rowspan="2">Enum</td> 's' |
The name of the value. If the name is not available, the base value
is used, preceeded by a cast. |
| All, but 's' |
Enums can be formatted with all format characters that can be used
with the base value. In that case they are formatted like the base value. |
|<td rowspan="3">Input Range</td> 's' |
When the elements of the range are characters, they are written like a string.
In all other cases, the elements are enclosed by square brackets and separated
by a comma and a space. |
| 'r' |
The sequence of the elements, each formatted with 'r'. |
| compound |
The sequence of the elements, each formatted according to the specifications
given inside of the compound specifier. |
|<td rowspan="1">Struct</td> 's' |
When the struct has neither an applicable toString
nor is an input range, it is formatted as follows:
StructType(field1, field2, ...). |
|<td rowspan="1">Class</td> 's' |
When the class has neither an applicable toString
nor is an input range, it is formatted as the
fully qualified name of the class. |
|<td rowspan="1">Union</td> 's' |
When the union has neither an applicable toString
nor is an input range, it is formatted as its base name. |
|<td rowspan="2">Pointer</td> 's' |
A null pointer is formatted as 'null'. All other pointers are
formatted as hexadecimal numbers with the format character 'X'. |
| 'x', 'X' |
Formatted as a hexadecimal number. |
|<td rowspan="3">SIMD vector</td> 's' |
The array is surrounded by square brackets
and the elements are separated by a comma and a space. |
| 'r' |
The sequence of the elements, each formatted with 'r'. |
| compound |
The sequence of the elements, each formatted according to the specifications
given inside of the compound specifier. |
|<td rowspan="1">Delegate</td> 's', 'r', compound |
As the .stringof of this delegate treated as a string.
Please note: The implementation is currently buggy
and its use is discouraged. |
Source
std/format/package.d
Examples
Simple use:
// Easiest way is to use `%s` everywhere:
assert(format("I got %s %s for %s euros.", 30, "eggs", 5.27) == "I got 30 eggs for 5.27 euros.");
// Other format characters provide more control:
assert(format("I got %b %(%X%) for %f euros.", 30, "eggs", 5.27) == "I got 11110 65676773 for 5.270000 euros.");
Compound specifiers allow formatting arrays and other compound types:
/*
The trailing end of the sub-format string following the specifier for
each item is interpreted as the array delimiter, and is therefore
omitted following the last array item:
*/
assert(format("My items are %(%s %).", [1,2,3]) == "My items are 1 2 3.");
assert(format("My items are %(%s, %).", [1,2,3]) == "My items are 1, 2, 3.");
/*
The "%|" delimiter specifier may be used to indicate where the
delimiter begins, so that the portion of the format string prior to
it will be retained in the last array element:
*/
assert(format("My items are %(-%s-%|, %).", [1,2,3]) == "My items are -1-, -2-, -3-.");
/*
These compound format specifiers may be nested in the case of a
nested array argument:
*/
auto mat = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
assert(format("%(%(%d %) - %)", mat), "1 2 3 - 4 5 6 - 7 8 9");
assert(format("[%(%(%d %) - %)]", mat), "[1 2 3 - 4 5 6 - 7 8 9]");
assert(format("[%([%(%d %)]%| - %)]", mat), "[1 2 3] - [4 5 6] - [7 8 9]");
/*
Strings and characters are escaped automatically inside compound
format specifiers. To avoid this behavior, use "%-(" instead of "%(":
*/
assert(format("My friends are %s.", ["John", "Nancy"]) == `My friends are ["John", "Nancy"].`);
assert(format("My friends are %(%s, %).", ["John", "Nancy"]) == `My friends are "John", "Nancy".`);
assert(format("My friends are %-(%s, %).", ["John", "Nancy"]) == `My friends are John, Nancy.`);
Using parameters:
// Flags can be used to influence to outcome:
assert(format("%g != %+#g", 3.14, 3.14) == "3.14 != +3.14000");
// Width and precision help to arrange the formatted result:
assert(format(">%10.2f<", 1234.56789) == "> 1234.57<");
// Numbers can be grouped:
assert(format("%,4d", int.max) == "21,4748,3647");
// It's possible to specify the position of an argument:
assert(format("%3$s %1$s", 3, 17, 5) == "5 3");
Providing parameters as arguments:
// Width as argument
assert(format(">%*s<", 10, "abc") == "> abc<");
// Precision as argument
assert(format(">%.*f<", 5, 123.2) == ">123.20000<");
// Grouping as argument
assert(format("%,*d", 1, int.max) == "2,1,4,7,4,8,3,6,4,7");
// Grouping separator as argument
assert(format("%,3?d", '_', int.max) == "2_147_483_647");
// All at once
assert(format("%*.*,*?d", 20, 15, 6, '/', int.max) == " 000/002147/483647");
format : (alias template) format = std.format.format(Char, Args...)(in Char[] fmt, Args args) if (isSomeChar!Char)Converts its arguments according to a format string into a string.
The second version of format takes the format string as template
argument. In this case, it is checked for consistency at
compile-time and produces slightly faster code, because the length of
the output buffer can be estimated in advance.
Params:
fmt = a $(MREF_ALTTEXT format string, std,format)
args = a variadic list of arguments to be formatted
Char = character type of fmt
Args = a variadic list of types of the arguments
Returns:
The formatted string.
Throws:
A $(LREF FormatException) if formatting did not succeed.
See_Also:
$(LREF sformat) for a variant, that tries to avoid garbage collection.
format;
return string std.format.format!("%s: %s vs %s", string, string, string)(string __param_0, string __param_1, string __param_2) pure @safeExamples
The format string can be checked at compile-time:
auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");
// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format!"%s: %s vs %s"((field) string uom_quantity_runtime_expected.DimError.messagestatic, GC-free
message, (field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.DimError.havethe left operand's dimension
have.string uom_quantity_runtime_expected.unitString(in uom_quantity_runtime_expected.Dim d) pure @safeRuntime unit label for an exponent vector (Dim(mass: 1, time: -3) →
"kg s^-3"). Called at runtime here — the dims are not known earlier — so
it may GC; that is fine off the @nogc checking path.
unitString, (field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.DimError.wantthe right operand's dimension (what have was required to match)
want.string uom_quantity_runtime_expected.unitString(in uom_quantity_runtime_expected.Dim d) pure @safeRuntime unit label for an exponent vector (Dim(mass: 1, time: -3) →
"kg s^-3"). Called at runtime here — the dims are not known earlier — so
it may GC; that is fine off the @nogc checking path.
unitString);
}
}
/// `Expected!(T, DimError)` with the `@nogc`-friendly hook baked in. A fallible
/// operation returns `DimExpected!RQuantity`; the caller inspects `hasValue` /
/// `hasError` rather than catching an exception.
alias (alias) uom_quantity_runtime_expected.DimExpected!(uom_quantity_runtime_expected.RQuantity) = expected.Expected!(RQuantity, DimError, NoGcHook)Expected!(T, DimError) with the @nogc-friendly hook baked in. A fallible
operation returns ``DimExpected!RQuantity; the caller inspects hasValue /
hasError rather than catching an exception.
DimExpected(T) = (struct) expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook)``Expected!(T, E) is a type that represents either success or failure.
Type T is used for success value.
If T is void, then Expected can only hold error value and is considered a success when there is no error value.
Type E is used for error value.
The default type for the error value is string.
Default behavior of Expected can be modified by the Hook template parameter.
Expected!(T, (struct) uom_quantity_runtime_expected.DimErrorA dimension mismatch: the two operands' dimensions, plus a fixed message.
It carries no heap data, so constructing one stays @nogc nothrow.
DimError, (struct) uom_quantity_runtime_expected.NoGcHookexpected hook that keeps the results usable in @nogc nothrow code: a
result must be explicitly ok or err, never a default-constructed limbo.
NoGcHook);
/// A quantity whose dimension is a *runtime* field, not a type parameter. Two
/// distinct dimensions inhabit the *same* type `RQuantity` — the distinction is
/// data, checked when the values meet.
struct (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity
{
double (field) double uom_quantity_runtime_expected.RQuantity.valuevalue;
(struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim (field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim;
/// `+`/`-`: fallible. Same `dim` → `ok`; different `dim` → `err` (no throw).
(alias) uom_quantity_runtime_expected.DimExpected!(uom_quantity_runtime_expected.RQuantity) = expected.Expected!(RQuantity, DimError, NoGcHook)Expected!(T, DimError) with the @nogc-friendly hook baked in. A fallible
operation returns ``DimExpected!RQuantity; the caller inspects hasValue /
hasError rather than catching an exception.
DimExpected!(struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity expected.Expected!(RQuantity, DimError, NoGcHook) uom_quantity_runtime_expected.RQuantity.add(in uom_quantity_runtime_expected.RQuantity rhs) const pure nothrow @nogc @safe+/-: fallible. Same dim → ok; different dim → err (no throw).
add(in (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity (parameter) const(uom_quantity_runtime_expected.RQuantity) rhsrhs) const @safe pure nothrow @nogc
{
if ((field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim != (parameter) const(uom_quantity_runtime_expected.RQuantity) rhsrhs.(field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim)
return expected.Expected!(RQuantity, DimError, NoGcHook) expected.err!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.NoGcHook, uom_quantity_runtime_expected.DimError)(uom_quantity_runtime_expected.DimError err) pure nothrow @nogc @safeCreates an Expected object from an error value, with type inference.
Examples
// implicit void value type
{
auto res = err("foo");
static assert(is(typeof(res) == Expected!(void, string)));
assert(!res);
assert(res.error == "foo");
}
// bool
{
auto res = err!int("42");
static assert(is(typeof(res) == Expected!(int, string)));
assert(!res);
assert(res.error == "42");
}
// other error type
{
auto res = err!bool(42);
static assert(is(typeof(res) == Expected!(bool, int)));
assert(!res);
assert(res.error == 42);
}
err!((struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity, (struct) uom_quantity_runtime_expected.NoGcHookexpected hook that keeps the results usable in @nogc nothrow code: a
result must be explicitly ok or err, never a default-constructed limbo.
NoGcHook)((struct) uom_quantity_runtime_expected.DimErrorA dimension mismatch: the two operands' dimensions, plus a fixed message.
It carries no heap data, so constructing one stays @nogc nothrow.
DimError((field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim, (parameter) const(uom_quantity_runtime_expected.RQuantity) rhsrhs.(field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim));
return expected.Expected!(RQuantity, DimError, NoGcHook) expected.ok!(uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook, uom_quantity_runtime_expected.RQuantity)(uom_quantity_runtime_expected.RQuantity value) pure nothrow @nogc @safeCreates an Expected object from an expected value, with type inference.
ok!((struct) uom_quantity_runtime_expected.DimErrorA dimension mismatch: the two operands' dimensions, plus a fixed message.
It carries no heap data, so constructing one stays @nogc nothrow.
DimError, (struct) uom_quantity_runtime_expected.NoGcHookexpected hook that keeps the results usable in @nogc nothrow code: a
result must be explicitly ok or err, never a default-constructed limbo.
NoGcHook)((struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity((field) double uom_quantity_runtime_expected.RQuantity.valuevalue + (parameter) const(uom_quantity_runtime_expected.RQuantity) rhsrhs.(field) double uom_quantity_runtime_expected.RQuantity.valuevalue, (field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim));
}
/// ditto for subtraction.
(alias) uom_quantity_runtime_expected.DimExpected!(uom_quantity_runtime_expected.RQuantity) = expected.Expected!(RQuantity, DimError, NoGcHook)Expected!(T, DimError) with the @nogc-friendly hook baked in. A fallible
operation returns ``DimExpected!RQuantity; the caller inspects hasValue /
hasError rather than catching an exception.
DimExpected!(struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity expected.Expected!(RQuantity, DimError, NoGcHook) uom_quantity_runtime_expected.RQuantity.sub(in uom_quantity_runtime_expected.RQuantity rhs) const pure nothrow @nogc @safeditto for subtraction.
sub(in (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity (parameter) const(uom_quantity_runtime_expected.RQuantity) rhsrhs) const @safe pure nothrow @nogc
{
if ((field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim != (parameter) const(uom_quantity_runtime_expected.RQuantity) rhsrhs.(field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim)
return expected.Expected!(RQuantity, DimError, NoGcHook) expected.err!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.NoGcHook, uom_quantity_runtime_expected.DimError)(uom_quantity_runtime_expected.DimError err) pure nothrow @nogc @safeCreates an Expected object from an error value, with type inference.
Examples
// implicit void value type
{
auto res = err("foo");
static assert(is(typeof(res) == Expected!(void, string)));
assert(!res);
assert(res.error == "foo");
}
// bool
{
auto res = err!int("42");
static assert(is(typeof(res) == Expected!(int, string)));
assert(!res);
assert(res.error == "42");
}
// other error type
{
auto res = err!bool(42);
static assert(is(typeof(res) == Expected!(bool, int)));
assert(!res);
assert(res.error == 42);
}
err!((struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity, (struct) uom_quantity_runtime_expected.NoGcHookexpected hook that keeps the results usable in @nogc nothrow code: a
result must be explicitly ok or err, never a default-constructed limbo.
NoGcHook)((struct) uom_quantity_runtime_expected.DimErrorA dimension mismatch: the two operands' dimensions, plus a fixed message.
It carries no heap data, so constructing one stays @nogc nothrow.
DimError((field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim, (parameter) const(uom_quantity_runtime_expected.RQuantity) rhsrhs.(field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim));
return expected.Expected!(RQuantity, DimError, NoGcHook) expected.ok!(uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook, uom_quantity_runtime_expected.RQuantity)(uom_quantity_runtime_expected.RQuantity value) pure nothrow @nogc @safeCreates an Expected object from an expected value, with type inference.
ok!((struct) uom_quantity_runtime_expected.DimErrorA dimension mismatch: the two operands' dimensions, plus a fixed message.
It carries no heap data, so constructing one stays @nogc nothrow.
DimError, (struct) uom_quantity_runtime_expected.NoGcHookexpected hook that keeps the results usable in @nogc nothrow code: a
result must be explicitly ok or err, never a default-constructed limbo.
NoGcHook)((struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity((field) double uom_quantity_runtime_expected.RQuantity.valuevalue - (parameter) const(uom_quantity_runtime_expected.RQuantity) rhsrhs.(field) double uom_quantity_runtime_expected.RQuantity.valuevalue, (field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim));
}
/// `*`: *total* — any two dimensions combine, so it returns an `RQuantity`
/// directly (never an `err`). `Length · Length` → an area, and so on.
(struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity uom_quantity_runtime_expected.RQuantity uom_quantity_runtime_expected.RQuantity.mul(in uom_quantity_runtime_expected.RQuantity rhs) const pure nothrow @nogc @safe*: total — any two dimensions combine, so it returns an RQuantity
directly (never an err). Length · Length → an area, and so on.
mul(in (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity (parameter) const(uom_quantity_runtime_expected.RQuantity) rhsrhs) const @safe pure nothrow @nogc
=> (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity((field) double uom_quantity_runtime_expected.RQuantity.valuevalue * (parameter) const(uom_quantity_runtime_expected.RQuantity) rhsrhs.(field) double uom_quantity_runtime_expected.RQuantity.valuevalue, uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.combine(in uom_quantity_runtime_expected.Dim a, in uom_quantity_runtime_expected.Dim b, in int sign) pure nothrow @nogc @safeThe group operation, component-wise: sign` = +1` for multiplication (the
join of two dimensions), sign = -1 for division (the group inverse).
combine((field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim, (parameter) const(uom_quantity_runtime_expected.RQuantity) rhsrhs.(field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim, 1));
/// ditto for division (the group inverse of the right dimension).
(struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity uom_quantity_runtime_expected.RQuantity uom_quantity_runtime_expected.RQuantity.div(in uom_quantity_runtime_expected.RQuantity rhs) const pure nothrow @nogc @safeditto for division (the group inverse of the right dimension).
div(in (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity (parameter) const(uom_quantity_runtime_expected.RQuantity) rhsrhs) const @safe pure nothrow @nogc
=> (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity((field) double uom_quantity_runtime_expected.RQuantity.valuevalue / (parameter) const(uom_quantity_runtime_expected.RQuantity) rhsrhs.(field) double uom_quantity_runtime_expected.RQuantity.valuevalue, uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.combine(in uom_quantity_runtime_expected.Dim a, in uom_quantity_runtime_expected.Dim b, in int sign) pure nothrow @nogc @safeThe group operation, component-wise: sign` = +1` for multiplication (the
join of two dimensions), sign = -1 for division (the group inverse).
combine((field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim, (parameter) const(uom_quantity_runtime_expected.RQuantity) rhsrhs.(field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim, -1));
/// Render as `value unit` with the dimension resolved at runtime.
(alias) object.string = stringstring string uom_quantity_runtime_expected.RQuantity.toString() const pure @safeRender as value unit with the dimension resolved at runtime.
toString() const @safe pure
{
import (package) stdstd.(module) std.formatThis package provides string formatting functionality using
printf style format strings.
Submodule Function Name Description package format Converts its arguments according to a format string into a string.
| package |
sformat |
Converts its arguments according to a format string into a buffer. |
| package |
FormatException |
Signals a problem while formatting. |
| write |
formattedWrite |
Converts its arguments according to a format string and writes
the result to an output range. |
| write |
formatValue |
Formats a value of any type according to a format specifier and
writes the result to an output range. |
| read |
formattedRead |
Reads an input range according to a format string and stores the read
values into its arguments. |
| read |
unformatValue |
Reads a value from the given input range and converts it according to
a format specifier. |
| spec |
FormatSpec |
A general handler for format strings. |
| spec |
singleSpec |
Helper function that returns a FormatSpec for a single format specifier. |
Limitation
This package does not support localization, but
adheres to the rounding mode of the floating point unit, if
available.
Format Strings
The functions contained in this package use format strings. A
format string describes the layout of another string for reading or
writing purposes. A format string is composed of normal text
interspersed with format specifiers. A format specifier starts
with a percentage sign '%', optionally followed by one or more
parameters and ends with a format indicator. A format
indicator may be a simple format character or a compound
indicator.
Format strings are composed according to the following grammar:
FormatString:
FormatStringItem FormatString
FormatStringItem:
Character
FormatSpecifier
FormatSpecifier:
'%' Parameters FormatIndicator
FormatIndicator:
FormatCharacter
CompoundIndicator
FormatCharacter:
see remark below
CompoundIndicator:
'(' FormatString '%)'
'(' FormatString '%|' Delimiter '%)'
Delimiter
empty
Character Delimiter
Parameters:
Position Flags Width Precision Separator
Position:
empty
Integer '$'**
*Integer* **':'** *Integer* **'$'
Integer ':' '$'**
*Flags*:
*empty*
*Flag* *Flags*
*Flag*:
**'-'**|**'+'**|**' '**|**'0'**|**'#'**|**'='**
*Width*:
*OptionalPositionalInteger*
*Precision*:
*empty*
**'.'** *OptionalPositionalInteger*
*Separator*:
*empty*
**','** *OptionalInteger*
**','** *OptionalInteger* **'?'**
*OptionalInteger*:
*empty*
*Integer*
**'*'**
*OptionalPositionalInteger*:
*OptionalInteger*
**'*'** *Integer* **'$'
Character
'%%'
AnyCharacterExceptPercent
Integer:
NonZeroDigit Digits
Digits:
empty
Digit Digits
NonZeroDigit:
'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'
Digit:
'0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'
Note
FormatCharacter is unspecified. It can be any character
that has no other purpose in this grammar, but it is
recommended to assign (lower- and uppercase) letters.
Note
The Parameters of a CompoundIndicator are currently
limited to a '-' flag.
Format Indicator
The format indicator can either be a single character or an
expression surrounded by '%(' and '%)'. It specifies the
basic manner in which a value will be formatted and is the minimum
requirement to format a value.
The following characters can be used as format characters:
FormatCharacter Semantics 's' To be formatted in a human readable format. Can be used with all types. 'c' To be formatted as a character. 'd' To be formatted as a signed decimal integer. 'u' To be formatted as a decimal image of the underlying bit representation. 'b' To be formatted as a binary image of the underlying bit representation. 'o' To be formatted as an octal image of the underlying bit representation. 'x' / 'X' To be formatted as a hexadecimal image of the underlying bit representation. 'e' / 'E' To be formatted as a real number in decimal scientific notation. 'f' / 'F' To be formatted as a real number in decimal natural notation. 'g' / 'G' To be formatted as a real number in decimal short notation. Depending on the number, a scientific notation or a natural notation is used. 'a' / 'A' To be formatted as a real number in hexadecimal scientific notation. 'r' To be formatted as raw bytes. The output may not be printable and depends on endianness.
The compound indicator can be used to describe compound types
like arrays or structs in more detail. A compound type is enclosed
within '%(' and '%)'. The enclosed sub-format string is
applied to individual elements. The trailing portion of the
sub-format string following the specifier for the element is
interpreted as the delimiter, and is therefore omitted following the
last element. The '%|' specifier may be used to explicitly
indicate the start of the delimiter, so that the preceding portion of
the string will be included following the last element.
The format string inside of the compound indicator should
contain exactly one format specifier (two in case of associative
arrays), which specifies the formatting mode of the elements of the
compound type. This format specifier can be a compound
indicator itself.
Note
Inside a compound indicator, strings and characters are
escaped automatically. To avoid this behavior, use "%-("
instead of "%(".
Flags
There are several flags that affect the outcome of the formatting.
Flag Semantics '-' When the formatted result is shorter than the value given by the width parameter, the output is left justified. Without the '-' flag, the output remains right justified.
There are two exceptions where the '-' flag has a
different meaning: (1) with 'r' it denotes to use little
endian and (2) in case of a compound indicator it means that
no special handling of the members is applied. |
| '=' |
When the formatted result is shorter than the value
given by the width parameter, the output is centered.
If the central position is not possible it is moved slightly
to the right. In this case, if '-' flag is present in
addition to the '=' flag, it is moved slightly to the left. |
| '+' / *' '* |
Applies to numerical values. By default, positive numbers are not
formatted to include the + sign. With one of these two flags present,
positive numbers are preceded by a plus sign or a space.
When both flags are present, a plus sign is used.
In case of 'r', a big endian format is used. |
| '0' |
Is applied to numerical values that are printed right justified.
If the zero flag is present, the space left to the number is
filled with zeros instead of spaces. |
| '#' |
Denotes that an alternative output must be used. This depends on the type
to be formatted and the format character used. See the
sections below for more information. |
Width, Precision and Separator
The width parameter specifies the minimum width of the result.
The meaning of precision depends on the format indicator. For
integers it denotes the minimum number of digits printed, for
real numbers it denotes the number of fractional digits and for
strings and compound types it denotes the maximum number of elements
that are included in the output.
A separator is used for formatting numbers. If it is specified,
the output is divided into chunks of three digits, separated by a ','. The number of digits in a chunk can be given explicitly by
providing a number or a ''* after the ','.
In all three cases the number of digits can be replaced by a ''*. In this scenario, the next argument is used as the number of
digits. If the argument is a negative number, the precision and
separator parameters are considered unspecified. For width,
the absolute value is used and the '-' flag is set.
The separator can also be followed by a '?'. In that case,
an additional argument is used to specify the symbol that should be
used to separate the chunks.
Position
By default, the arguments are processed in the provided order. With
the position parameter it is possible to address arguments
directly. It is also possible to denote a series of arguments with
two numbers separated by ':', that are all processed in the same
way. The second number can be omitted. In that case the series ends
with the last argument.
It's also possible to use positional arguments for width, precision and separator by adding a number and a '$' after the ''*.
Types
This section describes the result of combining types with format
characters. It is organized in 2 subsections: a list of general
information regarding the formatting of types in the presence of
format characters and a table that contains details for every
available combination of type and format character.
When formatting types, the following rules apply:
If the format character is upper case, the resulting string will
be formatted using upper case letters.
The default precision for floating point numbers is 6 digits.
Rounding of floating point numbers adheres to the rounding mode
of the floating point unit, if available.
The floating point values NaN and Infinity are formatted as
nan and inf, possibly preceded by '+' or '-' sign.
Formatting reals is only supported for 64 bit reals and 80 bit reals.
All other reals are cast to double before they are formatted. This will
cause the result to be inf for very large numbers.
Characters and strings formatted with the 's' format character
inside of compound types are surrounded by single and double quotes
and unprintable characters are escaped. To avoid this, a '-'
flag can be specified for the compound specifier
(e.g. "%-(%s%)" instead of "%(%s%)" ).
Structs, unions, classes and interfaces are formatted by calling a
toString method if available.
See module std.format.write for more
details.
Only part of these combinations can be used for reading. See
module std.format.read for more
detailed information.
This table contains descriptions for every possible combination of
type and format character:
<th scope="col" width="20%">Type</th> <th scope="col" width="20%">Format Character</th> Formatted as... <td rowspan="1">null</td> 's' null
|<td rowspan="3">bool</td> 's' |
false or true |
| 'b', 'd', 'o', 'u', 'x', 'X' |
As the integrals 0 or 1 with the same format character.
Please note, that 'o' and 'x' with '#' flag
might produce unexpected results due to special handling of
the value 0. |
| 'r' |
\0 or \1 |
|<td rowspan="4">Integral</td> 's', 'd' |
A signed decimal number. The '#' flag is ignored. |
| 'b', 'o', 'u', 'x', 'X' |
An unsigned binary, decimal, octal or hexadecimal number.
In case of 'o' and 'x', the '#' flag
denotes that the number must be preceded by 0 and 0x, with
the exception of the value 0, where this does not apply. For
'b' and 'u' the '#' flag has no effect. |
| 'e', 'E', 'f', 'F', 'g', 'G', 'a', 'A' |
As a floating point value with the same specifier.
Default precision is large enough to add all digits
of the integral value.
In case of 'a' and 'A', the integral digit can be
any hexadecimal digit.
|
| 'r' |
Characters taken directly from the binary representation. |
|<td rowspan="5">Floating Point</td> 'e', 'E' |
Scientific notation: Exactly one integral digit followed by a dot
and fractional digits, followed by the exponent.
The exponent is formatted as 'e' followed by
a '+' or '-' sign, followed by at least
two digits.
When there are no fractional digits and the '#' flag
is not present, the dot is omitted. |
| 'f', 'F' |
Natural notation: Integral digits followed by a dot and
fractional digits.
When there are no fractional digits and the '#' flag
is not present, the dot is omitted.
Please note: the difference between 'f' and 'F'
is only visible for NaN and Infinity. |
| 's', 'g', 'G' |
Short notation: If the absolute value is larger than 10 ^^ precision
or smaller than 0.0001, the scientific notation is used.
If not, the natural notation is applied.
In both cases precision denotes the count of all digits, including
the integral digits. Trailing zeros (including a trailing dot) are removed.
If '#' flag is present, trailing zeros are not removed. |
| 'a', 'A' |
Hexadecimal scientific notation: 0x followed by 1
(or 0 in case of value zero or denormalized number)
followed by a dot, fractional digits in hexadecimal
notation and an exponent. The exponent is build by p,
followed by a sign and the exponent in decimal notation.
When there are no fractional digits and the '#' flag
is not present, the dot is omitted. |
| 'r' |
Characters taken directly from the binary representation. |
|<td rowspan="3">Character</td> 's', 'c' |
As the character.
Inside of a compound indicator 's' is treated differently: The
character is surrounded by single quotes and non printable
characters are escaped. This can be avoided by preceding
the compound indicator with a '-' flag
(e.g. "%-(%s%)"). |
| 'b', 'd', 'o', 'u', 'x', 'X' |
As the integral that represents the character. |
| 'r' |
Characters taken directly from the binary representation. |
|<td rowspan="3">String</td> 's' |
The sequence of characters that form the string.
Inside of a compound indicator the string is surrounded by double quotes
and non printable characters are escaped. This can be avoided
by preceding the compound indicator with a '-' flag
(e.g. "%-(%s%)"). |
| 'r' |
The sequence of characters, each formatted with 'r'. |
| compound |
As an array of characters. |
|<td rowspan="3">Array</td> 's' |
When the elements are characters, the array is formatted as
a string. In all other cases the array is surrounded by square brackets
and the elements are separated by a comma and a space. If the elements
are strings, they are surrounded by double quotes and non
printable characters are escaped. |
| 'r' |
The sequence of the elements, each formatted with 'r'. |
| compound |
The sequence of the elements, each formatted according to the specifications
given inside of the compound specifier. |
|<td rowspan="2">Associative Array</td> 's' |
As a sequence of the elements in unpredictable order. The output is
surrounded by square brackets. The elements are separated by a
comma and a space. The elements are formatted as key:value. |
| compound |
As a sequence of the elements in unpredictable order. Each element
is formatted according to the specifications given inside of the
compound specifier. The first specifier is used for formatting
the key and the second specifier is used for formatting the value.
The order can be changed with positional arguments. For example
"%(%2$s (%1$s), %)" will write the value, followed by the key in
parenthesis. |
|<td rowspan="2">Enum</td> 's' |
The name of the value. If the name is not available, the base value
is used, preceeded by a cast. |
| All, but 's' |
Enums can be formatted with all format characters that can be used
with the base value. In that case they are formatted like the base value. |
|<td rowspan="3">Input Range</td> 's' |
When the elements of the range are characters, they are written like a string.
In all other cases, the elements are enclosed by square brackets and separated
by a comma and a space. |
| 'r' |
The sequence of the elements, each formatted with 'r'. |
| compound |
The sequence of the elements, each formatted according to the specifications
given inside of the compound specifier. |
|<td rowspan="1">Struct</td> 's' |
When the struct has neither an applicable toString
nor is an input range, it is formatted as follows:
StructType(field1, field2, ...). |
|<td rowspan="1">Class</td> 's' |
When the class has neither an applicable toString
nor is an input range, it is formatted as the
fully qualified name of the class. |
|<td rowspan="1">Union</td> 's' |
When the union has neither an applicable toString
nor is an input range, it is formatted as its base name. |
|<td rowspan="2">Pointer</td> 's' |
A null pointer is formatted as 'null'. All other pointers are
formatted as hexadecimal numbers with the format character 'X'. |
| 'x', 'X' |
Formatted as a hexadecimal number. |
|<td rowspan="3">SIMD vector</td> 's' |
The array is surrounded by square brackets
and the elements are separated by a comma and a space. |
| 'r' |
The sequence of the elements, each formatted with 'r'. |
| compound |
The sequence of the elements, each formatted according to the specifications
given inside of the compound specifier. |
|<td rowspan="1">Delegate</td> 's', 'r', compound |
As the .stringof of this delegate treated as a string.
Please note: The implementation is currently buggy
and its use is discouraged. |
Source
std/format/package.d
Examples
Simple use:
// Easiest way is to use `%s` everywhere:
assert(format("I got %s %s for %s euros.", 30, "eggs", 5.27) == "I got 30 eggs for 5.27 euros.");
// Other format characters provide more control:
assert(format("I got %b %(%X%) for %f euros.", 30, "eggs", 5.27) == "I got 11110 65676773 for 5.270000 euros.");
Compound specifiers allow formatting arrays and other compound types:
/*
The trailing end of the sub-format string following the specifier for
each item is interpreted as the array delimiter, and is therefore
omitted following the last array item:
*/
assert(format("My items are %(%s %).", [1,2,3]) == "My items are 1 2 3.");
assert(format("My items are %(%s, %).", [1,2,3]) == "My items are 1, 2, 3.");
/*
The "%|" delimiter specifier may be used to indicate where the
delimiter begins, so that the portion of the format string prior to
it will be retained in the last array element:
*/
assert(format("My items are %(-%s-%|, %).", [1,2,3]) == "My items are -1-, -2-, -3-.");
/*
These compound format specifiers may be nested in the case of a
nested array argument:
*/
auto mat = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
assert(format("%(%(%d %) - %)", mat), "1 2 3 - 4 5 6 - 7 8 9");
assert(format("[%(%(%d %) - %)]", mat), "[1 2 3 - 4 5 6 - 7 8 9]");
assert(format("[%([%(%d %)]%| - %)]", mat), "[1 2 3] - [4 5 6] - [7 8 9]");
/*
Strings and characters are escaped automatically inside compound
format specifiers. To avoid this behavior, use "%-(" instead of "%(":
*/
assert(format("My friends are %s.", ["John", "Nancy"]) == `My friends are ["John", "Nancy"].`);
assert(format("My friends are %(%s, %).", ["John", "Nancy"]) == `My friends are "John", "Nancy".`);
assert(format("My friends are %-(%s, %).", ["John", "Nancy"]) == `My friends are John, Nancy.`);
Using parameters:
// Flags can be used to influence to outcome:
assert(format("%g != %+#g", 3.14, 3.14) == "3.14 != +3.14000");
// Width and precision help to arrange the formatted result:
assert(format(">%10.2f<", 1234.56789) == "> 1234.57<");
// Numbers can be grouped:
assert(format("%,4d", int.max) == "21,4748,3647");
// It's possible to specify the position of an argument:
assert(format("%3$s %1$s", 3, 17, 5) == "5 3");
Providing parameters as arguments:
// Width as argument
assert(format(">%*s<", 10, "abc") == "> abc<");
// Precision as argument
assert(format(">%.*f<", 5, 123.2) == ">123.20000<");
// Grouping as argument
assert(format("%,*d", 1, int.max) == "2,1,4,7,4,8,3,6,4,7");
// Grouping separator as argument
assert(format("%,3?d", '_', int.max) == "2_147_483_647");
// All at once
assert(format("%*.*,*?d", 20, 15, 6, '/', int.max) == " 000/002147/483647");
format : (alias template) format = std.format.format(Char, Args...)(in Char[] fmt, Args args) if (isSomeChar!Char)Converts its arguments according to a format string into a string.
The second version of format takes the format string as template
argument. In this case, it is checked for consistency at
compile-time and produces slightly faster code, because the length of
the output buffer can be estimated in advance.
Params:
fmt = a $(MREF_ALTTEXT format string, std,format)
args = a variadic list of arguments to be formatted
Char = character type of fmt
Args = a variadic list of types of the arguments
Returns:
The formatted string.
Throws:
A $(LREF FormatException) if formatting did not succeed.
See_Also:
$(LREF sformat) for a variant, that tries to avoid garbage collection.
format;
return string std.format.format!("%.6g %s", const(double), string)(const(double) __param_0, string __param_1) pure @safeExamples
The format string can be checked at compile-time:
auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");
// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format!"%.6g %s"((field) double uom_quantity_runtime_expected.RQuantity.valuevalue, (field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim.string uom_quantity_runtime_expected.unitString(in uom_quantity_runtime_expected.Dim d) pure @safeRuntime unit label for an exponent vector (Dim(mass: 1, time: -3) →
"kg s^-3"). Called at runtime here — the dims are not known earlier — so
it may GC; that is fine off the @nogc checking path.
unitString);
}
}
/// The rare path that must *throw* in `@nogc` code rather than return a result:
/// it uses `recycledErrorInstance` (a pre-allocated, reusable `Error`) so no GC
/// allocation happens on the throw — `recycledErrorInstance` requires
/// `T : Error`, which suits a "this is a programming mistake" assertion. The
/// `Expected`-returning `add` above is the recoverable, `nothrow` default you
/// should prefer. See docs/guidelines/idioms/expected/ for when to pick which.
(struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity uom_quantity_runtime_expected.RQuantity uom_quantity_runtime_expected.mustAdd(in uom_quantity_runtime_expected.RQuantity a, in uom_quantity_runtime_expected.RQuantity b) @nogc @systemThe rare path that must throw in @nogc code rather than return a result:
it uses recycledErrorInstance (a pre-allocated, reusable Error) so no GC
allocation happens on the throw — recycledErrorInstance requires
T : Error, which suits a "this is a programming mistake" assertion. The
Expected-returning add above is the recoverable, nothrow default you
should prefer. See docs/guidelines/idioms/expected/ for when to pick which.
mustAdd(in (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity (parameter) const(uom_quantity_runtime_expected.RQuantity) aa, in (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity (parameter) const(uom_quantity_runtime_expected.RQuantity) bb) @system @nogc
{
import (package) sparklessparkles.(package) sparkles.basebase.(module) sparkles.base.lifetimelifetime : (alias template) recycledErrorInstance = sparkles.base.lifetime.recycledErrorInstance(T, Args...)(in char[] message, auto ref Args args) if (is(T == class) && is(T : Error))Returns a recycled error instance, suitable for throwing in @nogc code.
This is a convenience wrapper around recycledInstance with attributes
appropriate for error handling: @system pure nothrow @nogc.
It explicitly takes the error message as the first argument and copies it
into a stable thread-local buffer. This ensures that the message outlives
the call, even if it was originally a stack-allocated slice (common in
@nogc unit tests).
The function is marked @system because pure is technically a lie -
the implementation uses thread-local state. However, this is acceptable
for error throwing because:
$(UL
$(LI Try-catch code typically doesn't rely on object identity)
$(LI Exception object lifetimes are stack-bound)
)
Callers should wrap calls in @trusted after verifying correct usage.
Example:
@nogc pure nothrow void foo() @trusted {
throw recycledErrorInstance!Error("Something went wrong");
}
---
recycledErrorInstance;
auto (local variable) expected.Expected!(RQuantity, DimError, NoGcHook) rr = (parameter) const(uom_quantity_runtime_expected.RQuantity) aa.expected.Expected!(RQuantity, DimError, NoGcHook) uom_quantity_runtime_expected.RQuantity.add(in uom_quantity_runtime_expected.RQuantity rhs) const pure nothrow @nogc @safe+/-: fallible. Same dim → ok; different dim → err (no throw).
add((parameter) const(uom_quantity_runtime_expected.RQuantity) bb);
if ((local variable) expected.Expected!(RQuantity, DimError, NoGcHook) rr.bool expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).hasError!()() const pure nothrow @nogc @property @safeChecks if Expected has error
hasError)
throw object.Error sparkles.base.lifetime.recycledErrorInstance!(object.Error)(in char[] message) pure nothrow @nogc @systemReturns a recycled error instance, suitable for throwing in @nogc code.
This is a convenience wrapper around recycledInstance with attributes
appropriate for error handling: @system pure nothrow @nogc.
It explicitly takes the error message as the first argument and copies it
into a stable thread-local buffer. This ensures that the message outlives
the call, even if it was originally a stack-allocated slice (common in
@nogc unit tests).
The function is marked @system because pure is technically a lie -
the implementation uses thread-local state. However, this is acceptable
for error throwing because:
Try-catch code typically doesn't rely on object identity
Exception object lifetimes are stack-bound
Callers should wrap calls in @trusted after verifying correct usage.
Example
@nogc pure nothrow void foo() @trusted {
throw recycledErrorInstance!Error("Something went wrong");
}
recycledErrorInstance!(class) object.ErrorThe base class of all unrecoverable runtime errors.
This represents the category of Throwable objects that are not
safe to catch and handle. In principle, one should not catch Error
objects, as they represent unrecoverable runtime errors.
Certain runtime guarantees may fail to hold when these errors are
thrown, making it unsafe to continue execution after catching them.
Examples
bool gotCaught;
try
{
throw new Error("msg");
}
catch (Error e)
{
gotCaught = true;
assert(e.msg == "msg");
}
assert(gotCaught);
Error("dimension mismatch in mustAdd");
return (local variable) expected.Expected!(RQuantity, DimError, NoGcHook) rr.inout(uom_quantity_runtime_expected.RQuantity) expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).value!()() inout pure nothrow @nogc @property @safeReturns the expected value if there is one.
With default Abort hook, it asserts when there is no value.
It calls hook's onAccessEmptyValue otherwise.
It returns T.init when hook doesn't provide onAccessEmptyValue.
value;
}
// --- Runtime material table: the units are DATA, loaded at startup ----------
/// One row of a (toy) material file: a channel name and the dimension the
/// renderer should tag that channel's samples with.
struct (struct) uom_quantity_runtime_expected.MaterialRowOne row of a (toy) material file: a channel name and the dimension the
renderer should tag that channel's samples with.
MaterialRow
{
(alias) object.string = stringstring (field) string uom_quantity_runtime_expected.MaterialRow.namename;
(struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim (field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.MaterialRow.dimdim;
}
enum (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.metreDim = Dim(0, 1, 0, 0)metreDim = (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim(length: 1);
enum (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.secondDim = Dim(0, 0, 1, 0)secondDim = (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim(time: 1);
enum (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.powerDim = Dim(1, 2, -3, 0)powerDim = (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim(mass: 1, length: 2, time: -3); // W
enum (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.irradianceDim = Dim(1, 0, -3, 0)irradianceDim = (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim(mass: 1, length: 0, time: -3); // W·m⁻²
enum (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.radianceDim = Dim(1, 0, -3, -1)radianceDim = (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim(mass: 1, time: -3, solidAngle: -1); // W·m⁻²·sr⁻¹
/// A material catalogue "parsed from a file" — here a static table, but the
/// point is that `load` resolves a channel's *dimension at runtime*.
immutable (struct) uom_quantity_runtime_expected.MaterialRowOne row of a (toy) material file: a channel name and the dimension the
renderer should tag that channel's samples with.
MaterialRow[] (immutable global) immutable(uom_quantity_runtime_expected.MaterialRow[]) uom_quantity_runtime_expected.materialTableA material catalogue "parsed from a file" — here a static table, but the
point is that load resolves a channel's dimension at runtime.
materialTable = [
(struct) uom_quantity_runtime_expected.MaterialRowOne row of a (toy) material file: a channel name and the dimension the
renderer should tag that channel's samples with.
MaterialRow("length", (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.metreDim = Dim(0, 1, 0, 0)metreDim),
(struct) uom_quantity_runtime_expected.MaterialRowOne row of a (toy) material file: a channel name and the dimension the
renderer should tag that channel's samples with.
MaterialRow("duration", (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.secondDim = Dim(0, 0, 1, 0)secondDim),
(struct) uom_quantity_runtime_expected.MaterialRowOne row of a (toy) material file: a channel name and the dimension the
renderer should tag that channel's samples with.
MaterialRow("power", (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.powerDim = Dim(1, 2, -3, 0)powerDim),
(struct) uom_quantity_runtime_expected.MaterialRowOne row of a (toy) material file: a channel name and the dimension the
renderer should tag that channel's samples with.
MaterialRow("irradiance", (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.irradianceDim = Dim(1, 0, -3, 0)irradianceDim),
(struct) uom_quantity_runtime_expected.MaterialRowOne row of a (toy) material file: a channel name and the dimension the
renderer should tag that channel's samples with.
MaterialRow("radiance", (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.radianceDim = Dim(1, 0, -3, -1)radianceDim),
];
/// Look a channel up by name and tag a measured `value` with its dimension —
/// no compile-time knowledge of which unit it is. `@nogc nothrow`: string
/// comparison and struct copy only.
(struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity uom_quantity_runtime_expected.RQuantity uom_quantity_runtime_expected.load(in char[] channel, in double value) pure nothrow @nogc @safeLook a channel up by name and tag a measured value with its dimension —
no compile-time knowledge of which unit it is. @nogc nothrow: string
comparison and struct copy only.
load(in char[] (parameter) const(char[]) channelchannel, in double (parameter) const(double) valuevalue) @safe pure nothrow @nogc
{
foreach ((parameter) immutable(uom_quantity_runtime_expected.MaterialRow) rowrow; (immutable global) immutable(uom_quantity_runtime_expected.MaterialRow[]) uom_quantity_runtime_expected.materialTableA material catalogue "parsed from a file" — here a static table, but the
point is that load resolves a channel's dimension at runtime.
materialTable)
if ((local variable) immutable(uom_quantity_runtime_expected.MaterialRow) rowrow.(field) string uom_quantity_runtime_expected.MaterialRow.namename == (parameter) const(char[]) channelchannel)
return (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity((parameter) const(double) valuevalue, (local variable) immutable(uom_quantity_runtime_expected.MaterialRow) rowrow.(field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.MaterialRow.dimdim);
return (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity((parameter) const(double) valuevalue, (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim()); // unknown → dimensionless
}
// --- Composition with sparkles:math: one Dim tag for a whole vector ---------
/// A dimensioned 3-vector, composition *ordering A*: the runtime `Dim` wraps
/// the `Vec3`, tagging all three components at once (one tag, not three).
struct (struct) uom_quantity_runtime_expected.RVec3A dimensioned 3-vector, composition ordering A: the runtime Dim wraps
the Vec3, tagging all three components at once (one tag, not three).
RVec3
{
(alias) uom_quantity_runtime_expected.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])The raytracer's numeric payload for a 3-vector quantity.
Vec3 (field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_runtime_expected.RVec3.valuevalue;
(struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim (field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RVec3.dimdim;
/// Fallible add, mirroring `RQuantity.add`: a single `Dim` compare guards
/// the whole vector.
(alias) uom_quantity_runtime_expected.DimExpected!(uom_quantity_runtime_expected.RVec3) = expected.Expected!(RVec3, DimError, NoGcHook)Expected!(T, DimError) with the @nogc-friendly hook baked in. A fallible
operation returns ``DimExpected!RQuantity; the caller inspects hasValue /
hasError rather than catching an exception.
DimExpected!(struct) uom_quantity_runtime_expected.RVec3A dimensioned 3-vector, composition ordering A: the runtime Dim wraps
the Vec3, tagging all three components at once (one tag, not three).
RVec3 expected.Expected!(RVec3, DimError, NoGcHook) uom_quantity_runtime_expected.RVec3.add(in uom_quantity_runtime_expected.RVec3 rhs) const pure nothrow @nogc @safeFallible add, mirroring RQuantity.add``: a single Dim compare guards
the whole vector.
add(in (struct) uom_quantity_runtime_expected.RVec3A dimensioned 3-vector, composition ordering A: the runtime Dim wraps
the Vec3, tagging all three components at once (one tag, not three).
RVec3 (parameter) const(uom_quantity_runtime_expected.RVec3) rhsrhs) const @safe pure nothrow @nogc
{
if ((field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RVec3.dimdim != (parameter) const(uom_quantity_runtime_expected.RVec3) rhsrhs.(field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RVec3.dimdim)
return expected.Expected!(RVec3, DimError, NoGcHook) expected.err!(uom_quantity_runtime_expected.RVec3, uom_quantity_runtime_expected.NoGcHook, uom_quantity_runtime_expected.DimError)(uom_quantity_runtime_expected.DimError err) pure nothrow @nogc @safeCreates an Expected object from an error value, with type inference.
Examples
// implicit void value type
{
auto res = err("foo");
static assert(is(typeof(res) == Expected!(void, string)));
assert(!res);
assert(res.error == "foo");
}
// bool
{
auto res = err!int("42");
static assert(is(typeof(res) == Expected!(int, string)));
assert(!res);
assert(res.error == "42");
}
// other error type
{
auto res = err!bool(42);
static assert(is(typeof(res) == Expected!(bool, int)));
assert(!res);
assert(res.error == 42);
}
err!((struct) uom_quantity_runtime_expected.RVec3A dimensioned 3-vector, composition ordering A: the runtime Dim wraps
the Vec3, tagging all three components at once (one tag, not three).
RVec3, (struct) uom_quantity_runtime_expected.NoGcHookexpected hook that keeps the results usable in @nogc nothrow code: a
result must be explicitly ok or err, never a default-constructed limbo.
NoGcHook)((struct) uom_quantity_runtime_expected.DimErrorA dimension mismatch: the two operands' dimensions, plus a fixed message.
It carries no heap data, so constructing one stays @nogc nothrow.
DimError((field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RVec3.dimdim, (parameter) const(uom_quantity_runtime_expected.RVec3) rhsrhs.(field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RVec3.dimdim));
return expected.Expected!(RVec3, DimError, NoGcHook) expected.ok!(uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook, uom_quantity_runtime_expected.RVec3)(uom_quantity_runtime_expected.RVec3 value) pure nothrow @nogc @safeCreates an Expected object from an expected value, with type inference.
ok!((struct) uom_quantity_runtime_expected.DimErrorA dimension mismatch: the two operands' dimensions, plus a fixed message.
It carries no heap data, so constructing one stays @nogc nothrow.
DimError, (struct) uom_quantity_runtime_expected.NoGcHookexpected hook that keeps the results usable in @nogc nothrow code: a
result must be explicitly ok or err, never a default-constructed limbo.
NoGcHook)((struct) uom_quantity_runtime_expected.RVec3A dimensioned 3-vector, composition ordering A: the runtime Dim wraps
the Vec3, tagging all three components at once (one tag, not three).
RVec3((field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_runtime_expected.RVec3.valuevalue + sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).opBinary!("+", double)(in sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) rhs) const pure nothrow @nogc @safeComponent-wise vector addition/subtraction.
rhs.sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).opBinary!("+", double)(in sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) rhs) const pure nothrow @nogc @safeComponent-wise vector addition/subtraction.
value, (field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RVec3.dimdim));
}
/// Render the vector through an `appender` sink (never `writeln`'s
/// `LockingTextWriter`), then the runtime unit label.
(alias) object.string = stringstring string uom_quantity_runtime_expected.RVec3.toString() const @safeRender the vector through an appender sink (never writeln's
LockingTextWriter), then the runtime unit label.
toString() const @safe
{
import (package) stdstd.(module) std.arrayFunctions and types that manipulate built-in arrays and associative arrays.
This module provides all kinds of functions to create, manipulate or convert arrays:
Function Name Description
| array |
Returns a copy of the input in a newly allocated dynamic array.
|
| appender |
Returns a new Appender or RefAppender initialized with a given array.
|
| assocArray |
Returns a newly allocated associative array from a range/ranges of keys and values.
|
| byPair |
Construct a range iterating over an associative array by key/value tuples.
|
| insertInPlace |
Inserts into an existing array at a given position.
|
| join |
Concatenates a range of ranges into one array.
|
| minimallyInitializedArray |
Returns a new array of type T.
|
| replace |
Returns a new array with all occurrences of a certain subrange replaced.
|
| replaceFirst |
Returns a new array with the first occurrence of a certain subrange replaced.
|
| replaceInPlace |
Replaces all occurrences of a certain subrange and puts the result into a given array.
|
| replaceInto |
Replaces all occurrences of a certain subrange and puts the result into an output range.
|
| replaceLast |
Returns a new array with the last occurrence of a certain subrange replaced.
|
| replaceSlice |
Returns a new array with a given slice replaced.
|
| replicate |
Creates a new array out of several copies of an input array or range.
|
| sameHead |
Checks if the initial segments of two arrays refer to the same
place in memory.
|
| sameTail |
Checks if the final segments of two arrays refer to the same place
in memory.
|
| split |
Eagerly split a range or string into an array.
|
| staticArray |
Creates a new static array from given data.
|
| uninitializedArray |
Returns a new array of type T without initializing its elements.
|
Source
std/array.d
array : (alias template) appender = std.array.appender(A)() if (isDynamicArray!A)Convenience function that returns an $(LREF Appender) instance,
optionally initialized with array.
appender;
auto (local variable) std.array.Appender!string sinksink = std.array.Appender!string std.array.appender!string() pure nothrow @safeConvenience function that returns an Appender instance,
optionally initialized with array.
appender!(alias) object.string = stringstring();
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_runtime_expected.RVec3.valuevalue.void sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).toString!(std.array.Appender!string)(ref scope std.array.Appender!string writer) const pure @safeWrites the vector as (name0: value0, name1: value1, ...).
toString((local variable) std.array.Appender!string sinksink);
(local variable) std.array.Appender!string sinksink.void std.array.Appender!string.put!string(string items) pure nothrow @safeAppends an entire range to the managed array. Performs encoding for
char elements if A is a differently typed char array.
put(" ");
(local variable) std.array.Appender!string sinksink.void std.array.Appender!string.put!string(string items) pure nothrow @safeAppends an entire range to the managed array. Performs encoding for
char elements if A is a differently typed char array.
put((field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RVec3.dimdim.string uom_quantity_runtime_expected.unitString(in uom_quantity_runtime_expected.Dim d) pure @safeRuntime unit label for an exponent vector (Dim(mass: 1, time: -3) →
"kg s^-3"). Called at runtime here — the dims are not known earlier — so
it may GC; that is fine off the @nogc checking path.
unitString);
return (local variable) std.array.Appender!string sinksink[];
}
}
@("RQuantity.runtime.add-checks-and-total-multiply")
@safe pure nothrow @nogc
unittest
{
const (local variable) const(uom_quantity_runtime_expected.RQuantity) aa = (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity(3.0, (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.metreDim = Dim(0, 1, 0, 0)metreDim);
const (local variable) const(uom_quantity_runtime_expected.RQuantity) bb = (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity(4.0, (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.metreDim = Dim(0, 1, 0, 0)metreDim);
const (local variable) const(uom_quantity_runtime_expected.RQuantity) tt = (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity(2.0, (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.secondDim = Dim(0, 0, 1, 0)secondDim);
// Same dimension: add is ok.
auto (local variable) expected.Expected!(RQuantity, DimError, NoGcHook) sumsum = (local variable) const(uom_quantity_runtime_expected.RQuantity) aa.expected.Expected!(RQuantity, DimError, NoGcHook) uom_quantity_runtime_expected.RQuantity.add(in uom_quantity_runtime_expected.RQuantity rhs) const pure nothrow @nogc @safe+/-: fallible. Same dim → ok; different dim → err (no throw).
add((local variable) const(uom_quantity_runtime_expected.RQuantity) bb);
assert((local variable) expected.Expected!(RQuantity, DimError, NoGcHook) sumsum.bool expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).hasValue!()() const pure nothrow @nogc @property @safeChecks if Expected has value
hasValue);
assert((local variable) expected.Expected!(RQuantity, DimError, NoGcHook) sumsum.inout(uom_quantity_runtime_expected.RQuantity) expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).value!()() inout pure nothrow @nogc @property @safeReturns the expected value if there is one.
With default Abort hook, it asserts when there is no value.
It calls hook's onAccessEmptyValue otherwise.
It returns T.init when hook doesn't provide onAccessEmptyValue.
value.(field) double uom_quantity_runtime_expected.RQuantity.valuevalue == 7.0);
assert((local variable) expected.Expected!(RQuantity, DimError, NoGcHook) sumsum.inout(uom_quantity_runtime_expected.RQuantity) expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).value!()() inout pure nothrow @nogc @property @safeReturns the expected value if there is one.
With default Abort hook, it asserts when there is no value.
It calls hook's onAccessEmptyValue otherwise.
It returns T.init when hook doesn't provide onAccessEmptyValue.
value.(field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim == (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.metreDim = Dim(0, 1, 0, 0)metreDim);
// Different dimension: add is an err — no throw.
auto (local variable) expected.Expected!(RQuantity, DimError, NoGcHook) badbad = (local variable) const(uom_quantity_runtime_expected.RQuantity) aa.expected.Expected!(RQuantity, DimError, NoGcHook) uom_quantity_runtime_expected.RQuantity.add(in uom_quantity_runtime_expected.RQuantity rhs) const pure nothrow @nogc @safe+/-: fallible. Same dim → ok; different dim → err (no throw).
add((local variable) const(uom_quantity_runtime_expected.RQuantity) tt);
assert((local variable) expected.Expected!(RQuantity, DimError, NoGcHook) badbad.bool expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).hasError!()() const pure nothrow @nogc @property @safeChecks if Expected has error
hasError);
assert((local variable) expected.Expected!(RQuantity, DimError, NoGcHook) badbad.inout(uom_quantity_runtime_expected.DimError) expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).error() inout pure nothrow @nogc @property @safeReturns the error value. May only be called when hasValue returns false.
If there is no error value, it calls hook's onAccessEmptyError.
It returns E.init when hook doesn't provide onAccessEmptyError.
error.(field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.DimError.havethe left operand's dimension
have == (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.metreDim = Dim(0, 1, 0, 0)metreDim);
assert((local variable) expected.Expected!(RQuantity, DimError, NoGcHook) badbad.inout(uom_quantity_runtime_expected.DimError) expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).error() inout pure nothrow @nogc @property @safeReturns the error value. May only be called when hasValue returns false.
If there is no error value, it calls hook's onAccessEmptyError.
It returns E.init when hook doesn't provide onAccessEmptyError.
error.(field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.DimError.wantthe right operand's dimension (what have was required to match)
want == (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.secondDim = Dim(0, 0, 1, 0)secondDim);
// Multiplication is total: length · length is an area (length^2).
auto (local variable) uom_quantity_runtime_expected.RQuantity areaarea = (local variable) const(uom_quantity_runtime_expected.RQuantity) aa.uom_quantity_runtime_expected.RQuantity uom_quantity_runtime_expected.RQuantity.mul(in uom_quantity_runtime_expected.RQuantity rhs) const pure nothrow @nogc @safe*: total — any two dimensions combine, so it returns an RQuantity
directly (never an err). Length · Length → an area, and so on.
mul((local variable) const(uom_quantity_runtime_expected.RQuantity) bb);
assert((local variable) uom_quantity_runtime_expected.RQuantity areaarea.(field) double uom_quantity_runtime_expected.RQuantity.valuevalue == 12.0);
assert((local variable) uom_quantity_runtime_expected.RQuantity areaarea.(field) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.RQuantity.dimdim == (struct) uom_quantity_runtime_expected.DimA dimension carried as a runtime value: an exponent vector over
(mass, length, time, solid-angle). Two quantities are addable iff their
Dims are equal; == on the struct is the entire dimension check.
Dim(length: 2));
// Radiance vs irradiance: distinct only because sr is tracked.
const (local variable) const(uom_quantity_runtime_expected.RQuantity) radrad = (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity(1.0, (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.radianceDim = Dim(1, 0, -3, -1)radianceDim);
const (local variable) const(uom_quantity_runtime_expected.RQuantity) irrirr = (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity(1.0, (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.irradianceDim = Dim(1, 0, -3, 0)irradianceDim);
assert((local variable) const(uom_quantity_runtime_expected.RQuantity) radrad.expected.Expected!(RQuantity, DimError, NoGcHook) uom_quantity_runtime_expected.RQuantity.add(in uom_quantity_runtime_expected.RQuantity rhs) const pure nothrow @nogc @safe+/-: fallible. Same dim → ok; different dim → err (no throw).
add((local variable) const(uom_quantity_runtime_expected.RQuantity) irrirr).bool expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).hasError!()() const pure nothrow @nogc @property @safeChecks if Expected has error
hasError);
// Composition: one Dim tag guards the whole Vec3.
const (local variable) const(uom_quantity_runtime_expected.RVec3) v1v1 = (struct) uom_quantity_runtime_expected.RVec3A dimensioned 3-vector, composition ordering A: the runtime Dim wraps
the Vec3, tagging all three components at once (one tag, not three).
RVec3((struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])Vec3(1, 0, 0), (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.radianceDim = Dim(1, 0, -3, -1)radianceDim);
const (local variable) const(uom_quantity_runtime_expected.RVec3) v2v2 = (struct) uom_quantity_runtime_expected.RVec3A dimensioned 3-vector, composition ordering A: the runtime Dim wraps
the Vec3, tagging all three components at once (one tag, not three).
RVec3((struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])Vec3(0, 1, 0), (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.radianceDim = Dim(1, 0, -3, -1)radianceDim);
assert((local variable) const(uom_quantity_runtime_expected.RVec3) v1v1.expected.Expected!(RVec3, DimError, NoGcHook) uom_quantity_runtime_expected.RVec3.add(in uom_quantity_runtime_expected.RVec3 rhs) const pure nothrow @nogc @safeFallible add, mirroring RQuantity.add``: a single Dim compare guards
the whole vector.
add((local variable) const(uom_quantity_runtime_expected.RVec3) v2v2).bool expected.Expected!(uom_quantity_runtime_expected.RVec3, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).hasValue!()() const pure nothrow @nogc @property @safeChecks if Expected has value
hasValue);
assert((local variable) const(uom_quantity_runtime_expected.RVec3) v1v1.expected.Expected!(RVec3, DimError, NoGcHook) uom_quantity_runtime_expected.RVec3.add(in uom_quantity_runtime_expected.RVec3 rhs) const pure nothrow @nogc @safeFallible add, mirroring RQuantity.add``: a single Dim compare guards
the whole vector.
add((struct) uom_quantity_runtime_expected.RVec3A dimensioned 3-vector, composition ordering A: the runtime Dim wraps
the Vec3, tagging all three components at once (one tag, not three).
RVec3((struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])Vec3(0, 0, 1), (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.irradianceDim = Dim(1, 0, -3, 0)irradianceDim)).bool expected.Expected!(uom_quantity_runtime_expected.RVec3, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).hasError!()() const pure nothrow @nogc @property @safeChecks if Expected has error
hasError);
}
@("RQuantity.runtime.mustAdd-throws-recycled-on-mismatch")
@system unittest
{
const (local variable) const(uom_quantity_runtime_expected.RQuantity) aa = (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity(1.0, (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.metreDim = Dim(0, 1, 0, 0)metreDim);
const (local variable) const(uom_quantity_runtime_expected.RQuantity) bb = (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity(2.0, (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.metreDim = Dim(0, 1, 0, 0)metreDim);
// Matching dimensions: the throwing helper returns the sum.
assert(uom_quantity_runtime_expected.RQuantity uom_quantity_runtime_expected.mustAdd(in uom_quantity_runtime_expected.RQuantity a, in uom_quantity_runtime_expected.RQuantity b) @nogc @systemThe rare path that must throw in @nogc code rather than return a result:
it uses recycledErrorInstance (a pre-allocated, reusable Error) so no GC
allocation happens on the throw — recycledErrorInstance requires
T : Error, which suits a "this is a programming mistake" assertion. The
Expected-returning add above is the recoverable, nothrow default you
should prefer. See docs/guidelines/idioms/expected/ for when to pick which.
mustAdd((local variable) const(uom_quantity_runtime_expected.RQuantity) aa, (local variable) const(uom_quantity_runtime_expected.RQuantity) bb).(field) double uom_quantity_runtime_expected.RQuantity.valuevalue == 3.0);
// Mismatch: it throws (a recycled `Error`, GC-free) instead of returning.
bool (local variable) bool threwthrew;
try
uom_quantity_runtime_expected.RQuantity uom_quantity_runtime_expected.mustAdd(in uom_quantity_runtime_expected.RQuantity a, in uom_quantity_runtime_expected.RQuantity b) @nogc @systemThe rare path that must throw in @nogc code rather than return a result:
it uses recycledErrorInstance (a pre-allocated, reusable Error) so no GC
allocation happens on the throw — recycledErrorInstance requires
T : Error, which suits a "this is a programming mistake" assertion. The
Expected-returning add above is the recoverable, nothrow default you
should prefer. See docs/guidelines/idioms/expected/ for when to pick which.
mustAdd((local variable) const(uom_quantity_runtime_expected.RQuantity) aa, (struct) uom_quantity_runtime_expected.RQuantityA quantity whose dimension is a runtime field, not a type parameter. Two
distinct dimensions inhabit the same type RQuantity — the distinction is
data, checked when the values meet.
RQuantity(1.0, (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.secondDim = Dim(0, 0, 1, 0)secondDim));
catch ((class) object.ErrorThe base class of all unrecoverable runtime errors.
This represents the category of Throwable objects that are not
safe to catch and handle. In principle, one should not catch Error
objects, as they represent unrecoverable runtime errors.
Certain runtime guarantees may fail to hold when these errors are
thrown, making it unsafe to continue execution after catching them.
Examples
bool gotCaught;
try
{
throw new Error("msg");
}
catch (Error e)
{
gotCaught = true;
assert(e.msg == "msg");
}
assert(gotCaught);
Error (local variable) object.Error ee)
(local variable) bool threwthrew = true;
assert((local variable) bool threwthrew);
}
void void D main() @safemain() @safe
{
import (package) stdstd.(module) std.stdioCategory Symbols File handles _popen File isFileHandle openNetwork stderr stdin stdout Reading chunks lines readf readfln readln Writing toFile write writef writefln writeln Misc KeepTerminator LockType StdioException
Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio
is publically imported when importing std.stdio.
There are three layers of I/O:
The lowest layer is the operating system layer. The two main schemes are Windows and Posix.
C's stdio.h which unifies the two operating system schemes.
std.stdio, this module, unifies the various stdio.h implementations into
a high level package for D programs.
Source
std/stdio.d
stdio : (alias template) writeln = std.stdio.writeln(T...)(T args)Equivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Params:
args = the items to write to stdout
Throws:
In case of an I/O error, throws an $(LREF StdioException).
Example:
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
---
writeln;
// "Material data loaded at runtime": dimensions come from the table, not
// from types written into this source.
const (local variable) const(uom_quantity_runtime_expected.RQuantity) len1len1 = uom_quantity_runtime_expected.RQuantity uom_quantity_runtime_expected.load(in char[] channel, in double value) pure nothrow @nogc @safeLook a channel up by name and tag a measured value with its dimension —
no compile-time knowledge of which unit it is. @nogc nothrow: string
comparison and struct copy only.
load("length", 3.0);
const (local variable) const(uom_quantity_runtime_expected.RQuantity) len2len2 = uom_quantity_runtime_expected.RQuantity uom_quantity_runtime_expected.load(in char[] channel, in double value) pure nothrow @nogc @safeLook a channel up by name and tag a measured value with its dimension —
no compile-time knowledge of which unit it is. @nogc nothrow: string
comparison and struct copy only.
load("length", 4.0);
const (local variable) const(uom_quantity_runtime_expected.RQuantity) secssecs = uom_quantity_runtime_expected.RQuantity uom_quantity_runtime_expected.load(in char[] channel, in double value) pure nothrow @nogc @safeLook a channel up by name and tag a measured value with its dimension —
no compile-time knowledge of which unit it is. @nogc nothrow: string
comparison and struct copy only.
load("duration", 2.0);
const (local variable) const(uom_quantity_runtime_expected.RQuantity) radrad = uom_quantity_runtime_expected.RQuantity uom_quantity_runtime_expected.load(in char[] channel, in double value) pure nothrow @nogc @safeLook a channel up by name and tag a measured value with its dimension —
no compile-time knowledge of which unit it is. @nogc nothrow: string
comparison and struct copy only.
load("radiance", 1.0);
const (local variable) const(uom_quantity_runtime_expected.RQuantity) irrirr = uom_quantity_runtime_expected.RQuantity uom_quantity_runtime_expected.load(in char[] channel, in double value) pure nothrow @nogc @safeLook a channel up by name and tag a measured value with its dimension —
no compile-time knowledge of which unit it is. @nogc nothrow: string
comparison and struct copy only.
load("irradiance", 1.0);
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("Loaded (dimension resolved at runtime):");
void std.stdio.writeln!(string, const(uom_quantity_runtime_expected.RQuantity))(string __param_0, const(uom_quantity_runtime_expected.RQuantity) __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln(" length = ", (local variable) const(uom_quantity_runtime_expected.RQuantity) len1len1);
void std.stdio.writeln!(string, const(uom_quantity_runtime_expected.RQuantity))(string __param_0, const(uom_quantity_runtime_expected.RQuantity) __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln(" duration = ", (local variable) const(uom_quantity_runtime_expected.RQuantity) secssecs);
void std.stdio.writeln!(string, const(uom_quantity_runtime_expected.RQuantity))(string __param_0, const(uom_quantity_runtime_expected.RQuantity) __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln(" radiance = ", (local variable) const(uom_quantity_runtime_expected.RQuantity) radrad);
void std.stdio.writeln!(string, const(uom_quantity_runtime_expected.RQuantity))(string __param_0, const(uom_quantity_runtime_expected.RQuantity) __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln(" irradiance = ", (local variable) const(uom_quantity_runtime_expected.RQuantity) irrirr);
void std.stdio.writeln!()() @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln();
// add(len, len) -> ok
auto (local variable) expected.Expected!(RQuantity, DimError, NoGcHook) okSumokSum = (local variable) const(uom_quantity_runtime_expected.RQuantity) len1len1.expected.Expected!(RQuantity, DimError, NoGcHook) uom_quantity_runtime_expected.RQuantity.add(in uom_quantity_runtime_expected.RQuantity rhs) const pure nothrow @nogc @safe+/-: fallible. Same dim → ok; different dim → err (no throw).
add((local variable) const(uom_quantity_runtime_expected.RQuantity) len2len2);
void std.stdio.writeln!(string, string)(string __param_0, string __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("add(length, length) -> ", (local variable) expected.Expected!(RQuantity, DimError, NoGcHook) okSumokSum.bool expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).hasValue!()() const pure nothrow @nogc @property @safeChecks if Expected has value
hasValue ? "ok" : "err");
if ((local variable) expected.Expected!(RQuantity, DimError, NoGcHook) okSumokSum.bool expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).hasValue!()() const pure nothrow @nogc @property @safeChecks if Expected has value
hasValue)
void std.stdio.writeln!(string, uom_quantity_runtime_expected.RQuantity)(string __param_0, uom_quantity_runtime_expected.RQuantity __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln(" = ", (local variable) expected.Expected!(RQuantity, DimError, NoGcHook) okSumokSum.inout(uom_quantity_runtime_expected.RQuantity) expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).value!()() inout pure nothrow @nogc @property @safeReturns the expected value if there is one.
With default Abort hook, it asserts when there is no value.
It calls hook's onAccessEmptyValue otherwise.
It returns T.init when hook doesn't provide onAccessEmptyValue.
value);
// add(radiance, irradiance) -> err (only because sr is tracked)
auto (local variable) expected.Expected!(RQuantity, DimError, NoGcHook) radErrradErr = (local variable) const(uom_quantity_runtime_expected.RQuantity) radrad.expected.Expected!(RQuantity, DimError, NoGcHook) uom_quantity_runtime_expected.RQuantity.add(in uom_quantity_runtime_expected.RQuantity rhs) const pure nothrow @nogc @safe+/-: fallible. Same dim → ok; different dim → err (no throw).
add((local variable) const(uom_quantity_runtime_expected.RQuantity) irrirr);
void std.stdio.writeln!(string, string)(string __param_0, string __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("add(radiance, irradiance) -> ", (local variable) expected.Expected!(RQuantity, DimError, NoGcHook) radErrradErr.bool expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).hasError!()() const pure nothrow @nogc @property @safeChecks if Expected has error
hasError ? "err" : "ok");
if ((local variable) expected.Expected!(RQuantity, DimError, NoGcHook) radErrradErr.bool expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).hasError!()() const pure nothrow @nogc @property @safeChecks if Expected has error
hasError)
void std.stdio.writeln!(string, string)(string __param_0, string __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln(" ", (local variable) expected.Expected!(RQuantity, DimError, NoGcHook) radErrradErr.inout(uom_quantity_runtime_expected.DimError) expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).error() inout pure nothrow @nogc @property @safeReturns the error value. May only be called when hasValue returns false.
If there is no error value, it calls hook's onAccessEmptyError.
It returns E.init when hook doesn't provide onAccessEmptyError.
error.string uom_quantity_runtime_expected.DimError.describe() const pure @safeA human-readable rendering (GC-allocating via unitString; used only
on the reporting path, never inside @nogc arithmetic).
describe);
// m + s -> err
auto (local variable) expected.Expected!(RQuantity, DimError, NoGcHook) msErrmsErr = (local variable) const(uom_quantity_runtime_expected.RQuantity) len1len1.expected.Expected!(RQuantity, DimError, NoGcHook) uom_quantity_runtime_expected.RQuantity.add(in uom_quantity_runtime_expected.RQuantity rhs) const pure nothrow @nogc @safe+/-: fallible. Same dim → ok; different dim → err (no throw).
add((local variable) const(uom_quantity_runtime_expected.RQuantity) secssecs);
void std.stdio.writeln!(string, string)(string __param_0, string __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("add(length, duration) [m + s] -> ", (local variable) expected.Expected!(RQuantity, DimError, NoGcHook) msErrmsErr.bool expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).hasError!()() const pure nothrow @nogc @property @safeChecks if Expected has error
hasError ? "err" : "ok");
if ((local variable) expected.Expected!(RQuantity, DimError, NoGcHook) msErrmsErr.bool expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).hasError!()() const pure nothrow @nogc @property @safeChecks if Expected has error
hasError)
void std.stdio.writeln!(string, string)(string __param_0, string __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln(" ", (local variable) expected.Expected!(RQuantity, DimError, NoGcHook) msErrmsErr.inout(uom_quantity_runtime_expected.DimError) expected.Expected!(uom_quantity_runtime_expected.RQuantity, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).error() inout pure nothrow @nogc @property @safeReturns the error value. May only be called when hasValue returns false.
If there is no error value, it calls hook's onAccessEmptyError.
It returns E.init when hook doesn't provide onAccessEmptyError.
error.string uom_quantity_runtime_expected.DimError.describe() const pure @safeA human-readable rendering (GC-allocating via unitString; used only
on the reporting path, never inside @nogc arithmetic).
describe);
void std.stdio.writeln!()() @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln();
// Multiplication is total: length · length is an area.
auto (local variable) uom_quantity_runtime_expected.RQuantity areaarea = (local variable) const(uom_quantity_runtime_expected.RQuantity) len1len1.uom_quantity_runtime_expected.RQuantity uom_quantity_runtime_expected.RQuantity.mul(in uom_quantity_runtime_expected.RQuantity rhs) const pure nothrow @nogc @safe*: total — any two dimensions combine, so it returns an RQuantity
directly (never an err). Length · Length → an area, and so on.
mul((local variable) const(uom_quantity_runtime_expected.RQuantity) len2len2);
void std.stdio.writeln!(string, uom_quantity_runtime_expected.RQuantity)(string __param_0, uom_quantity_runtime_expected.RQuantity __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("mul(length, length) is total -> ", (local variable) uom_quantity_runtime_expected.RQuantity areaarea);
// Composition: a runtime-dim Vec3 radiance sample — one Dim tag, three
// components, checked once.
const (local variable) const(uom_quantity_runtime_expected.RVec3) s1s1 = (struct) uom_quantity_runtime_expected.RVec3A dimensioned 3-vector, composition ordering A: the runtime Dim wraps
the Vec3, tagging all three components at once (one tag, not three).
RVec3((struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])Vec3(0.8, 0.2, 0.1), (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.radianceDim = Dim(1, 0, -3, -1)radianceDim);
const (local variable) const(uom_quantity_runtime_expected.RVec3) s2s2 = (struct) uom_quantity_runtime_expected.RVec3A dimensioned 3-vector, composition ordering A: the runtime Dim wraps
the Vec3, tagging all three components at once (one tag, not three).
RVec3((struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])Vec3(0.1, 0.3, 0.9), (constant) uom_quantity_runtime_expected.Dim uom_quantity_runtime_expected.radianceDim = Dim(1, 0, -3, -1)radianceDim);
void std.stdio.writeln!(string, const(uom_quantity_runtime_expected.RVec3))(string __param_0, const(uom_quantity_runtime_expected.RVec3) __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("RVec3 radiance sample s1 = ", (local variable) const(uom_quantity_runtime_expected.RVec3) s1s1);
void std.stdio.writeln!(string, uom_quantity_runtime_expected.RVec3)(string __param_0, uom_quantity_runtime_expected.RVec3 __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("add(s1, s2) [one Dim tag for 3 components] -> ", (local variable) const(uom_quantity_runtime_expected.RVec3) s1s1.expected.Expected!(RVec3, DimError, NoGcHook) uom_quantity_runtime_expected.RVec3.add(in uom_quantity_runtime_expected.RVec3 rhs) const pure nothrow @nogc @safeFallible add, mirroring RQuantity.add``: a single Dim compare guards
the whole vector.
add((local variable) const(uom_quantity_runtime_expected.RVec3) s2s2).inout(uom_quantity_runtime_expected.RVec3) expected.Expected!(uom_quantity_runtime_expected.RVec3, uom_quantity_runtime_expected.DimError, uom_quantity_runtime_expected.NoGcHook).value!()() inout pure nothrow @nogc @property @safeReturns the expected value if there is one.
With default Abort hook, it asserts when there is no value.
It calls hook's onAccessEmptyValue otherwise.
It returns T.init when hook doesn't provide onAccessEmptyValue.
value);
}