#!/usr/bin/env dub
/+ dub.sdl:
name "gen-sdl-datasets"
buildType "checked" {
buildOptions "optimize" "inline" "debugInfo"
}
+/
/**
Derives the two generated SDL benchmark datasets of the `wired_bench` runtime
harness. `nix/packages/wired-bench-data.nix` runs it at build time with
`ldc2 -run`, so it imports nothing but Phobos, and its output depends only on
its arguments: the same input tree gives the same bytes.
$(UL
$(LI `concat <recipes-dir> <out>` — every `dub.sdl` under `<recipes-dir>`, in
byte order of its relative path, wrapped as an inline `subPackage { … }`
block of one root recipe. The recipes' bytes are not read, only copied,
so the generator does no SDL work of its own (lossless editing SDE9); their
subpackage names may repeat, which the benchmark's schema does not mind.)
$(LI `deep-wide <out>` — a deep and wide SDL document over every scalar kind
DUB's pinned SDLang parser shares with `sdlFull`: chains nested 200 levels
deep, tags with 256 attributes and 64 values, and a balanced tree of
4⁶ leaves, filled from a fixed xorshift sequence.)
)
Run by hand with `dub run --single tools/gen-sdl-datasets.d -- deep-wide /tmp/x.sdl`.
A change to either output changes the dataset: regenerate the fingerprints
in `src/sparkles/wired_bench/sdl.d` in the same commit.
*/
module (module) gen_sdl_datasetsDerives the two generated SDL benchmark datasets of the wired_bench runtime
harness. nix/packages/wired-bench-data.nix runs it at build time with
ldc2 -run, so it imports nothing but Phobos, and its output depends only on
its arguments: the same input tree gives the same bytes.
concat <recipes-dir> <out> — every dub.sdl under <recipes-dir>, in
byte order of its relative path, wrapped as an inline subPackage { … }
block of one root recipe. The recipes' bytes are not read, only copied,
so the generator does no SDL work of its own (lossless editing SDE9); their
subpackage names may repeat, which the benchmark's schema does not mind.
deep-wide <out> — a deep and wide SDL document over every scalar kind
DUB's pinned SDLang parser shares with sdlFull: chains nested 200 levels
deep, tags with 256 attributes and 64 values, and a balanced tree of
4⁶ leaves, filled from a fixed xorshift sequence.
Run by hand with dub run --single tools/gen-sdl-datasets.d -- deep-wide /tmp/x.sdl.
A change to either output changes the dataset: regenerate the fingerprints
in src/sparkles/wired_bench/sdl.d in the same commit.
gen_sdl_datasets;
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.iterationThis is a submodule of std.algorithm.
It contains generic iteration algorithms.
Function Name Description cache Eagerly evaluates and caches another range's front. lazyCache Lazily evaluates and caches another range's front, unlike cache. cacheBidirectional As above, but also provides back and popBack. chunkBy chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]]) returns a range containing 3 subranges: the first with just [1, 1]; the second with the elements [1, 2] and [2, 2]; and the third with just [2, 1]. cumulativeFold cumulativeFold!((a, b) => a + b)([1, 2, 3, 4]) returns a lazily-evaluated range containing the successive reduced values 1, 3, 6, 10. each each!writeln([1, 2, 3]) eagerly prints the numbers 1, 2 and 3 on their own lines. filter filter!(a => a > 0)([1, -1, 2, 0, -3]) iterates over elements 1 and 2. filterBidirectional Similar to filter, but also provides back and popBack at a small increase in cost. fold fold!((a, b) => a + b)([1, 2, 3, 4]) returns 10. group group([5, 2, 2, 3, 3]) returns a range containing the tuples tuple(5, 1), tuple(2, 2), and tuple(3, 2). joiner joiner(["hello", "world!"], "; ") returns a range that iterates over the characters "hello; world!". No new string is created - the existing inputs are iterated. map map!(a => a * 2)([1, 2, 3]) lazily returns a range with the numbers 2, 4, 6. mean Colloquially known as the average, mean([1, 2, 3]) returns 2. permutations Lazily computes all permutations using Heap's algorithm. reduce reduce!((a, b) => a + b)([1, 2, 3, 4]) returns 10. This is the old implementation of fold. splitWhen Lazily splits a range by comparing adjacent elements. splitter Lazily splits a range by a separator, element predicate or whitespace. substitute [1, 2].substitute(1, 0.1) returns [0.1, 2]. sum Same as fold, but specialized for accurate summation. uniq Iterates over the unique elements in a range, which is assumed sorted.
Source
std/algorithm/iteration.d
iteration : (alias template) gen_sdl_datasets.map = std.algorithm.iteration.map(fun...) if (fun.length >= 1)Implements the homonym function (also known as transform) present
in many languages of functional flavor. The call ``map!(fun)(range)
returns a range of which elements are obtained by applying fun(a)
left to right for all elements a in range. The original ranges are
not changed. Evaluation is done lazily.
map;
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.sortingThis is a submodule of std.algorithm.
It contains generic sorting algorithms.
Function Name Description completeSort If a = [10, 20, 30] and b = [40, 6, 15], then completeSort(a, b) leaves a = [6, 10, 15] and b = [20, 30, 40]. The range a must be sorted prior to the call, and as a result the combination ``chain(a, b) is sorted. isPartitioned isPartitioned!"a < 0"([-1, -2, 1, 0, 2]) returns true because the predicate is true for a portion of the range and false afterwards. isSorted isSorted([1, 1, 2, 3]) returns true. isStrictlyMonotonic isStrictlyMonotonic([1, 1, 2, 3]) returns false. ordered ordered(1, 1, 2, 3) returns true. strictlyOrdered strictlyOrdered(1, 1, 2, 3) returns false. makeIndex Creates a separate index for a range. merge Lazily merges two or more sorted ranges. multiSort Sorts by multiple keys. nextEvenPermutation Computes the next lexicographically greater even permutation of a range in-place. nextPermutation Computes the next lexicographically greater permutation of a range in-place. nthPermutation Computes the nth permutation of a range in-place. partialSort If a = [5, 4, 3, 2, 1], then partialSort(a, 3) leaves a[0 .. 3] = [1, 2, 3]. The other elements of a are left in an unspecified order. partition Partitions a range according to a unary predicate. partition3 Partitions a range according to a binary predicate in three parts (less than, equal, greater than the given pivot). Pivot is not given as an index, but instead as an element independent from the range's content. pivotPartition Partitions a range according to a binary predicate in two parts: less than or equal, and greater than or equal to the given pivot, passed as an index in the range. schwartzSort Sorts with the help of the Schwartzian transform. sort Sorts. topN Separates the top elements in a range, akin to Quickselect. topNCopy Copies out the top elements of a range. topNIndex Builds an index of the top elements of a range.
Source
std/algorithm/sorting.d
sorting : (alias template) gen_sdl_datasets.sort = std.algorithm.sorting.sort(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r)Sorts a random-access range according to the predicate less.
Performs O(r.length * log(r.length)) evaluations of less. If less involves
expensive computations on the sort key, it may be worthwhile to use
schwartzSort instead.
Stable sorting requires hasAssignableElements!Range to be true.
sort returns a SortedRange over the original range,
allowing functions that can take advantage of sorted data to know that the
range is sorted and adjust accordingly. The SortedRange is a
wrapper around the original range, so both it and the original range are sorted.
Other functions can't know that the original range has been sorted, but
they can know that SortedRange has been sorted.
Preconditions
The predicate is expected to satisfy certain rules in order for sort to
behave as expected - otherwise, the program may fail on certain inputs (but not
others) when not compiled in release mode, due to the cursory assumeSorted
check. Specifically, sort expects less(a,b) && less(b,c) to imply
less(a,c) (transitivity), and, conversely, !less(a,b) && !less(b,c) to
imply !less(a,c). Note that the default predicate ("a < b") does not
always satisfy these conditions for floating point types, because the expression
will always be false when either a or b is NaN.
Use cmp instead.
Algorithms
Introsort is used for unstable sorting and
Timsort is used for stable sorting.
Each algorithm has benefits beyond stability. Introsort is generally faster but
Timsort may achieve greater speeds on data with low entropy or if predicate calls
are expensive. Introsort performs no allocations whereas Timsort will perform one
or more allocations per call. Both algorithms have O(n log n) worst-case
time complexity.
sort;
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) gen_sdl_datasets.appender = std.array.appender(A)() if (isDynamicArray!A)Convenience function that returns an Appender instance,
optionally initialized with array.
appender, (alias template) gen_sdl_datasets.array = std.array.array(Range)(Range r) if (isIterable!Range && !isAutodecodableString!Range && !isInfinite!Range)Allocates an array and initializes it with copies of the elements
of range r.
Narrow strings are handled as follows:
If autodecoding is turned on (default), then they are handled as a separate overload.
If autodecoding is turned off, then this is equivalent to duplicating the array.
array;
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) gen_sdl_datasets.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:
Integer:
Sign UnsignedInteger
UnsignedInteger
Sign:
+
-
For conversion to unsigned types, the grammar recognized is:
UnsignedInteger:
DecimalDigit
DecimalDigit UnsignedInteger
to;
import (package) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias template) gen_sdl_datasets.dirEntries = std.file.dirEntries(bool useDIP1000 = dip1000Enabled)(string path, SpanMode mode, bool followSymlink = true)Returns an input range
of DirEntry that lazily iterates a given directory,
also provides two ways of foreach iteration. The iteration variable can be of
type string if only the name is needed, or DirEntry
if additional details are needed. The span mode dictates how the
directory is traversed. The name of each iterated directory entry
contains the absolute or relative path (depending on pathname).
Note
The order of returned directory entries is as it is provided by the
operating system / filesystem, and may not follow any particular sorting.
Example
// Iterate a directory in depth
foreach (string name; dirEntries("destroy/me", SpanMode.depth))
{
remove(name);
}
// Iterate the current directory in breadth
foreach (string name; dirEntries("", SpanMode.breadth))
{
writeln(name);
}
// Iterate a directory and get detailed info about it
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
{
writeln(e.name, "\t", e.size);
}
// Iterate over all *.d files in current directory and all its subdirectories
auto dFiles = dirEntries("", SpanMode.depth).filter!(f => f.name.endsWith(".d"));
foreach (d; dFiles)
writeln(d.name);
// Hook it up with std.parallelism to compile them all in parallel:
foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread
{
string cmd = "dmd -c " ~ d.name;
writeln(cmd);
std.process.executeShell(cmd);
}
// Iterate over all D source files in current directory and all its
// subdirectories
auto dFiles = dirEntries("","*.{d,di}",SpanMode.depth);
foreach (d; dFiles)
writeln(d.name);
To handle subdirectories with denied read permission, use SpanMode.shallow:
void scan(string path)
{
foreach (DirEntry entry; dirEntries(path, SpanMode.shallow))
{
try
{
writeln(entry.name);
if (entry.isDir)
scan(entry.name);
}
catch (FileException fe) { continue; } // ignore
}
}
scan("");
dirEntries, (alias template) gen_sdl_datasets.readText = std.file.readText(S = string, R)(auto ref R name) if (isSomeString!S && (isSomeFiniteCharInputRange!R || is(StringTypeOf!R)))Reads and validates (using validate) a text file. S can be
an array of any character type. However, no width or endian conversions are
performed. So, if the width or endianness of the characters in the given
file differ from the width or endianness of the element type of S, then
validation will fail.
readText, (enum) std.file.SpanModeDictates directory spanning policy for dirEntries (see below).
Examples
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.algorithm.sorting : sort;
import std.array : array;
import std.path : buildPath, relativePath;
auto root = deleteme ~ "root";
scope(exit) root.rmdirRecurse;
root.mkdir;
root.buildPath("animals").mkdir;
root.buildPath("animals", "cat").mkdir;
alias removeRoot = (return scope e) => e.relativePath(root);
assert(root.dirEntries(SpanMode.depth).map!removeRoot.equal(
[buildPath("animals", "cat"), "animals"]));
assert(root.dirEntries(SpanMode.breadth).map!removeRoot.equal(
["animals", buildPath("animals", "cat")]));
root.buildPath("plants").mkdir;
assert(root.dirEntries(SpanMode.shallow).array.sort.map!removeRoot.equal(
["animals", "plants"]));
SpanMode, (alias template) gen_sdl_datasets.write = std.file.write(R)(R name, const void[] buffer) if ((isSomeFiniteCharInputRange!R || isSomeString!R) && !isConvertibleToString!R)Write buffer to file name.
Creates the file if it does not already exist.
write;
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) gen_sdl_datasets.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.
format;
import (package) stdstd.(module) std.pathThis module is used to manipulate path strings.
All functions, with the exception of expandTilde (and in some
cases absolutePath and relativePath), are pure
string manipulation functions; they don't depend on any state outside
the program, nor do they perform any actual file system actions.
This has the consequence that the module does not make any distinction
between a path that points to a directory and a path that points to a
file, and it does not know whether or not the object pointed to by the
path actually exists in the file system.
To differentiate between these cases, use isDir and
exists.
Note that on Windows, both the backslash (\) and the slash (/)
are in principle valid directory separators. This module treats them
both on equal footing, but in cases where a new separator is
added, a backslash will be used. Furthermore, the buildNormalizedPath
function will replace all slashes with backslashes on that platform.
In general, the functions in this module assume that the input paths
are well-formed. (That is, they should not contain invalid characters,
they should follow the file system's path format, etc.) The result
of calling a function on an ill-formed path is undefined. When there
is a chance that a path or a file name is invalid (for instance, when it
has been input by the user), it may sometimes be desirable to use the
isValidFilename and isValidPath functions to check
this.
Most functions do not perform any memory allocations, and if a string is
returned, it is usually a slice of an input string. If a function
allocates, this is explicitly mentioned in the documentation.
Category Functions Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension Other filenameCharCmp filenameCmp globMatch CaseSensitive
Source
std/path.d
path : (alias template) gen_sdl_datasets.relativePath = std.path.relativePath(CaseSensitive cs = CaseSensitive.osDefault)(string path, lazy string base = getcwd())Translates path into a relative path.
The returned path is relative to base, which is by default
taken to be the current working directory. If specified,
base must be an absolute path, and it is always assumed
to refer to a directory. If path and base refer to
the same directory, the function returns ..
The following algorithm is used:
If path is a relative directory, return it unaltered.
Find a common root between path and base.
If there is no common root, return path unaltered.
Prepare a string with as many ../ or ..\ as
necessary to reach the common root from base path.
Append the remaining segments of path to the string
and return.
In the second step, path components are compared using filenameCmp!cs,
where cs is an optional template parameter determining whether
the comparison is case sensitive or not. See the
filenameCmp documentation for details.
This function allocates memory.
relativePath;
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 : stderr;
int int D main(string[] args)main((alias) object.string = stringstring[] (parameter) string[] argsargs)
{
if ((parameter) string[] argsargs.(field) ulong string[].lengthlength == 4 && (parameter) string[] argsargs[1] == "concat")
void std.file.write!string(string name, const(void[]) buffer) @safeWrite buffer to file name.
Creates the file if it does not already exist.
Examples
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write(deleteme, a); // deleteme is the name of a temporary file
const bytes = read(deleteme);
const fileInts = () @trusted { return cast(int[]) bytes; }();
assert(fileInts == a);
write((parameter) string[] argsargs[3], string gen_sdl_datasets.concatRecipes(string root)The recipes under root as one recipe of inline subpackages: each
recipe's bytes, unread, inside subPackage { … }. Their names may repeat;
DUB would reject that, but the benchmark's schema does not ask.
concatRecipes((parameter) string[] argsargs[2]));
else if ((parameter) string[] argsargs.(field) ulong string[].lengthlength == 3 && (parameter) string[] argsargs[1] == "deep-wide")
void std.file.write!string(string name, const(void[]) buffer) @safeWrite buffer to file name.
Creates the file if it does not already exist.
Examples
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write(deleteme, a); // deleteme is the name of a temporary file
const bytes = read(deleteme);
const fileInts = () @trusted { return cast(int[]) bytes; }();
assert(fileInts == a);
write((parameter) string[] argsargs[2], string gen_sdl_datasets.deepWide()The generated deep-and-wide document.
deepWide());
else
{
stderr.std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @systemwriteln("usage: gen-sdl-datasets concat <recipes-dir> <out>\n"
~ " gen-sdl-datasets deep-wide <out>");
return 2;
}
return 0;
}
/// The recipes under `root` as one recipe of inline subpackages: each
/// recipe's bytes, unread, inside `subPackage { … }`. Their names may repeat;
/// DUB would reject that, but the benchmark's schema does not ask.
(alias) object.string = stringstring string gen_sdl_datasets.concatRecipes(string root)The recipes under root as one recipe of inline subpackages: each
recipe's bytes, unread, inside subPackage { … }. Their names may repeat;
DUB would reject that, but the benchmark's schema does not ask.
concatRecipes((alias) object.string = stringstring (parameter) string rootroot)
{
auto (local variable) string[] pathspaths = std.file.dirEntries!false.FilterResult!(f, _DirIterator!false) std.file.dirEntries!false(string path, string pattern, std.file.SpanMode mode, bool followSymlink = true) @systemDuplicate functionality of D1's std.file.listdir():
dirEntries((parameter) string rootroot, "dub.sdl", (enum) std.file.SpanModeDictates directory spanning policy for dirEntries (see below).
Examples
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.algorithm.sorting : sort;
import std.array : array;
import std.path : buildPath, relativePath;
auto root = deleteme ~ "root";
scope(exit) root.rmdirRecurse;
root.mkdir;
root.buildPath("animals").mkdir;
root.buildPath("animals", "cat").mkdir;
alias removeRoot = (return scope e) => e.relativePath(root);
assert(root.dirEntries(SpanMode.depth).map!removeRoot.equal(
[buildPath("animals", "cat"), "animals"]));
assert(root.dirEntries(SpanMode.breadth).map!removeRoot.equal(
["animals", buildPath("animals", "cat")]));
root.buildPath("plants").mkdir;
assert(root.dirEntries(SpanMode.shallow).array.sort.map!removeRoot.equal(
["animals", "plants"]));
SpanMode.(enum value) std.file.SpanMode.depth = 1Spans the directory in
depth-first post-order, i.e. the content of any
subdirectory is spanned before that subdirectory itself. Useful
e.g. when recursively deleting files.
depth)
.gen_sdl_datasets.concatRecipes.MapResult!(__lambda_L62_C15, FilterResult!(f, _DirIterator!false)) gen_sdl_datasets.concatRecipes.map!(std.file.dirEntries!false.FilterResult!(f, _DirIterator!false))(std.file.dirEntries!false.FilterResult!(f, _DirIterator!false) r) @systemImplements the homonym function (also known as transform) present
in many languages of functional flavor. The call ``map!(fun)(range)
returns a range of which elements are obtained by applying fun(a)
left to right for all elements a in range. The original ranges are
not changed. Evaluation is done lazily.
Examples
import std.algorithm.comparison : equal;
import std.range : chain, only;
auto squares =
chain(only(1, 2, 3, 4), only(5, 6)).map!(a => a * a);
assert(equal(squares, only(1, 4, 9, 16, 25, 36)));
Multiple functions can be passed to map. In that case, the
element type of map is a tuple containing one element for each
function.
auto sums = [2, 4, 6, 8];
auto products = [1, 4, 9, 16];
size_t i = 0;
foreach (result; [ 1, 2, 3, 4 ].map!("a + a", "a * a"))
{
assert(result[0] == sums[i]);
assert(result[1] == products[i]);
++i;
}
You may alias map with some function(s) to a symbol and use
it separately:
import std.algorithm.comparison : equal;
import std.conv : to;
alias stringize = map!(to!string);
assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ]));
map!(e => e.name.relativePath(root))
.string[] std.array.array!(gen_sdl_datasets.concatRecipes.MapResult!(__lambda_L62_C15, FilterResult!(f, _DirIterator!false)))(gen_sdl_datasets.concatRecipes.MapResult!(__lambda_L62_C15, FilterResult!(f, _DirIterator!false)) r) @systemAllocates an array and initializes it with copies of the elements
of range r.
Narrow strings are handled as follows:
If autodecoding is turned on (default), then they are handled as a separate overload.
If autodecoding is turned off, then this is equivalent to duplicating the array.
array;
(local variable) string[] pathspaths.std.range.SortedRange!(string[], "a < b", SortedRangeOptions.assumeSorted) std.algorithm.sorting.sort!("a < b", SwapStrategy.unstable, string[])(string[] r) pure nothrow @nogc @safeSorts a random-access range according to the predicate less.
Performs O(r.length * log(r.length)) evaluations of less. If less involves
expensive computations on the sort key, it may be worthwhile to use
schwartzSort instead.
Stable sorting requires hasAssignableElements!Range to be true.
sort returns a SortedRange over the original range,
allowing functions that can take advantage of sorted data to know that the
range is sorted and adjust accordingly. The SortedRange is a
wrapper around the original range, so both it and the original range are sorted.
Other functions can't know that the original range has been sorted, but
they can know that SortedRange has been sorted.
Preconditions
The predicate is expected to satisfy certain rules in order for sort to
behave as expected - otherwise, the program may fail on certain inputs (but not
others) when not compiled in release mode, due to the cursory assumeSorted
check. Specifically, sort expects less(a,b) && less(b,c) to imply
less(a,c) (transitivity), and, conversely, !less(a,b) && !less(b,c) to
imply !less(a,c). Note that the default predicate ("a < b") does not
always satisfy these conditions for floating point types, because the expression
will always be false when either a or b is NaN.
Use cmp instead.
Algorithms
Introsort is used for unstable sorting and
Timsort is used for stable sorting.
Each algorithm has benefits beyond stability. Introsort is generally faster but
Timsort may achieve greater speeds on data with low entropy or if predicate calls
are expensive. Introsort performs no allocations whereas Timsort will perform one
or more allocations per call. Both algorithms have O(n log n) worst-case
time complexity.
Examples
int[] array = [ 1, 2, 3, 4 ];
// sort in descending order
array.sort!("a > b");
assert(array == [ 4, 3, 2, 1 ]);
// sort in ascending order
array.sort();
assert(array == [ 1, 2, 3, 4 ]);
// sort with reusable comparator and chain
alias myComp = (x, y) => x > y;
assert(array.sort!(myComp).release == [ 4, 3, 2, 1 ]);
// Showcase stable sorting
import std.algorithm.mutation : SwapStrategy;
string[] words = [ "aBc", "a", "abc", "b", "ABC", "c" ];
sort!("toUpper(a) < toUpper(b)", SwapStrategy.stable)(words);
assert(words == [ "a", "aBc", "abc", "ABC", "b", "c" ]);
// Sorting floating-point numbers in presence of NaN
double[] numbers = [-0.0, 3.0, -2.0, double.nan, 0.0, -double.nan];
import std.algorithm.comparison : equal;
import std.math.operations : cmp;
import std.math.traits : isIdentical;
sort!((a, b) => cmp(a, b) < 0)(numbers);
double[] sorted = [-double.nan, -2.0, -0.0, 0.0, 3.0, double.nan];
assert(numbers.equal!isIdentical(sorted));
sort();
auto (local variable) std.array.Appender!string oo = 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;
(local variable) std.array.Appender!string oo ~= "name \"sparkles-recipes\"\n";
(local variable) std.array.Appender!string oo ~= "description \"Every dub.sdl of the snapshot, as inline subpackages\"\n";
foreach ((parameter) string pathpath; (local variable) string[] pathspaths)
{
(local variable) std.array.Appender!string oo ~= "subPackage {\n";
(local variable) std.array.Appender!string oo ~= string std.file.readText!(string, string)(string name) @safeReads and validates (using validate) a text file. S can be
an array of any character type. However, no width or endian conversions are
performed. So, if the width or endianness of the characters in the given
file differ from the width or endianness of the element type of S, then
validation will fail.
Examples
Read file with UTF-8 text.
write(deleteme, "abc"); // deleteme is the name of a temporary file
scope(exit) remove(deleteme);
string content = readText(deleteme);
assert(content == "abc");
readText((parameter) string rootroot ~ "/" ~ (local variable) string pathpath);
(local variable) std.array.Appender!string oo ~= "\n}\n";
}
return (local variable) std.array.Appender!string oo.string std.array.Appender!string.data() inout pure nothrow @nogc @property @safeUse opSlice() from now on.
data;
}
/// Fixed pseudo-random sequence (xorshift64), so the document never varies.
private struct (struct) gen_sdl_datasets.RngFixed pseudo-random sequence (xorshift64), so the document never varies.
Rng
{
ulong (field) ulong gen_sdl_datasets.Rng.ss = 0x9E37_79B9_7F4A_7C15;
ulong ulong gen_sdl_datasets.Rng.next()next()
{
(field) ulong gen_sdl_datasets.Rng.ss ^= (field) ulong gen_sdl_datasets.Rng.ss << 13;
(field) ulong gen_sdl_datasets.Rng.ss ^= (field) ulong gen_sdl_datasets.Rng.ss >> 7;
(field) ulong gen_sdl_datasets.Rng.ss ^= (field) ulong gen_sdl_datasets.Rng.ss << 17;
return (field) ulong gen_sdl_datasets.Rng.ss;
}
uint uint gen_sdl_datasets.Rng.below(uint n)below(uint (parameter) uint nn) => cast(uint) (ulong gen_sdl_datasets.Rng.next()next() % (parameter) uint nn);
}
/// One scalar literal, cycling through the kinds both parsers accept. A
/// positional value is never a date-time: one followed by a value starting
/// with a digit does not lex as two values, so the slot is a duration.
private (alias) object.string = stringstring string gen_sdl_datasets.scalar(ref gen_sdl_datasets.Rng rng, bool positional)One scalar literal, cycling through the kinds both parsers accept. A
positional value is never a date-time: one followed by a value starting
with a digit does not lex as two values, so the slot is a duration.
scalar(ref (struct) gen_sdl_datasets.RngFixed pseudo-random sequence (xorshift64), so the document never varies.
Rng (parameter) gen_sdl_datasets.Rng rngrng, bool (parameter) bool positionalpositional)
{
const (local variable) const(uint) kindkind = (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(12);
switch ((local variable) const(uint) kindkind == 9 && (parameter) bool positionalpositional ? 10 : (local variable) const(uint) kindkind)
{
case 0:
return string std.format.format!("\"s%d \\\"q\\\" \\t\\n\"", uint)(uint __param_0) 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%d \\\"q\\\" \\t\\n\"" ((parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(100_000));
case 1:
return string std.format.format!("`raw %d\\no-escape`", uint)(uint __param_0) 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!"`raw %d\\no-escape`" ((parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(100_000));
case 2:
return (cast(int) (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(2_000_000) - 1_000_000).string std.conv.to!string.to!int(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.
[special case]
: 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;
case 3:
return string std.format.format!("%dL", ulong)(ulong __param_0) 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!"%dL" ((parameter) gen_sdl_datasets.Rng rngrng.ulong gen_sdl_datasets.Rng.next()next() >> 2);
case 4:
return string std.format.format!("%d.%02dF", uint, uint)(uint __param_0, uint __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!"%d.%02dF" ((parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(10_000), (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(100));
case 5:
return string std.format.format!("%d.%04d", uint, uint)(uint __param_0, uint __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!"%d.%04d" ((parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(1_000_000), (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(10_000));
case 6:
return string std.format.format!("%d.%03dBD", uint, uint)(uint __param_0, uint __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!"%d.%03dBD" ((parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(1_000_000), (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(1000));
case 7:
return (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(2) ? "true" : "false";
case 8:
return "null";
case 9:
// A zoned date-time: a bare date followed by a numeric value would
// lex as one date-time.
return string std.format.format!("%04d/%02d/%02d %02d:%02d:%02d-GMT+%02d:00", uint, uint, uint, uint, uint, uint, uint)(uint __param_0, uint __param_1, uint __param_2, uint __param_3, uint __param_4, uint __param_5, uint __param_6) 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!"%04d/%02d/%02d %02d:%02d:%02d-GMT+%02d:00" (1970 + (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(80),
1 + (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(12), 1 + (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(28), (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(24), (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(60),
(parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(60), (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(13));
case 10:
return string std.format.format!("%02d:%02d:%02d", uint, uint, uint)(uint __param_0, uint __param_1, uint __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!"%02d:%02d:%02d" ((parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(24), (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(60), (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(60));
default:
return "[" ~ ["c3BhcmtsZXM=", "d2lyZWQ=", "U0RM"][(parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(3)] ~ "]";
}
}
private void void gen_sdl_datasets.attrs(ref gen_sdl_datasets.Rng rng, ref std.array.Appender!string o, uint n)attrs(ref (struct) gen_sdl_datasets.RngFixed pseudo-random sequence (xorshift64), so the document never varies.
Rng (parameter) gen_sdl_datasets.Rng rngrng, ref typeof((template instance) appender!stringappender!(alias) object.string = stringstring()) (parameter) std.array.Appender!string oo, uint (parameter) uint nn)
{
foreach ((local variable) uint ii; 0 .. (parameter) uint nn)
(parameter) std.array.Appender!string oo ~= string std.format.format!(" %sa%d=%s", string, uint, string)(string __param_0, uint __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!" %sa%d=%s"((local variable) uint ii % 5 == 0 ? "ns:" : "", (local variable) uint ii, string gen_sdl_datasets.scalar(ref gen_sdl_datasets.Rng rng, bool positional)One scalar literal, cycling through the kinds both parsers accept. A
positional value is never a date-time: one followed by a value starting
with a digit does not lex as two values, so the slot is a duration.
scalar((parameter) gen_sdl_datasets.Rng rngrng, positional: false));
}
private void void gen_sdl_datasets.values(ref gen_sdl_datasets.Rng rng, ref std.array.Appender!string o, uint n)values(ref (struct) gen_sdl_datasets.RngFixed pseudo-random sequence (xorshift64), so the document never varies.
Rng (parameter) gen_sdl_datasets.Rng rngrng, ref typeof((template instance) appender!stringappender!(alias) object.string = stringstring()) (parameter) std.array.Appender!string oo, uint (parameter) uint nn)
{
foreach ((local variable) uint __; 0 .. (parameter) uint nn)
{
(parameter) std.array.Appender!string oo ~= ' ';
(parameter) std.array.Appender!string oo ~= string gen_sdl_datasets.scalar(ref gen_sdl_datasets.Rng rng, bool positional)One scalar literal, cycling through the kinds both parsers accept. A
positional value is never a date-time: one followed by a value starting
with a digit does not lex as two values, so the slot is a duration.
scalar((parameter) gen_sdl_datasets.Rng rngrng, positional: true);
}
}
private void void gen_sdl_datasets.indent(ref std.array.Appender!string o, ulong depth)indent(ref typeof((template instance) appender!stringappender!(alias) object.string = stringstring()) (parameter) std.array.Appender!string oo, (alias) object.size_t = ulongsize_t (parameter) ulong depthdepth)
{
foreach ((local variable) ulong __; 0 .. (parameter) ulong depthdepth)
(parameter) std.array.Appender!string oo ~= " ";
}
/// A balanced tree: `fanout` children per node down to `depth`.
private void void gen_sdl_datasets.tree(ref gen_sdl_datasets.Rng rng, ref std.array.Appender!string o, ulong level, uint depth, uint fanout)A balanced tree: fanout children per node down to depth.
tree(ref (struct) gen_sdl_datasets.RngFixed pseudo-random sequence (xorshift64), so the document never varies.
Rng (parameter) gen_sdl_datasets.Rng rngrng, ref typeof((template instance) appender!stringappender!(alias) object.string = stringstring()) (parameter) std.array.Appender!string oo, (alias) object.size_t = ulongsize_t (parameter) ulong levellevel,
uint (parameter) uint depthdepth, uint (parameter) uint fanoutfanout)
{
foreach ((local variable) uint ii; 0 .. (parameter) uint fanoutfanout)
{
void gen_sdl_datasets.indent(ref std.array.Appender!string o, ulong depth)indent((parameter) std.array.Appender!string oo, (parameter) ulong levellevel);
(parameter) std.array.Appender!string oo ~= string std.format.format!("n%d", uint)(uint __param_0) 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!"n%d"((local variable) uint ii);
void gen_sdl_datasets.values(ref gen_sdl_datasets.Rng rng, ref std.array.Appender!string o, uint n)values((parameter) gen_sdl_datasets.Rng rngrng, (parameter) std.array.Appender!string oo, 1 + (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(3));
void gen_sdl_datasets.attrs(ref gen_sdl_datasets.Rng rng, ref std.array.Appender!string o, uint n)attrs((parameter) gen_sdl_datasets.Rng rngrng, (parameter) std.array.Appender!string oo, (parameter) gen_sdl_datasets.Rng rngrng.uint gen_sdl_datasets.Rng.below(uint n)below(3));
if ((parameter) uint depthdepth > 1)
{
(parameter) std.array.Appender!string oo ~= " {\n";
void gen_sdl_datasets.tree(ref gen_sdl_datasets.Rng rng, ref std.array.Appender!string o, ulong level, uint depth, uint fanout)A balanced tree: fanout children per node down to depth.
tree((parameter) gen_sdl_datasets.Rng rngrng, (parameter) std.array.Appender!string oo, (parameter) ulong levellevel + 1, (parameter) uint depthdepth - 1, (parameter) uint fanoutfanout);
void gen_sdl_datasets.indent(ref std.array.Appender!string o, ulong depth)indent((parameter) std.array.Appender!string oo, (parameter) ulong levellevel);
(parameter) std.array.Appender!string oo ~= "}\n";
}
else
(parameter) std.array.Appender!string oo ~= '\n';
}
}
/// The generated deep-and-wide document.
(alias) object.string = stringstring string gen_sdl_datasets.deepWide()The generated deep-and-wide document.
deepWide()
{
(struct) gen_sdl_datasets.RngFixed pseudo-random sequence (xorshift64), so the document never varies.
Rng (local variable) gen_sdl_datasets.Rng rngrng;
auto (local variable) std.array.Appender!string oo = 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;
(local variable) std.array.Appender!string oo ~= "// Generated by libs/wired/bench/runtime/tools/gen-sdl-datasets.d\n";
// Deep: 4 chains, each nested 200 levels.
foreach ((local variable) int cc; 0 .. 4)
{
foreach ((local variable) int levellevel; 0 .. 200)
{
void gen_sdl_datasets.indent(ref std.array.Appender!string o, ulong depth)indent((local variable) std.array.Appender!string oo, (local variable) int levellevel);
(local variable) std.array.Appender!string oo ~= string std.format.format!("deep:d%d", int)(int __param_0) 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!"deep:d%d"((local variable) int levellevel);
void gen_sdl_datasets.values(ref gen_sdl_datasets.Rng rng, ref std.array.Appender!string o, uint n)values((local variable) gen_sdl_datasets.Rng rngrng, (local variable) std.array.Appender!string oo, 2);
void gen_sdl_datasets.attrs(ref gen_sdl_datasets.Rng rng, ref std.array.Appender!string o, uint n)attrs((local variable) gen_sdl_datasets.Rng rngrng, (local variable) std.array.Appender!string oo, 2);
(local variable) std.array.Appender!string oo ~= " {\n";
}
void gen_sdl_datasets.indent(ref std.array.Appender!string o, ulong depth)indent((local variable) std.array.Appender!string oo, 200);
(local variable) std.array.Appender!string oo ~= string std.format.format!("leaf %d\n", int)(int __param_0) 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!"leaf %d\n"((local variable) int cc);
foreach_reverse ((local variable) int levellevel; 0 .. 200)
{
void gen_sdl_datasets.indent(ref std.array.Appender!string o, ulong depth)indent((local variable) std.array.Appender!string oo, (local variable) int levellevel);
(local variable) std.array.Appender!string oo ~= "}\n";
}
}
// Wide: 64 tags, each with 64 values and 256 attributes.
foreach ((local variable) int ww; 0 .. 64)
{
(local variable) std.array.Appender!string oo ~= string std.format.format!("wide%d", int)(int __param_0) 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!"wide%d"((local variable) int ww);
void gen_sdl_datasets.values(ref gen_sdl_datasets.Rng rng, ref std.array.Appender!string o, uint n)values((local variable) gen_sdl_datasets.Rng rngrng, (local variable) std.array.Appender!string oo, 64);
void gen_sdl_datasets.attrs(ref gen_sdl_datasets.Rng rng, ref std.array.Appender!string o, uint n)attrs((local variable) gen_sdl_datasets.Rng rngrng, (local variable) std.array.Appender!string oo, 256);
(local variable) std.array.Appender!string oo ~= '\n';
}
// Broad: a balanced tree, fan-out 4, depth 6.
(local variable) std.array.Appender!string oo ~= "tree {\n";
void gen_sdl_datasets.tree(ref gen_sdl_datasets.Rng rng, ref std.array.Appender!string o, ulong level, uint depth, uint fanout)A balanced tree: fanout children per node down to depth.
tree((local variable) gen_sdl_datasets.Rng rngrng, (local variable) std.array.Appender!string oo, 1, 6, 4);
(local variable) std.array.Appender!string oo ~= "}\n";
return (local variable) std.array.Appender!string oo.string std.array.Appender!string.data() inout pure nothrow @nogc @property @safeUse opSlice() from now on.
data;
}