quantity-nominal.dhover×236all
#!/usr/bin/env dub
/+ dub.sdl:
    name "uom_quantity_nominal"
    dependency "sparkles:math" path="../../../.."
    dflags "-preview=in" "-preview=dip1000"
    targetPath "build"
+/
/**
 * Units of measure — the *nominal* fork of the kind system: one distinct struct
 * per quantity, with NO shared exponent algebra, as a raytracer would meet it.
 *
 * The graded prototypes (`quantity-zn-graded.d`, `quantity-affine-torsor.d`)
 * make a quantity's identity its exponent vector in `ℤⁿ`, so `*`/`/` are *total*
 * and every product has a type computed by the group operation. This file takes
 * the opposite design-space point — the one [squants][squants] (Scala) and
 * [Swift Foundation `Measurement`][swift] occupy. Here each physical quantity is
 * its own hand-written struct — `struct Irradiance { double w_m2; }`,
 * `struct Radiance { double w_m2_sr; }`, `struct Position { Vec3 m; }` — and there
 * is no exponent group at all. Products and quotients are not derived: each legal
 * one is a *hand-wired* `opBinary` (`Radiance * SolidAngle → Irradiance`,
 * `Irradiance * Area → Power`, `Position - Position → Displacement`).
 *
 * The fork's upside is *kind for free*: because typing is nominal, `Radiance` and
 * `Irradiance` — or `Torque` and `Energy`, both dimensionally `N·m` — are simply
 * unrelated types, so `radiance + irradiance` and `torque + energy` do not compile
 * with no kind machinery written at all. This is exactly the distinction the
 * graded systems *cannot* make: to them `W·m⁻²·sr⁻¹ · sr` and `W·m⁻²` are the same
 * exponent vector.
 *
 * The cost is the Swift dead-end: an *undeclared* product has no type. Nothing
 * derives `Position * Position` — `!__traits(compiles, pos * pos)` unless you sit
 * down and hand-declare that struct and its `opBinary`. The combinatorial closure
 * the group gives you for free must be enumerated by hand, edge by edge.
 *
 * **Composition finding.** Nominal typing composes *poorly* with a generic vector.
 * A graded design reuses one template — `Quantity!(dim, Vec3)` — for every
 * vector-valued quantity (`Displacement`, `Direction`, a force field…), the
 * dimension riding along as a type parameter. The nominal fork *cannot*: with no
 * `dim` to parameterize on, each vector quantity must be its own bespoke struct
 * wrapping `Vec3` (`Position`, `Displacement`, … each re-declared, each re-wiring
 * `toString` and its own operators). So `sparkles:math`'s `Vector` is still used
 * as the payload (composition *ordering A*, dimension-wraps-vector), but the reuse
 * is per-struct boilerplate rather than one instantiation — the nominal fork
 * multiplies the surface that would compose with `Vector`, instead of factoring it.
 *
 * Companion to docs/research/units-of-measure/scala-squants.md and
 * docs/research/units-of-measure/swift-units.md (the two nominal data points),
 * and docs/research/units-of-measure/comparison.md § "Kinds: the shared blind
 * spot" (nominal typing as the counter-example to the graded-group hypothesis).
 *
 * Run with: `dub run --single quantity-nominal.d`
 */
module 
(module) uom_quantity_nominal

Units of measure — the nominal fork of the kind system: one distinct struct per quantity, with NO shared exponent algebra, as a raytracer would meet it.

The graded prototypes (quantity-zn-graded.d, quantity-affine-torsor.d) make a quantity's identity its exponent vector in ℤⁿ, so *// are total and every product has a type computed by the group operation. This file takes the opposite design-space point — the one [squants][squants] (Scala) and [Swift Foundation `Measurement`][swift] occupy. Here each physical quantity is its own hand-written struct — struct Irradiance { double w_m2; }, struct Radiance { double w_m2_sr; }, struct Position { Vec3 m; } — and there is no exponent group at all. Products and quotients are not derived: each legal one is a hand-wired opBinary (Radiance * SolidAngle → Irradiance, Irradiance * Area → Power, Position - Position → Displacement).

The fork's upside is kind for free: because typing is nominal, Radiance and Irradiance — or Torque and Energy, both dimensionally N·m — are simply unrelated types, so radiance + irradiance and torque + energy do not compile with no kind machinery written at all. This is exactly the distinction the graded systems cannot make: to them W·m⁻²·sr⁻¹ · sr and W·m⁻² are the same exponent vector.

The cost is the Swift dead-end: an undeclared product has no type. Nothing derives Position * Position!__traits(compiles, pos * pos) unless you sit down and hand-declare that struct and its opBinary. The combinatorial closure the group gives you for free must be enumerated by hand, edge by edge.

Composition finding. Nominal typing composes poorly with a generic vector. A graded design reuses one template — Quantity!(dim, Vec3) — for every vector-valued quantity (Displacement, Direction, a force field…), the dimension riding along as a type parameter. The nominal fork cannot: with no dim to parameterize on, each vector quantity must be its own bespoke struct wrapping Vec3 (Position, Displacement, … each re-declared, each re-wiring toString and its own operators). So sparkles:math's Vector is still used as the payload (composition ordering A, dimension-wraps-vector), but the reuse is per-struct boilerplate rather than one instantiation — the nominal fork multiplies the surface that would compose with Vector, instead of factoring it.

Companion to docs/research/units-of-measure/scala-squants.md and docs/research/units-of-measure/swift-units.md (the two nominal data points), and docs/research/units-of-measure/comparison.md § "Kinds: the shared blind spot" (nominal typing as the counter-example to the graded-group hypothesis).

Run with: dub run --single quantity-nominal.d

uom_quantity_nominal
;
import
(package) sparkles
sparkles
.
(package) sparkles.math
math
.
(module) sparkles.math.vector

Vector 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_nominal.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_nominal.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);
// ─── Scalar radiometric quantities ─────────────────────────────────────────── // // Each is a DISTINCT struct. There is no exponent vector anywhere: `Radiance` // does not "know" it is `W·m⁻²·sr⁻¹`; that fact lives only in the hand-wired // products below and in the human-readable `unit` label. /// Radiant power, in watts (W). The energy flux leaving a source per second. struct
(struct) uom_quantity_nominal.Power

Radiant power, in watts (W). The energy flux leaving a source per second.

Power
{ double
(field) double uom_quantity_nominal.Power.w
w
;
enum
(constant) string uom_quantity_nominal.Power.unit = "W"
unit
= "W";
(alias) object.string = string
string
string uom_quantity_nominal.Power.toString() const @safe
toString
() const @safe =>
string uom_quantity_nominal.scalarLabel(in double v, in string unit) @safe

Render a scalar quantity as value unit``.

scalarLabel
(
(field) double uom_quantity_nominal.Power.w
w
,
(constant) string uom_quantity_nominal.Power.unit = "W"
unit
);
} /// Projected solid angle, in steradians (sr). Dimensionless in SI, but a /// *distinct nominal type* here — that is the whole point. struct
(struct) uom_quantity_nominal.SolidAngle

Projected solid angle, in steradians (sr). Dimensionless in SI, but a distinct nominal type here — that is the whole point.

SolidAngle
{ double
(field) double uom_quantity_nominal.SolidAngle.sr
sr
;
enum
(constant) string uom_quantity_nominal.SolidAngle.unit = "sr"
unit
= "sr";
(alias) object.string = string
string
string uom_quantity_nominal.SolidAngle.toString() const @safe
toString
() const @safe =>
string uom_quantity_nominal.scalarLabel(in double v, in string unit) @safe

Render a scalar quantity as value unit``.

scalarLabel
(
(field) double uom_quantity_nominal.SolidAngle.sr
sr
,
(constant) string uom_quantity_nominal.SolidAngle.unit = "sr"
unit
);
} /// Area, in square metres (m²) — e.g. a differential surface patch `dA`. struct
(struct) uom_quantity_nominal.Area

Area, in square metres (m²) — e.g. a differential surface patch dA.

Area
{ double
(field) double uom_quantity_nominal.Area.m2
m2
;
enum
(constant) string uom_quantity_nominal.Area.unit = "m^2"
unit
= "m^2";
(alias) object.string = string
string
string uom_quantity_nominal.Area.toString() const @safe
toString
() const @safe =>
string uom_quantity_nominal.scalarLabel(in double v, in string unit) @safe

Render a scalar quantity as value unit``.

scalarLabel
(
(field) double uom_quantity_nominal.Area.m2
m2
,
(constant) string uom_quantity_nominal.Area.unit = "m^2"
unit
);
} /// Irradiance, in W·m⁻²: power arriving per unit area on a surface. struct
(struct) uom_quantity_nominal.Irradiance

Irradiance, in W·m⁻²: power arriving per unit area on a surface.

Irradiance
{ double
(field) double uom_quantity_nominal.Irradiance.w_m2
w_m2
;
enum
(constant) string uom_quantity_nominal.Irradiance.unit = "W m^-2"
unit
= "W m^-2";
(alias) object.string = string
string
string uom_quantity_nominal.Irradiance.toString() const @safe
toString
() const @safe =>
string uom_quantity_nominal.scalarLabel(in double v, in string unit) @safe

Render a scalar quantity as value unit``.

scalarLabel
(
(field) double uom_quantity_nominal.Irradiance.w_m2
w_m2
,
(constant) string uom_quantity_nominal.Irradiance.unit = "W m^-2"
unit
);
/// HAND-WIRED: `Irradiance * Area → Power` (W·m⁻² · m² = W). The group would /// *derive* this; nominally we enumerate it.
(struct) uom_quantity_nominal.Power

Radiant power, in watts (W). The energy flux leaving a source per second.

Power
uom_quantity_nominal.Power uom_quantity_nominal.Irradiance.opBinary!"*"(in uom_quantity_nominal.Area a) const pure nothrow @nogc @safe

HAND-WIRED: Irradiance * Area → Power (W·m⁻² · m² = W). The group would derive this; nominally we enumerate it.

opBinary
(string op : "*")(in
(struct) uom_quantity_nominal.Area

Area, in square metres (m²) — e.g. a differential surface patch dA.

Area
(parameter) const(uom_quantity_nominal.Area) a
a
) const @safe pure nothrow @nogc
=>
(struct) uom_quantity_nominal.Power

Radiant power, in watts (W). The energy flux leaving a source per second.

Power
(
(field) double uom_quantity_nominal.Irradiance.w_m2
w_m2
*
(parameter) const(uom_quantity_nominal.Area) a
a
.
(field) double uom_quantity_nominal.Area.m2
m2
);
} /// Radiance, in W·m⁻²·sr⁻¹: the raytracer's central quantity — power per unit /// projected area per unit solid angle, carried along a ray. struct
(struct) uom_quantity_nominal.Radiance

Radiance, in W·m⁻²·sr⁻¹: the raytracer's central quantity — power per unit projected area per unit solid angle, carried along a ray.

Radiance
{ double
(field) double uom_quantity_nominal.Radiance.w_m2_sr
w_m2_sr
;
enum
(constant) string uom_quantity_nominal.Radiance.unit = "W m^-2 sr^-1"
unit
= "W m^-2 sr^-1";
(alias) object.string = string
string
string uom_quantity_nominal.Radiance.toString() const @safe
toString
() const @safe =>
string uom_quantity_nominal.scalarLabel(in double v, in string unit) @safe

Render a scalar quantity as value unit``.

scalarLabel
(
(field) double uom_quantity_nominal.Radiance.w_m2_sr
w_m2_sr
,
(constant) string uom_quantity_nominal.Radiance.unit = "W m^-2 sr^-1"
unit
);
/// HAND-WIRED: `Radiance * SolidAngle → Irradiance` (W·m⁻²·sr⁻¹ · sr = /// W·m⁻²) — integrating radiance over a cone of directions. The canonical /// nominal edge: the sr cancels only because *we said so* on this line.
(struct) uom_quantity_nominal.Irradiance

Irradiance, in W·m⁻²: power arriving per unit area on a surface.

Irradiance
uom_quantity_nominal.Irradiance uom_quantity_nominal.Radiance.opBinary!"*"(in uom_quantity_nominal.SolidAngle s) const pure nothrow @nogc @safe

HAND-WIRED: Radiance * SolidAngle → Irradiance (W·m⁻²·sr⁻¹ · sr = W·m⁻²) — integrating radiance over a cone of directions. The canonical nominal edge: the sr cancels only because we said so on this line.

opBinary
(string op : "*")(in
(struct) uom_quantity_nominal.SolidAngle

Projected solid angle, in steradians (sr). Dimensionless in SI, but a distinct nominal type here — that is the whole point.

SolidAngle
(parameter) const(uom_quantity_nominal.SolidAngle) s
s
) const @safe pure nothrow @nogc
=>
(struct) uom_quantity_nominal.Irradiance

Irradiance, in W·m⁻²: power arriving per unit area on a surface.

Irradiance
(
(field) double uom_quantity_nominal.Radiance.w_m2_sr
w_m2_sr
*
(parameter) const(uom_quantity_nominal.SolidAngle) s
s
.
(field) double uom_quantity_nominal.SolidAngle.sr
sr
);
} // ─── The kind-for-free pair: Torque vs Energy ──────────────────────────────── // // Both are dimensionally N·m = kg·m²·s⁻². A graded system gives them the SAME // type and so type-checks `torque + energy`. Nominal typing makes them unrelated // structs — the distinction the survey calls "kind" — for free, no tags written. /// Torque (moment of force), in N·m. Dimensionally identical to `Energy`. struct
(struct) uom_quantity_nominal.Torque

Torque (moment of force), in N·m. Dimensionally identical to Energy.

Torque
{ double
(field) double uom_quantity_nominal.Torque.n_m
n_m
;
enum
(constant) string uom_quantity_nominal.Torque.unit = "N m"
unit
= "N m";
(alias) object.string = string
string
string uom_quantity_nominal.Torque.toString() const @safe
toString
() const @safe =>
string uom_quantity_nominal.scalarLabel(in double v, in string unit) @safe

Render a scalar quantity as value unit``.

scalarLabel
(
(field) double uom_quantity_nominal.Torque.n_m
n_m
,
(constant) string uom_quantity_nominal.Torque.unit = "N m"
unit
);
} /// Energy / work, in joules (J = N·m). Dimensionally identical to `Torque`, /// but a *distinct nominal type* — so `torque + energy` cannot compile. struct
(struct) uom_quantity_nominal.Energy

Energy / work, in joules (J = N·m). Dimensionally identical to Torque, but a distinct nominal type — so torque + energy cannot compile.

Energy
{ double
(field) double uom_quantity_nominal.Energy.j
j
;
enum
(constant) string uom_quantity_nominal.Energy.unit = "J"
unit
= "J";
(alias) object.string = string
string
string uom_quantity_nominal.Energy.toString() const @safe
toString
() const @safe =>
string uom_quantity_nominal.scalarLabel(in double v, in string unit) @safe

Render a scalar quantity as value unit``.

scalarLabel
(
(field) double uom_quantity_nominal.Energy.j
j
,
(constant) string uom_quantity_nominal.Energy.unit = "J"
unit
);
} // ─── Vector-valued quantities: the composition finding, made concrete ───────── // // Position and Displacement BOTH wrap a `Vec3` of metres, yet — with no `dim` to // parameterize on — each must be its own struct. There is no single // `Quantity!(lengthDim, Vec3)` serving both, as in quantity-affine-torsor.d. // This bespoke-per-quantity duplication IS the poor `Vector` reuse. /// An affine world position, in metres. A distinct nominal type from /// `Displacement`, even though both are just a `Vec3` of metres. struct
(struct) uom_quantity_nominal.Position

An affine world position, in metres. A distinct nominal type from Displacement, even though both are just a Vec3 of metres.

Position
{
(alias) uom_quantity_nominal.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_nominal.Position.m
m
;
(alias) object.string = string
string
string uom_quantity_nominal.Position.toString() const @safe
toString
() const @safe =>
string uom_quantity_nominal.vecLabel(in sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) v, in string unit) @safe

Render a Vec3-valued quantity through an appender sink — never writeln or format(vec) directly, whose LockingTextWriter fails Vector.toString's scope analysis under -preview=dip1000.

vecLabel
(
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_nominal.Position.m
m
, "m (pos)");
/// HAND-WIRED: `Position - Position → Displacement`. Subtraction of two /// positions is the only affine combination that has a declared type.
(struct) uom_quantity_nominal.Displacement

A free length-vector (the difference of two positions), in metres. A distinct nominal struct wrapping the same Vec3 payload as Position — the duplication the composition finding is about.

Displacement
uom_quantity_nominal.Displacement uom_quantity_nominal.Position.opBinary!"-"(in uom_quantity_nominal.Position rhs) const pure nothrow @nogc @safe

HAND-WIRED: Position - Position → Displacement. Subtraction of two positions is the only affine combination that has a declared type.

opBinary
(string op : "-")(in
(struct) uom_quantity_nominal.Position

An affine world position, in metres. A distinct nominal type from Displacement, even though both are just a Vec3 of metres.

Position
(parameter) const(uom_quantity_nominal.Position) rhs
rhs
) const @safe pure nothrow @nogc
=>
(struct) uom_quantity_nominal.Displacement

A free length-vector (the difference of two positions), in metres. A distinct nominal struct wrapping the same Vec3 payload as Position — the duplication the composition finding is about.

Displacement
(
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_nominal.Position.m
m
-
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 @safe

Component-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 @safe

Component-wise vector addition/subtraction.

m
);
/// HAND-WIRED: `Position + Displacement → Position` — offset a point.
(struct) uom_quantity_nominal.Position

An affine world position, in metres. A distinct nominal type from Displacement, even though both are just a Vec3 of metres.

Position
uom_quantity_nominal.Position uom_quantity_nominal.Position.opBinary!"+"(in uom_quantity_nominal.Displacement d) const pure nothrow @nogc @safe

HAND-WIRED: Position + Displacement → Position — offset a point.

opBinary
(string op : "+")(in
(struct) uom_quantity_nominal.Displacement

A free length-vector (the difference of two positions), in metres. A distinct nominal struct wrapping the same Vec3 payload as Position — the duplication the composition finding is about.

Displacement
(parameter) const(uom_quantity_nominal.Displacement) d
d
) const @safe pure nothrow @nogc
=>
(struct) uom_quantity_nominal.Position

An affine world position, in metres. A distinct nominal type from Displacement, even though both are just a Vec3 of metres.

Position
(
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_nominal.Position.m
m
+
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 @safe

Component-wise vector addition/subtraction.

d
.
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 @safe

Component-wise vector addition/subtraction.

m
);
} /// A free length-vector (the difference of two positions), in metres. A distinct /// nominal struct wrapping the *same* `Vec3` payload as `Position` — the /// duplication the composition finding is about. struct
(struct) uom_quantity_nominal.Displacement

A free length-vector (the difference of two positions), in metres. A distinct nominal struct wrapping the same Vec3 payload as Position — the duplication the composition finding is about.

Displacement
{
(alias) uom_quantity_nominal.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_nominal.Displacement.m
m
;
(alias) object.string = string
string
string uom_quantity_nominal.Displacement.toString() const @safe
toString
() const @safe =>
string uom_quantity_nominal.vecLabel(in sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) v, in string unit) @safe

Render a Vec3-valued quantity through an appender sink — never writeln or format(vec) directly, whose LockingTextWriter fails Vector.toString's scope analysis under -preview=dip1000.

vecLabel
(
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_nominal.Displacement.m
m
, "m (disp)");
} // ─── Shared rendering helpers (CTFE-friendly, run at runtime here) ──────────── /// Render a scalar quantity as `value unit`. private
(alias) object.string = string
string
string uom_quantity_nominal.scalarLabel(in double v, in string unit) @safe

Render a scalar quantity as value unit``.

scalarLabel
(in double
(parameter) const(double) v
v
, in
(alias) object.string = string
string
(parameter) const(string) unit
unit
) @safe
{ import
(package) std
std
.
(module) std.array

Functions 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

@copyrightCopyright Andrei Alexandrescu 2008- and Jonathan M Davis 2011-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu and Jonathan M Davis
array
:
(alias template) appender = std.array.appender(A)() if (isDynamicArray!A)

Convenience function that returns an $(LREF Appender) instance, optionally initialized with array.

appender
;
import
(package) std
std
.
(module) std.format

This 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");
@copyrightCopyright The D Language Foundation 2000-2021.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, and Kenji Hara
format
:
(alias template) formattedWrite = std.format.write.formattedWrite(Writer, Char, Args...)(auto ref Writer w, scope const Char[] fmt, Args args)

Converts its arguments according to a format string and writes the result to an output range.

The second version of formattedWrite takes the format string as a template argument. In this case, it is checked for consistency at compile-time.

Params: w = an $(REF_ALTTEXT output range, isOutputRange, std, range, primitives), where the formatted result is written to fmt = a $(MREF_ALTTEXT format string, std,format) args = a variadic list of arguments to be formatted Writer = the type of the writer w Char = character type of fmt Args = a variadic list of types of the arguments

Returns: The index of the last argument that was formatted. If no positional arguments are used, this is the number of arguments that where formatted.

Throws: A $(REF_ALTTEXT FormatException, FormatException, std, format) if formatting did not succeed.

Note: In theory this function should be @nogc. But with the current implementation there are some cases where allocations occur. See $(REF_ALTTEXT $(D sformat), sformat, std, format) for more details.

formattedWrite
;
auto
(local variable) std.array.Appender!string sink
sink
=
std.array.Appender!string std.array.appender!string() pure nothrow @safe

Convenience function that returns an Appender instance, optionally initialized with array.

appender
!
(alias) object.string = string
string
();
uint std.format.write.formattedWrite!(std.array.Appender!string, char, const(double), string)(ref std.array.Appender!string w, scope const(char[]) fmt, const(double) __param_2, string __param_3) pure @safe

Converts its arguments according to a format string and writes the result to an output range.

The second version of formattedWrite takes the format string as a template argument. In this case, it is checked for consistency at compile-time.

Note

In theory this function should be @nogc. But with the current implementation there are some cases where allocations occur. See sformat for more details.

Examples

import std.array : appender;

auto writer1 = appender!string();
formattedWrite(writer1, "%s is the ultimate %s.", 42, "answer");
assert(writer1[] == "42 is the ultimate answer.");

auto writer2 = appender!string();
formattedWrite(writer2, "Increase: %7.2f %%", 17.4285);
assert(writer2[] == "Increase:   17.43 %");
@paramw an output range, where the formatted result is written to@paramfmt a format string@paramargs a variadic list of arguments to be formatted@paramWriter the type of the writer w@paramChar character type of fmt@paramArgs a variadic list of types of the arguments@returnsThe index of the last argument that was formatted. If no positional arguments are used, this is the number of arguments that where formatted.@throwsA FormatException if formatting did not succeed.
formattedWrite
(
(local variable) std.array.Appender!string sink
sink
, "%.6g %s",
(parameter) const(double) v
v
,
(parameter) const(string) unit
unit
);
return
(local variable) std.array.Appender!string sink
sink
[];
} /// Render a `Vec3`-valued quantity through an `appender` sink — never `writeln` /// or `format(vec)` directly, whose `LockingTextWriter` fails `Vector.toString`'s /// `scope` analysis under `-preview=dip1000`. private
(alias) object.string = string
string
string uom_quantity_nominal.vecLabel(in sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) v, in string unit) @safe

Render a Vec3-valued quantity through an appender sink — never writeln or format(vec) directly, whose LockingTextWriter fails Vector.toString's scope analysis under -preview=dip1000.

vecLabel
(in
(alias) uom_quantity_nominal.Vec3 = sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])

The raytracer's numeric payload for a 3-vector quantity.

Vec3
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) v
v
, in
(alias) object.string = string
string
(parameter) const(string) unit
unit
) @safe
{ import
(package) std
std
.
(module) std.array

Functions 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

@copyrightCopyright Andrei Alexandrescu 2008- and Jonathan M Davis 2011-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu and Jonathan M Davis
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 sink
sink
=
std.array.Appender!string std.array.appender!string() pure nothrow @safe

Convenience function that returns an Appender instance, optionally initialized with array.

appender
!
(alias) object.string = string
string
();
(parameter) const(sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])) v
v
.
void sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).toString!(std.array.Appender!string)(ref scope std.array.Appender!string writer) const pure @safe

Writes the vector as (name0: value0, name1: value1, ...).

toString
(
(local variable) std.array.Appender!string sink
sink
);
(local variable) std.array.Appender!string sink
sink
.
void std.array.Appender!string.put!string(string items) pure nothrow @safe

Appends an entire range to the managed array. Performs encoding for char elements if A is a differently typed char array.

@paramitems the range of items to append
put
(" ");
(local variable) std.array.Appender!string sink
sink
.
void std.array.Appender!string.put!string(string items) pure nothrow @safe

Appends an entire range to the managed array. Performs encoding for char elements if A is a differently typed char array.

@paramitems the range of items to append
put
(
(parameter) const(string) unit
unit
);
return
(local variable) std.array.Appender!string sink
sink
[];
} @("Quantity.nominal.hand-wired-products-and-kind-for-free") @safe pure nothrow @nogc unittest { // Hand-wired radiometric edges resolve to their declared nominal types. auto
(local variable) uom_quantity_nominal.Radiance radiance
radiance
=
(struct) uom_quantity_nominal.Radiance

Radiance, in W·m⁻²·sr⁻¹: the raytracer's central quantity — power per unit projected area per unit solid angle, carried along a ray.

Radiance
(100.0);
auto
(local variable) uom_quantity_nominal.SolidAngle cone
cone
=
(struct) uom_quantity_nominal.SolidAngle

Projected solid angle, in steradians (sr). Dimensionless in SI, but a distinct nominal type here — that is the whole point.

SolidAngle
(0.5);
auto
(local variable) uom_quantity_nominal.Irradiance e
e
=
(local variable) uom_quantity_nominal.Radiance radiance
radiance
*
uom_quantity_nominal.Irradiance uom_quantity_nominal.Radiance.opBinary!"*"(in uom_quantity_nominal.SolidAngle s) const pure nothrow @nogc @safe

HAND-WIRED: Radiance * SolidAngle → Irradiance (W·m⁻²·sr⁻¹ · sr = W·m⁻²) — integrating radiance over a cone of directions. The canonical nominal edge: the sr cancels only because we said so on this line.

cone
;
static assert(is(typeof(
(local variable) uom_quantity_nominal.Irradiance e
e
) == Irradiance),
"Radiance * SolidAngle must be Irradiance"); assert(
(local variable) uom_quantity_nominal.Irradiance e
e
.
(field) double uom_quantity_nominal.Irradiance.w_m2
w_m2
== 50.0);
auto
(local variable) uom_quantity_nominal.Power received
received
=
(local variable) uom_quantity_nominal.Irradiance e
e
*
uom_quantity_nominal.Power uom_quantity_nominal.Irradiance.opBinary!"*"(in uom_quantity_nominal.Area a) const pure nothrow @nogc @safe

HAND-WIRED: Irradiance * Area → Power (W·m⁻² · m² = W). The group would derive this; nominally we enumerate it.

Area
(2.0);
static assert(is(typeof(
(local variable) uom_quantity_nominal.Power received
received
) == Power),
"Irradiance * Area must be Power"); assert(
(local variable) uom_quantity_nominal.Power received
received
.
(field) double uom_quantity_nominal.Power.w
w
== 100.0);
// Kind for free: Radiance and Irradiance are unrelated, so no `+`. static assert(!__traits(compiles,
(local variable) uom_quantity_nominal.Radiance radiance
radiance
+
(local variable) uom_quantity_nominal.Irradiance e
e
),
"radiance + irradiance must not compile (distinct nominal kinds)"); // Torque vs Energy — dimensionally both N·m, nominally distinct. static assert(!__traits(compiles,
(struct) uom_quantity_nominal.Torque

Torque (moment of force), in N·m. Dimensionally identical to Energy.

Torque
(3.0) +
(struct) uom_quantity_nominal.Energy

Energy / work, in joules (J = N·m). Dimensionally identical to Torque, but a distinct nominal type — so torque + energy cannot compile.

Energy
(3.0)),
"torque + energy must not compile (distinct nominal kinds)"); // Affine geometry: the two hand-wired edges exist... auto
(local variable) uom_quantity_nominal.Position a
a
=
(struct) uom_quantity_nominal.Position

An affine world position, in metres. A distinct nominal type from Displacement, even though both are just a Vec3 of metres.

Position
(
(struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])
Vec3
(0, 0, 0));
auto
(local variable) uom_quantity_nominal.Position b
b
=
(struct) uom_quantity_nominal.Position

An affine world position, in metres. A distinct nominal type from Displacement, even though both are just a Vec3 of metres.

Position
(
(struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])
Vec3
(3, 4, 0));
auto
(local variable) uom_quantity_nominal.Displacement d
d
=
(local variable) uom_quantity_nominal.Position b
b
-
uom_quantity_nominal.Displacement uom_quantity_nominal.Position.opBinary!"-"(in uom_quantity_nominal.Position rhs) const pure nothrow @nogc @safe

HAND-WIRED: Position - Position → Displacement. Subtraction of two positions is the only affine combination that has a declared type.

a
;
static assert(is(typeof(
(local variable) uom_quantity_nominal.Displacement d
d
) == Displacement));
assert(
(local variable) uom_quantity_nominal.Displacement d
d
.
(field) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) uom_quantity_nominal.Displacement.m
m
==
bool sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]).opEquals(in sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"]) rhs) const pure nothrow @nogc @safe

Component-wise equality (compares the backing components directly, so it is well-defined despite the union — the compiler-generated == over a union is not).

Vec3
(3, 4, 0));
static assert(is(typeof(
(local variable) uom_quantity_nominal.Position a
a
+
uom_quantity_nominal.Position uom_quantity_nominal.Position.opBinary!"+"(in uom_quantity_nominal.Displacement d) const pure nothrow @nogc @safe

HAND-WIRED: Position + Displacement → Position — offset a point.

d
) == Position));
// ...but the UNDECLARED product has no type (the Swift dead-end). static assert(!__traits(compiles,
(local variable) uom_quantity_nominal.Position a
a
*
(local variable) uom_quantity_nominal.Position b
b
),
"Position * Position is undeclared — nominally it has no type at all"); } void
void D main() @safe
main
() @safe
{ import
(package) std
std
.
(module) std.stdio
Category 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:

  1. The lowest layer is the operating system layer. The two main schemes are Windows and Posix.

  2. C's stdio.h which unifies the two operating system schemes.

  3. std.stdio, this module, unifies the various stdio.h implementations into a high level package for D programs.

Source

std/stdio.d

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Alex Rønne Petersen
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
;
// A hand-enumerated radiometric chain: radiance → irradiance → power. const
(local variable) const(uom_quantity_nominal.Radiance) radiance
radiance
=
(struct) uom_quantity_nominal.Radiance

Radiance, in W·m⁻²·sr⁻¹: the raytracer's central quantity — power per unit projected area per unit solid angle, carried along a ray.

Radiance
(120.0); // W·m⁻²·sr⁻¹ along a ray
const
(local variable) const(uom_quantity_nominal.SolidAngle) cone
cone
=
(struct) uom_quantity_nominal.SolidAngle

Projected solid angle, in steradians (sr). Dimensionless in SI, but a distinct nominal type here — that is the whole point.

SolidAngle
(0.25); // sr subtended by the light
const
(local variable) const(uom_quantity_nominal.Area) patch
patch
=
(struct) uom_quantity_nominal.Area

Area, in square metres (m²) — e.g. a differential surface patch dA.

Area
(2.0); // m² of receiving surface
const
(local variable) const(uom_quantity_nominal.Irradiance) irradiance
irradiance
=
(local variable) const(uom_quantity_nominal.Radiance) radiance
radiance
*
uom_quantity_nominal.Irradiance uom_quantity_nominal.Radiance.opBinary!"*"(in uom_quantity_nominal.SolidAngle s) const pure nothrow @nogc @safe

HAND-WIRED: Radiance * SolidAngle → Irradiance (W·m⁻²·sr⁻¹ · sr = W·m⁻²) — integrating radiance over a cone of directions. The canonical nominal edge: the sr cancels only because we said so on this line.

cone
; // hand-wired: sr cancels
const
(local variable) const(uom_quantity_nominal.Power) power
power
=
(local variable) const(uom_quantity_nominal.Irradiance) irradiance
irradiance
*
uom_quantity_nominal.Power uom_quantity_nominal.Irradiance.opBinary!"*"(in uom_quantity_nominal.Area a) const pure nothrow @nogc @safe

HAND-WIRED: Irradiance * Area → Power (W·m⁻² · m² = W). The group would derive this; nominally we enumerate it.

patch
; // hand-wired: m² cancels
void std.stdio.writeln!(string, const(uom_quantity_nominal.Radiance))(string __param_0, const(uom_quantity_nominal.Radiance) __param_1) @safe

Equivalent 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);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("radiance = ",
(local variable) const(uom_quantity_nominal.Radiance) radiance
radiance
);
void std.stdio.writeln!(string, const(uom_quantity_nominal.SolidAngle))(string __param_0, const(uom_quantity_nominal.SolidAngle) __param_1) @safe

Equivalent 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);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("solid angle = ",
(local variable) const(uom_quantity_nominal.SolidAngle) cone
cone
);
void std.stdio.writeln!(string, const(uom_quantity_nominal.Irradiance), string)(string __param_0, const(uom_quantity_nominal.Irradiance) __param_1, string __param_2) @safe

Equivalent 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);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("irradiance = ",
(local variable) const(uom_quantity_nominal.Irradiance) irradiance
irradiance
, " (Radiance * SolidAngle)");
void std.stdio.writeln!(string, const(uom_quantity_nominal.Area))(string __param_0, const(uom_quantity_nominal.Area) __param_1) @safe

Equivalent 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);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("area = ",
(local variable) const(uom_quantity_nominal.Area) patch
patch
);
void std.stdio.writeln!(string, const(uom_quantity_nominal.Power), string)(string __param_0, const(uom_quantity_nominal.Power) __param_1, string __param_2) @safe

Equivalent 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);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("power on patch = ",
(local variable) const(uom_quantity_nominal.Power) power
power
, " (Irradiance * Area)");
// Kind for free — these hold precisely because the additions do NOT compile. static assert(!__traits(compiles,
(local variable) const(uom_quantity_nominal.Radiance) radiance
radiance
+
(local variable) const(uom_quantity_nominal.Irradiance) irradiance
irradiance
),
"Radiance + Irradiance must not compile"); static assert(!__traits(compiles,
(struct) uom_quantity_nominal.Torque

Torque (moment of force), in N·m. Dimensionally identical to Energy.

Torque
(1.0) +
(struct) uom_quantity_nominal.Energy

Energy / work, in joules (J = N·m). Dimensionally identical to Torque, but a distinct nominal type — so torque + energy cannot compile.

Energy
(1.0)),
"Torque + Energy must not compile — kind distinction is free here");
void std.stdio.writeln!string(string __param_0) @safe

Equivalent 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);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("kind for free : Radiance+Irradiance and Torque+Energy both rejected");
// Affine geometry over a bespoke Vec3-wrapping struct pair. const
(local variable) const(uom_quantity_nominal.Position) eye
eye
=
(struct) uom_quantity_nominal.Position

An affine world position, in metres. A distinct nominal type from Displacement, even though both are just a Vec3 of metres.

Position
(
(struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])
Vec3
(0, 1, 4));
const
(local variable) const(uom_quantity_nominal.Position) target
target
=
(struct) uom_quantity_nominal.Position

An affine world position, in metres. A distinct nominal type from Displacement, even though both are just a Vec3 of metres.

Position
(
(struct) sparkles.math.vector.Vector!(double, 3LU, ["x", "y", "z"])
Vec3
(0, 0, 0));
auto
(local variable) uom_quantity_nominal.Displacement look
look
=
(local variable) const(uom_quantity_nominal.Position) target
target
-
uom_quantity_nominal.Displacement uom_quantity_nominal.Position.opBinary!"-"(in uom_quantity_nominal.Position rhs) const pure nothrow @nogc @safe

HAND-WIRED: Position - Position → Displacement. Subtraction of two positions is the only affine combination that has a declared type.

eye
; // hand-wired: Position - Position
static assert(is(typeof(
(local variable) uom_quantity_nominal.Displacement look
look
) == Displacement));
void std.stdio.writeln!(string, const(uom_quantity_nominal.Position))(string __param_0, const(uom_quantity_nominal.Position) __param_1) @safe

Equivalent 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);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("eye = ",
(local variable) const(uom_quantity_nominal.Position) eye
eye
);
void std.stdio.writeln!(string, const(uom_quantity_nominal.Position))(string __param_0, const(uom_quantity_nominal.Position) __param_1) @safe

Equivalent 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);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("target = ",
(local variable) const(uom_quantity_nominal.Position) target
target
);
void std.stdio.writeln!(string, uom_quantity_nominal.Displacement, string)(string __param_0, uom_quantity_nominal.Displacement __param_1, string __param_2) @safe

Equivalent 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);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("look (t - e) = ",
(local variable) uom_quantity_nominal.Displacement look
look
, " (Position - Position)");
// The Swift dead-end: an undeclared product simply has no type. static assert(!__traits(compiles,
(local variable) const(uom_quantity_nominal.Position) eye
eye
*
(local variable) const(uom_quantity_nominal.Position) target
target
),
"Position * Position is undeclared — nominally unnameable");
void std.stdio.writeln!string(string __param_0) @safe

Equivalent 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);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("dead-end : Position * Position has no type (undeclared product)");
}