#!/usr/bin/env dub
/+ dub.sdl:
name "build_settings_bench"
targetPath "build"
buildType "checked" {
buildOptions "optimize" "inline" "debugInfo"
}
+/
/**
Replay actual LDC root compile/link commands, with warm dependencies and no
test execution in build timings. See docs/guidelines/build-settings.md.
Capture with `dub test :pkg --force --verbose -- --help > capture.txt 2>&1`.
Run from the same working directory. Only replay trusted captures, without
whitespace in paths. Output retains commands, exit codes, logs and JSON samples.
BUILD_STUDY_VARIANTS selects comma-separated variants instead of the full matrix.
BUILD_STUDY_WILD_DIR names a directory containing an ld symlink to Wild.
BUILD_STUDY_CPU selects the runtime CPU (default 4); builds remain unpinned.
*/
module (module) build_settings_benchReplay actual LDC root compile/link commands, with warm dependencies and no
test execution in build timings. See docs/guidelines/build-settings.md.
Capture with dub test :pkg --force --verbose -- --help > capture.txt 2>&1.
Run from the same working directory. Only replay trusted captures, without
whitespace in paths. Output retains commands, exit codes, logs and JSON samples.
BUILD_STUDY_VARIANTS selects comma-separated variants instead of the full matrix.
BUILD_STUDY_WILD_DIR names a directory containing an ld symlink to Wild.
BUILD_STUDY_CPU selects the runtime CPU (default 4); builds remain unpinned.
build_settings_bench;
import (package) stdstd.(module) std.algorithmThis package implements generic algorithms oriented towards the processing of
sequences. Sequences processed by these functions define range-based
interfaces. See also Reference on ranges and
tutorial on ranges.
Algorithms are categorized into the following submodules:
Submodule Functions
| Searching |
all
any
balancedParens
boyerMooreFinder
canFind
commonPrefix
count
countUntil
endsWith
find
findAdjacent
findAmong
findSkip
findSplit
findSplitAfter
findSplitBefore
minCount
maxCount
minElement
maxElement
minIndex
maxIndex
minPos
maxPos
skipOver
startsWith
until
|
| Comparison |
among
castSwitch
clamp
cmp
either
equal
isPermutation
isSameLength
levenshteinDistance
levenshteinDistanceAndPath
max
min
mismatch
predSwitch
|
| Iteration |
cache
cacheBidirectional
chunkBy
cumulativeFold
each
filter
filterBidirectional
fold
group
joiner
map
mean
permutations
reduce
splitWhen
splitter
substitute
sum
uniq
|
| Sorting |
completeSort
isPartitioned
isSorted
isStrictlyMonotonic
ordered
strictlyOrdered
makeIndex
merge
multiSort
nextEvenPermutation
nextPermutation
nthPermutation
partialSort
partition
partition3
schwartzSort
sort
topN
topNCopy
topNIndex
|
| Set operations (setops) |
cartesianProduct
largestPartialIntersection
largestPartialIntersectionWeighted
multiwayMerge
multiwayUnion
setDifference
setIntersection
setSymmetricDifference
|
| Mutation |
bringToFront
copy
fill
initializeAll
move
moveAll
moveSome
moveEmplace
moveEmplaceAll
moveEmplaceSome
remove
reverse
strip
stripLeft
stripRight
swap
swapRanges
uninitializedFill
|
Many functions in this package are parameterized with a predicate.
The predicate may be any suitable callable type
(a function, a delegate, a functor, or a lambda), or a
compile-time string. The string may consist of any legal D
expression that uses the symbol a (for unary functions) or the
symbols a and b (for binary functions). These names will NOT
interfere with other homonym symbols in user code because they are
evaluated in a different context. The default for all binary
comparison predicates is "a == b" for unordered operations and
"a < b" for ordered operations.
Example
int[] a = ...;
static bool greater(int a, int b)
{
return a > b;
}
sort!greater(a); // predicate as alias
sort!((a, b) => a > b)(a); // predicate as a lambda.
sort!"a > b"(a); // predicate as string
// (no ambiguity with array name)
sort(a); // no predicate, "a < b" is implicit
Source
std/algorithm/package.d
algorithm : (alias template) build_settings_bench.canFind = std.algorithm.searching.canFind(alias pred = "a == b")Convenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
canFind, (alias template) build_settings_bench.endsWith = std.algorithm.searching.endsWith(alias pred = "a == b", Range, Needles...)(Range doesThisEnd, Needles withOneOfThese) if (isBidirectionalRange!Range && (Needles.length > 1) && allSatisfy!(canTestStartsWith!(pred, Range), Needles))Checks if the given range ends with (one of) the given needle(s).
The reciprocal of startsWith.
endsWith, (alias template) build_settings_bench.filter = std.algorithm.iteration.filter(alias predicate) if (is(typeof(unaryFun!predicate)))``filter!(predicate)(range) returns a new range containing only elements x in range for
which predicate(x) returns true.
The predicate is passed to unaryFun, and can be either a string, or
any callable that can be executed via pred(element).
filter, (alias template) build_settings_bench.startsWith = std.algorithm.searching.startsWith(alias pred = (a, b) => a == b, Range, Needles...)(Range doesThisStart, Needles withOneOfThese) if (isInputRange!Range && (Needles.length > 1) && allSatisfy!(canTestStartsWith!(pred, Range), Needles))Checks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith;
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) build_settings_bench.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, (alias template) build_settings_bench.join = std.array.join(RoR, R)(RoR ror, R sep) if (isInputRange!RoR && isInputRange!(Unqual!(ElementType!RoR)) && isInputRange!R && (is(immutable(ElementType!(ElementType!RoR)) == immutable(ElementType!R)) || isSomeChar!(ElementType!(ElementType!RoR)) && isSomeChar!(ElementType!R)))Eagerly concatenates all of the ranges in ror together (with the GC)
into one array using sep as the separator if present.
join, (alias template) build_settings_bench.split = std.array.split(S)(S s) if (isSomeString!S)Eagerly splits range into an array, using sep as the delimiter.
When no delimiter is provided, strings are split into an array of words,
using whitespace as delimiter.
Runs of whitespace are merged together (no empty words are produced).
The range must be a forward range.
The separator can be a value of the same type as the elements in range
or it can be another forward range.
split;
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) build_settings_bench.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.(package) std.datetimedatetime.(module) std.datetime.stopwatchModule containing some basic benchmarking and timing functionality.
For convenience, this module publicly imports core.time.
Category Functions Main functionality StopWatch benchmark Flags AutoStart
Unlike the other modules in std.datetime, this module is not currently
publicly imported in std.datetime.package, because the old
versions of this functionality which use
TickDuration are in std.datetime.package and would
conflict with the symbols in this module. After the old symbols have
gone through the deprecation cycle and have been fully removed, then
this module will be publicly imported in std.datetime.package. The
old, deprecated symbols has been removed from the documentation in
December 2019 and currently scheduled to be fully removed from Phobos
after 2.094.
So, for now, when using std.datetime.stopwatch, if other modules from
std.datetime are needed, then either import them individually rather than
importing std.datetime, or use selective or static imports to import
std.datetime.stopwatch. e.g.
import std.datetime;
import std.datetime.stopwatch : benchmark, StopWatch;
The compiler will then know to use the symbols from std.datetime.stopwatch
rather than the deprecated ones from std.datetime.package.
Source
std/datetime/stopwatch.d
stopwatch : (struct) std.datetime.stopwatch.StopWatchStopWatch is used to measure time just like one would do with a physical
stopwatch, including stopping, restarting, and/or resetting it.
MonoTime is used to hold the time, and it uses the system's
monotonic clock, which is high precision and never counts backwards (unlike
the wall clock time, which can count backwards, which is why
SysTime should not be used for timing).
Note that the precision of StopWatch differs from system to system. It is
impossible for it to be the same for all systems, since the precision of the
system clock and other system-dependent and situation-dependent factors
(such as the overhead of a context switch between threads) varies from
system to system and can affect StopWatch's accuracy.
Examples
Measure a time in milliseconds, microseconds, or nanoseconds
auto sw = StopWatch(AutoStart.no);
sw.start();
// ... Insert operations to be timed here ...
sw.stop();
long msecs = sw.peek.total!"msecs";
long usecs = sw.peek.total!"usecs";
long nsecs = sw.peek.total!"nsecs";
assert(usecs >= msecs * 1000);
assert(nsecs >= usecs * 1000);
import core.thread : Thread;
auto sw = StopWatch(AutoStart.yes);
Duration t1 = sw.peek();
Thread.sleep(usecs(1));
Duration t2 = sw.peek();
assert(t2 > t1);
Thread.sleep(usecs(1));
sw.stop();
Duration t3 = sw.peek();
assert(t3 > t2);
Duration t4 = sw.peek();
assert(t3 == t4);
sw.start();
Thread.sleep(usecs(1));
Duration t5 = sw.peek();
assert(t5 > t4);
// If stopping or resetting the StopWatch is not required, then
// MonoTime can easily be used by itself without StopWatch.
auto before = MonoTime.currTime;
// do stuff...
auto timeElapsed = MonoTime.currTime - before;
StopWatch;
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) build_settings_bench.exists = std.file.exists(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)Determine whether the given file (or directory) exists.
exists, (alias template) build_settings_bench.getSize = std.file.getSize(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)Get size of file name in bytes.
getSize, (alias) build_settings_bench.mkdirRecurse = void std.file.mkdirRecurse(scope const(char)[] pathname) @safeMake directory and all parent directories as needed.
Does nothing if the directory specified by
pathname already exists.
mkdirRecurse, (alias template) build_settings_bench.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, (alias template) build_settings_bench.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.jsonImplements functionality to read and write JavaScript Object Notation values.
JavaScript Object Notation is a lightweight data interchange format commonly used in web services and configuration files.
It's easy for humans to read and write, and it's easy for machines to parse and generate.
Warning: While JSONValue is fine for small-scale use, at the range of hundreds of megabytes it is
known to cause and exacerbate GC problems. If you encounter problems, try replacing it with a stream parser. See
also https://forum.dlang.org/post/dzfyaxypmkdrpakmycjv@forum.dlang.org.
References
http://json.org/, https://seriot.ch/projects/parsing_json.html
Source
std/json.d
Examples
import std.conv : to;
// parse a file or string of json into a usable structure
string s = `{ "language": "D", "rating": 3.5, "code": "42" }`;
JSONValue j = parseJSON(s);
// j and j["language"] return JSONValue,
// j["language"].str returns a string
assert(j["language"].str == "D");
assert(j["rating"].floating == 3.5);
// check a type
long x;
if (const(JSONValue)* code = "code" in j)
{
if (code.type() == JSONType.integer)
x = code.integer;
else
x = to!int(code.str);
}
// create a json struct
JSONValue jj = [ "language": "D" ];
// rating doesnt exist yet, so use .object to assign
jj.object["rating"] = JSONValue(3.5);
// create an array to assign to list
jj.object["list"] = JSONValue( ["a", "b", "c"] );
// list already exists, so .object optional
jj["list"].array ~= JSONValue("D");
string jjStr = `{"language":"D","list":["a","b","c","D"],"rating":3.5}`;
assert(jj.toString == jjStr);
json : (struct) std.json.JSONValueJSON value node
JSONValue, (alias template) build_settings_bench.parseJSON = std.json.parseJSON(T)(T json, int maxDepth = -1, JSONOptions options = JSONOptions.none) if (isSomeFiniteCharInputRange!T)Parses a serialized string and returns a tree of JSON values.
parseJSON;
import (package) stdstd.(module) std.processFunctions for starting and interacting with other processes, and for
working with the current process' execution environment.
Process handling
`spawnProcess` spawns a new `process`, optionally assigning it an
arbitrary set of standard input, output, and error streams.
The function returns immediately, leaving the child process to execute
in parallel with its parent. All other functions in this module that
spawn processes are built around spawnProcess.
`wait` makes the parent `process` wait for a child `process` to
terminate. In general one should always do this, to avoid
child processes becoming "zombies" when the parent process exits.
Scope guards are perfect for this – see the spawnProcess
documentation for examples. tryWait is similar to wait,
but does not block if the process has not yet terminated.
`pipeProcess` also spawns a child `process` which runs
in parallel with its parent. However, instead of taking
arbitrary streams, it automatically creates a set of
pipes that allow the parent to communicate with the child
through the child's standard input, output, and/or error streams.
This function corresponds roughly to C's popen function.
`execute` starts a new `process` and waits for it
to complete before returning. Additionally, it captures
the process' standard output and error streams and returns
the output of these as a string.
`spawnShell`, `pipeShell` and `executeShell` work like
spawnProcess, pipeProcess and execute, respectively,
except that they take a single command string and run it through
the current user's default command interpreter.
executeShell corresponds roughly to C's system function.
`kill` attempts to terminate a running `process`.
The following table compactly summarises the different process creation
functions and how they relate to each other:
Runs program directly
Runs shell command Low-level process creation spawnProcess spawnShell Automatic input/output redirection using pipes pipeProcess pipeShell Execute and wait for completion, collect output execute executeShell
Other functionality
`pipe` is used to create unidirectional pipes.
`environment` is an interface through which the current `process`'
environment variables can be read and manipulated.
`escapeShellCommand` and `escapeShellFileName` are useful
for constructing shell command lines in a portable way.
Source
std/process.d
Note
Most of the functionality in this module is not available on iOS, tvOS
and watchOS. The only functions available on those platforms are:
environment, thisProcessID and thisThreadID.
process : (struct) std.process.ConfigOptions that control the behaviour of process creation functions in this
module. Most options only apply to spawnProcess and
spawnShell.
Example
auto logFile = File("myapp_error.log", "w");
// Start program, suppressing the console window (Windows only),
// redirect its error stream to logFile, and leave logFile open
// in the parent process as well.
auto pid = spawnProcess("myapp", stdin, stdout, logFile,
Config.retainStderr | Config.suppressConsole);
scope(exit)
{
auto exitCode = wait(pid);
logFile.writeln("myapp exited with code ", exitCode);
logFile.close();
}
Config, (class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment, (alias) build_settings_bench.execute = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute, (alias) build_settings_bench.executeShell = auto std.process.executeShell(scope const(char)[] command, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null, string shellPath = nativeShell()) @safeexecuteShell;
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 : (struct) std.stdio.FileEncapsulates a FILE*. Generally D does not attempt to provide
thin wrappers over equivalent functions in the C standard library, but
manipulating FILE* values directly is unsafe and error-prone in
many ways. The File type ensures safe manipulation, automatic
file closing, and a lot of convenience.
The underlying FILE* handle is maintained in a reference-counted
manner, such that as soon as the last File variable bound to a
given FILE* goes out of scope, the underlying FILE* is
automatically closed.
Example
// test.d
import std.stdio;
void main(string[] args)
{
auto f = File("test.txt", "w"); // open for writing
f.write("Hello");
if (args.length > 1)
{
auto g = f; // now g and f write to the same file
// internal reference count is 2
g.write(", ", args[1]);
// g exits scope, reference count decreases to 1
}
f.writeln("!");
// f exits scope, reference count falls to zero,
// underlying `FILE*` is closed.
}
% rdmd test.d Jimmy
% cat test.txt
Hello, Jimmy!
% _
File, (alias template) build_settings_bench.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.
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;
import (package) stdstd.(module) std.stringString handling functions.
Category Functions Searching column indexOf indexOfAny indexOfNeither lastIndexOf lastIndexOfAny lastIndexOfNeither Comparison isNumeric Mutation capitalize Pruning and Filling center chomp chompPrefix chop detabber detab entab entabber leftJustify outdent rightJustify strip stripLeft stripRight wrap Substitution abbrev soundex soundexer succ tr translate Miscellaneous assumeUTF fromStringz lineSplitter representation splitLines toStringz Objects of types string, wstring, and dstring are value types and cannot be mutated element-by-element. For using mutation during building strings, use char[], wchar[], or dchar[]. The xxxstring types are preferable because they don't exhibit undesired aliasing, thus making code more robust.
The following functions are publicly imported:
Module Functions Publicly imported functions std.algorithm cmp, std,algorithm,comparison count, std,algorithm,searching endsWith, std,algorithm,searching startsWith, std,algorithm,searching std.array join, std,array replace, std,array replaceInPlace, std,array split, std,array empty, std,array std.format format, std,format sformat, std,format std.uni icmp, std,uni toLower, std,uni toLowerInPlace, std,uni toUpper, std,uni toUpperInPlace, std,uni There is a rich set of functions for string handling defined in other modules. Functions related to Unicode and ASCII are found in std.uni and std.ascii, respectively. Other functions that have a wider generality than just strings can be found in std.algorithm and std.range.
Source
std/string.d
string : (alias template) build_settings_bench.lineSplitter = std.string.lineSplitter(Flag keepTerm = No.keepTerminator, Range)(Range r) if (hasSlicing!Range && hasLength!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range)Split an array or slicable range of characters into a range of lines
using '\r', '\n', '\v', '\f', "\r\n",
lineSep, paraSep and '\u0085' (NEL)
as delimiters. If keepTerm is set to Yes.keepTerminator, then the
delimiter is included in the slices returned.
Does not throw on invalid UTF; such is simply passed unchanged
to the output.
Adheres to Unicode 7.0.
Does not allocate memory.
lineSplitter;
private struct (struct) build_settings_bench.CommandsCommands
{
(alias) object.string = stringstring[] (field) string[] build_settings_bench.Commands.compilecompile, (field) string[] build_settings_bench.Commands.linklink;
(alias) object.string = stringstring (field) string build_settings_bench.Commands.objectobject;
(alias) object.string = stringstring[][] (field) string[][] build_settings_bench.Commands.graphgraph;
}
private (struct) build_settings_bench.CommandsCommands build_settings_bench.Commands build_settings_bench.commandsFrom(string capture) @safecommandsFrom((alias) object.string = stringstring (parameter) string capturecapture) @safe
{
(struct) build_settings_bench.CommandsCommands (local variable) build_settings_bench.Commands resultresult;
foreach ((local variable) string lineline; (parameter) string capturecapture.std.string.LineSplitter!(Flag.no, string) std.string.lineSplitter!(Flag.no, immutable(char))(string r) pure nothrow @nogc @safeSplit an array or slicable range of characters into a range of lines
using '\r', '\n', '\v', '\f', "\r\n",
lineSep, paraSep and '\u0085' (NEL)
as delimiters. If keepTerm is set to Yes.keepTerminator, then the
delimiter is included in the slices returned.
Does not throw on invalid UTF; such is simply passed unchanged
to the output.
Adheres to Unicode 7.0.
Does not allocate memory.
Examples
import std.array : array;
string s = "Hello\nmy\rname\nis";
/* notice the call to 'array' to turn the lazy range created by
lineSplitter comparable to the string[] created by splitLines.
*/
assert(lineSplitter(s).array == splitLines(s));
auto s = "\rpeter\n\rpaul\r\njerry\u2028ice\u2029cream\n\nsunday\nmon\u2030day\n";
auto lines = s.lineSplitter();
static immutable witness = ["", "peter", "", "paul", "jerry", "ice", "cream", "", "sunday", "mon\u2030day"];
uint i;
foreach (line; lines)
{
assert(line == witness[i++]);
}
assert(i == witness.length);
lineSplitter)
{
if (!(local variable) string lineline.bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safeChecks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith("ldc2 ")) continue;
assert(!(local variable) string lineline.bool std.algorithm.searching.canFind!().canFind!(string, char)(string haystack, scope char needle) pure @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind('"') && !(local variable) string lineline.bool std.algorithm.searching.canFind!().canFind!(string, char)(string haystack, scope char needle) pure @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind('\''), "quoted paths are not supported");
auto (local variable) string[] tokenstokens = (local variable) string lineline.string[] std.array.split!string(string s) pure @safeEagerly splits range into an array, using sep as the delimiter.
When no delimiter is provided, strings are split into an array of words,
using whitespace as delimiter.
Runs of whitespace are merged together (no empty words are produced).
The range must be a forward range.
The separator can be a value of the same type as the elements in range
or it can be another forward range.
Examples
import std.uni : isWhite;
assert("Learning,D,is,fun".split(",") == ["Learning", "D", "is", "fun"]);
assert("Learning D is fun".split!isWhite == ["Learning", "D", "is", "fun"]);
assert("Learning D is fun".split(" D ") == ["Learning", "is fun"]);
string str = "Hello World!";
assert(str.split == ["Hello", "World!"]);
string str2 = "Hello\t\tWorld\t!";
assert(str2.split == ["Hello", "World", "!"]);
assert(split("hello world") == ["hello","world"]);
assert(split("192.168.0.1", ".") == ["192", "168", "0", "1"]);
auto a = split([1, 2, 3, 4, 5, 1, 2, 3, 4, 5], [2, 3]);
assert(a == [[1], [4, 5, 1], [4, 5]]);
split;
if ((local variable) string[] tokenstokens.bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind("-lib") || (local variable) string[] tokenstokens.bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind("-c") || (local variable) string[] tokenstokens[1].bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safeChecks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith("-of"))
(local variable) build_settings_bench.Commands resultresult.(field) string[][] build_settings_bench.Commands.graphgraph ~= (local variable) string[] tokenstokens;
if ((local variable) string[] tokenstokens.bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind("-c")) (local variable) build_settings_bench.Commands resultresult.(field) string[] build_settings_bench.Commands.compilecompile = (local variable) string[] tokenstokens;
else if ((local variable) string[] tokenstokens[1].bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safeChecks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith("-of")) (local variable) build_settings_bench.Commands resultresult.(field) string[] build_settings_bench.Commands.linklink = (local variable) string[] tokenstokens;
}
assert((local variable) build_settings_bench.Commands resultresult.(field) string[] build_settings_bench.Commands.compilecompile.(field) ulong string[].lengthlength && (local variable) build_settings_bench.Commands resultresult.(field) string[] build_settings_bench.Commands.linklink.(field) ulong string[].lengthlength, "need verbose LDC compile and link commands");
foreach ((parameter) string tt; (local variable) build_settings_bench.Commands resultresult.(field) string[] build_settings_bench.Commands.compilecompile) if ((local variable) string tt.bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safeChecks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith("-of")) (local variable) build_settings_bench.Commands resultresult.(field) string build_settings_bench.Commands.objectobject = (local variable) string tt[3 .. $];
assert((local variable) build_settings_bench.Commands resultresult.(field) string build_settings_bench.Commands.objectobject.bool std.algorithm.searching.endsWith!("a == b", string, string)(string doesThisEnd, string withThis) pure nothrow @nogc @safeChecks if the given range ends with (one of) the given needle(s).
The reciprocal of startsWith.
endsWith(".o"));
return (local variable) build_settings_bench.Commands resultresult;
}
/// Root commands are selected independently of dependency compilation commands.
@("buildSettings.commandsFrom.root")
@safe void build_settings_bench.__unittest_L60_C7() @safeRoot commands are selected independently of dependency compilation commands.
unittest
{
const (local variable) const(build_settings_bench.Commands) cc = build_settings_bench.Commands build_settings_bench.commandsFrom(string capture) @safecommandsFrom("ldc2 -lib dependency.d -ofdep.a\n"
~ "ldc2 -g -c root.d -ofroot.o\nldc2 -ofbin root.o dep.a\n");
assert((local variable) const(build_settings_bench.Commands) cc.(field) string[] build_settings_bench.Commands.compilecompile == ["ldc2", "-g", "-c", "root.d", "-ofroot.o"]);
assert((local variable) const(build_settings_bench.Commands) cc.(field) string build_settings_bench.Commands.objectobject == "root.o");
assert((local variable) const(build_settings_bench.Commands) cc.(field) string[] build_settings_bench.Commands.linklink == ["ldc2", "-ofbin", "root.o", "dep.a"]);
assert((local variable) const(build_settings_bench.Commands) cc.(field) string[][] build_settings_bench.Commands.graphgraph.(field) ulong const(string[][]).lengthlength == 3);
}
// Replays dependency archives too, into the captured DUB cache paths. Never run
// concurrently with another build using those caches. DUB setup and suite runtime
// stay outside the sum; compiler-invoked archiving is part of compilation.
private int int build_settings_bench.compareGraph(string[] args) @systemcompareGraph((alias) object.string = stringstring[] (parameter) string[] argsargs) @system
{
assert((parameter) string[] argsargs.(field) ulong string[].lengthlength == 6 || (parameter) string[] argsargs.(field) ulong string[].lengthlength == 8,
"--compare-graph baseline-capture selected-capture output-dir rounds [baseline-cwd selected-cwd]");
auto (local variable) build_settings_bench.Commands[] capturescaptures = [build_settings_bench.Commands build_settings_bench.commandsFrom(string capture) @safecommandsFrom((parameter) string[] argsargs[2].string std.file.readText!(string, string)(ref 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), build_settings_bench.Commands build_settings_bench.commandsFrom(string capture) @safecommandsFrom((parameter) string[] argsargs[3].string std.file.readText!(string, string)(ref 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)];
auto (local variable) string[][][] graphsgraphs = [(local variable) build_settings_bench.Commands[] capturescaptures[0].(field) string[][] build_settings_bench.Commands.graphgraph, (local variable) build_settings_bench.Commands[] capturescaptures[1].(field) string[][] build_settings_bench.Commands.graphgraph];
const (local variable) const(string) outputDiroutputDir = (parameter) string[] argsargs[4];
(local variable) const(string) outputDiroutputDir.void std.file.mkdirRecurse(scope const(char)[] pathname) @safeMake directory and all parent directories as needed.
Does nothing if the directory specified by
pathname already exists.
Examples
import std.path : buildPath;
auto dir = deleteme ~ "dir";
scope(exit) dir.rmdirRecurse;
dir.mkdir;
assert(dir.exists);
dir.mkdirRecurse; // does nothing
// creates all parent directories as needed
auto nested = dir.buildPath("a", "b", "c");
nested.mkdirRecurse;
assert(nested.exists);
import std.exception : assertThrown;
scope(exit) deleteme.remove;
deleteme.write("a");
// cannot make directory as it's already a file
assertThrown!FileException(deleteme.mkdirRecurse);
mkdirRecurse;
auto (local variable) std.stdio.File samplessamples = (struct) std.stdio.FileEncapsulates a FILE*. Generally D does not attempt to provide
thin wrappers over equivalent functions in the C standard library, but
manipulating FILE* values directly is unsafe and error-prone in
many ways. The File type ensures safe manipulation, automatic
file closing, and a lot of convenience.
The underlying FILE* handle is maintained in a reference-counted
manner, such that as soon as the last File variable bound to a
given FILE* goes out of scope, the underlying FILE* is
automatically closed.
Example
// test.d
import std.stdio;
void main(string[] args)
{
auto f = File("test.txt", "w"); // open for writing
f.write("Hello");
if (args.length > 1)
{
auto g = f; // now g and f write to the same file
// internal reference count is 2
g.write(", ", args[1]);
// g exits scope, reference count decreases to 1
}
f.writeln("!");
// f exits scope, reference count falls to zero,
// underlying `FILE*` is closed.
}
% rdmd test.d Jimmy
% cat test.txt
Hello, Jimmy!
% _
File(std.stdio.File std.stdio.File.this(string name, scope const(char)[] stdioOpenmode = "rb") ref @safeConstructor taking the name of the file to open and the open mode.
Copying one File object to another results in the two File
objects referring to the same underlying file.
The destructor automatically closes the file as soon as no File
object refers to it anymore.
outputDir ~ "/samples.jsonl", "a");
foreach ((local variable) uint roundround; 0 .. (parameter) string[] argsargs[5].uint std.conv.to!uint.to!string(string __param_0) pure @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!uint)
foreach ((local variable) int offsetoffset; 0 .. 2)
{
const (local variable) const(uint) selectedselected = ((local variable) uint roundround + (local variable) int offsetoffset) % 2;
const (local variable) const(string) variantvariant = (local variable) const(uint) selectedselected ? "selected" : "baseline";
long (local variable) long compileMscompileMs, (local variable) long rootCompileMsrootCompileMs, (local variable) long linkMslinkMs;
(struct) std.json.JSONValueJSON value node
JSONValue[] (local variable) std.json.JSONValue[] stepssteps;
foreach ((parameter) ulong indexindex, (parameter) string[] commandcommand; (local variable) string[][][] graphsgraphs[(local variable) const(uint) selectedselected])
{
const (local variable) const(string) stemstem = (local variable) const(string) outputDiroutputDir ~ "/" ~ (local variable) const(string) variantvariant ~ "-" ~ (local variable) uint roundround.string std.conv.to!string.to!uint(uint __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 ~ "-" ~ (local variable) ulong indexindex.string std.conv.to!string.to!ulong(ulong __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;
((local variable) const(string) stemstem ~ ".command").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((local variable) string[] commandcommand.string std.array.join!(string[], string)(string[] ror, string sep) pure nothrow @safeEagerly concatenates all of the ranges in ror together (with the GC)
into one array using sep as the separator if present.
join(" ") ~ "\n");
auto (local variable) std.datetime.stopwatch.StopWatch timertimer = (struct) std.datetime.stopwatch.StopWatchStopWatch is used to measure time just like one would do with a physical
stopwatch, including stopping, restarting, and/or resetting it.
MonoTime is used to hold the time, and it uses the system's
monotonic clock, which is high precision and never counts backwards (unlike
the wall clock time, which can count backwards, which is why
SysTime should not be used for timing).
Note that the precision of StopWatch differs from system to system. It is
impossible for it to be the same for all systems, since the precision of the
system clock and other system-dependent and situation-dependent factors
(such as the overhead of a context switch between threads) varies from
system to system and can affect StopWatch's accuracy.
Examples
Measure a time in milliseconds, microseconds, or nanoseconds
auto sw = StopWatch(AutoStart.no);
sw.start();
// ... Insert operations to be timed here ...
sw.stop();
long msecs = sw.peek.total!"msecs";
long usecs = sw.peek.total!"usecs";
long nsecs = sw.peek.total!"nsecs";
assert(usecs >= msecs * 1000);
assert(nsecs >= usecs * 1000);
import core.thread : Thread;
auto sw = StopWatch(AutoStart.yes);
Duration t1 = sw.peek();
Thread.sleep(usecs(1));
Duration t2 = sw.peek();
assert(t2 > t1);
Thread.sleep(usecs(1));
sw.stop();
Duration t3 = sw.peek();
assert(t3 > t2);
Duration t4 = sw.peek();
assert(t3 == t4);
sw.start();
Thread.sleep(usecs(1));
Duration t5 = sw.peek();
assert(t5 > t4);
// If stopping or resetting the StopWatch is not required, then
// MonoTime can easily be used by itself without StopWatch.
auto before = MonoTime.currTime;
// do stuff...
auto timeElapsed = MonoTime.currTime - before;
StopWatch();
(local variable) std.datetime.stopwatch.StopWatch timertimer.void std.datetime.stopwatch.StopWatch.start() nothrow @nogc @safeStarts the StopWatch.
start should not be called if the StopWatch is already running.
Examples
import core.thread : Thread;
StopWatch sw;
assert(!sw.running);
assert(sw.peek() == Duration.zero);
sw.start();
assert(sw.running);
Thread.sleep(usecs(1));
assert(sw.peek() > Duration.zero);
start;
auto (local variable) std.typecons.Tuple!(int, "status", string, "output") rr = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute((local variable) string[] commandcommand, null, (struct) std.process.ConfigOptions that control the behaviour of process creation functions in this
module. Most options only apply to spawnProcess and
spawnShell.
Example
auto logFile = File("myapp_error.log", "w");
// Start program, suppressing the console window (Windows only),
// redirect its error stream to logFile, and leave logFile open
// in the parent process as well.
auto pid = spawnProcess("myapp", stdin, stdout, logFile,
Config.retainStderr | Config.suppressConsole);
scope(exit)
{
auto exitCode = wait(pid);
logFile.writeln("myapp exited with code ", exitCode);
logFile.close();
}
Config.(constant) std.process.Config std.process.Config.none = Config(Flags.none, null, null)For backwards compatibility, and cases when only flags need to
be specified in the Config, these allow building Config
instances using flag names only.
none, size_t.(constant) ulong ulong.max = 18446744073709551615LUmax,
(parameter) string[] argsargs.(field) ulong string[].lengthlength == 8 ? (parameter) string[] argsargs[6 + (local variable) const(uint) selectedselected] : null);
(local variable) std.datetime.stopwatch.StopWatch timertimer.void std.datetime.stopwatch.StopWatch.stop() nothrow @nogc @safeStops the StopWatch.
stop should not be called if the StopWatch is not running.
Examples
import core.thread : Thread;
auto sw = StopWatch(AutoStart.yes);
assert(sw.running);
Thread.sleep(usecs(1));
immutable t1 = sw.peek();
assert(t1 > Duration.zero);
sw.stop();
assert(!sw.running);
immutable t2 = sw.peek();
assert(t2 >= t1);
immutable t3 = sw.peek();
assert(t2 == t3);
stop;
const (local variable) const(long) msms = (local variable) std.datetime.stopwatch.StopWatch timertimer.core.time.Duration std.datetime.stopwatch.StopWatch.peek() const nothrow @nogc @safePeek at the amount of time that the StopWatch has been running.
This does not include any time during which the StopWatch was stopped but
does include all of the time that it was running and not just the
time since it was started last.
Calling reset will reset this to Duration.zero.
Examples
import core.thread : Thread;
auto sw = StopWatch(AutoStart.no);
assert(sw.peek() == Duration.zero);
sw.start();
Thread.sleep(usecs(1));
assert(sw.peek() >= usecs(1));
Thread.sleep(usecs(1));
assert(sw.peek() >= usecs(2));
sw.stop();
immutable stopped = sw.peek();
Thread.sleep(usecs(1));
assert(sw.peek() == stopped);
sw.start();
Thread.sleep(usecs(1));
assert(sw.peek() > stopped);
peek.long core.time.Duration.total!"msecs"() const pure nothrow @nogc @property @safeReturns the total number of the given units in this Duration.
So, unlike split, it does not strip out the larger units.
Examples
assert(dur!"weeks"(12).total!"weeks" == 12);
assert(dur!"weeks"(12).total!"days" == 84);
assert(dur!"days"(13).total!"weeks" == 1);
assert(dur!"days"(13).total!"days" == 13);
assert(dur!"hours"(49).total!"days" == 2);
assert(dur!"hours"(49).total!"hours" == 49);
assert(dur!"nsecs"(2007).total!"hnsecs" == 20);
assert(dur!"nsecs"(2007).total!"nsecs" == 2000);
total!"msecs";
const (local variable) const(bool) isLinkisLink = (local variable) string[] commandcommand[1].bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safeChecks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith("-of");
if ((local variable) const(bool) isLinkisLink) (local variable) long linkMslinkMs += (local variable) const(long) msms; else (local variable) long compileMscompileMs += (local variable) const(long) msms;
if ((local variable) string[] commandcommand == (local variable) build_settings_bench.Commands[] capturescaptures[(local variable) const(uint) selectedselected].(field) string[] build_settings_bench.Commands.compilecompile) (local variable) long rootCompileMsrootCompileMs += (local variable) const(long) msms;
((local variable) const(string) stemstem ~ ".log").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((local variable) std.typecons.Tuple!(int, "status", string, "output") rr.output);
(struct) std.json.JSONValueJSON value node
JSONValue (local variable) std.json.JSONValue stepstep;
(local variable) std.json.JSONValue stepstep["index"] = void std.json.JSONValue.opIndexAssign!ulong(ref ulong value, string key) pure @safeProvides support for index assignments, which sets the
corresponding value of the JSON object's key field to value.
If the JSONValue is JSONType.null_, then this function
initializes it with a JSON object and then performs
the index assignment.
Examples
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
index;
(local variable) std.json.JSONValue stepstep["phase"] = void std.json.JSONValue.opIndexAssign!string(string value, string key) pure @safeProvides support for index assignments, which sets the
corresponding value of the JSON object's key field to value.
If the JSONValue is JSONType.null_, then this function
initializes it with a JSON object and then performs
the index assignment.
Examples
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
isLink ? "link" : "compile";
(local variable) std.json.JSONValue stepstep["ms"] = void std.json.JSONValue.opIndexAssign!(const(long))(ref const(long) value, string key) pure @safeProvides support for index assignments, which sets the
corresponding value of the JSON object's key field to value.
If the JSONValue is JSONType.null_, then this function
initializes it with a JSON object and then performs
the index assignment.
Examples
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
ms;
(local variable) std.json.JSONValue stepstep["exit"] = void std.json.JSONValue.opIndexAssign!int(ref int value, string key) pure @safeProvides support for index assignments, which sets the
corresponding value of the JSON object's key field to value.
If the JSONValue is JSONType.null_, then this function
initializes it with a JSON object and then performs
the index assignment.
Examples
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
r.status;
(local variable) std.json.JSONValue[] stepssteps ~= (local variable) std.json.JSONValue stepstep;
assert((local variable) std.typecons.Tuple!(int, "status", string, "output") rr.status == 0, (field) int std.typecons.Tuple!(int, "status", string, "output").__expand_field_0r.output);
}
(struct) std.json.JSONValueJSON value node
JSONValue (local variable) std.json.JSONValue samplesample;
(local variable) std.json.JSONValue samplesample["variant"] = void std.json.JSONValue.opIndexAssign!(const(string))(ref const(string) value, string key) pure @safeProvides support for index assignments, which sets the
corresponding value of the JSON object's key field to value.
If the JSONValue is JSONType.null_, then this function
initializes it with a JSON object and then performs
the index assignment.
Examples
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
variant;
(local variable) std.json.JSONValue samplesample["round"] = void std.json.JSONValue.opIndexAssign!uint(ref uint value, string key) pure @safeProvides support for index assignments, which sets the
corresponding value of the JSON object's key field to value.
If the JSONValue is JSONType.null_, then this function
initializes it with a JSON object and then performs
the index assignment.
Examples
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
round;
(local variable) std.json.JSONValue samplesample["compileMs"] = void std.json.JSONValue.opIndexAssign!long(ref long value, string key) pure @safeProvides support for index assignments, which sets the
corresponding value of the JSON object's key field to value.
If the JSONValue is JSONType.null_, then this function
initializes it with a JSON object and then performs
the index assignment.
Examples
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
compileMs;
(local variable) std.json.JSONValue samplesample["rootCompileMs"] = void std.json.JSONValue.opIndexAssign!long(ref long value, string key) pure @safeProvides support for index assignments, which sets the
corresponding value of the JSON object's key field to value.
If the JSONValue is JSONType.null_, then this function
initializes it with a JSON object and then performs
the index assignment.
Examples
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
rootCompileMs;
(local variable) std.json.JSONValue samplesample["compileExit"] = 0;
(local variable) std.json.JSONValue samplesample["linkMs"] = void std.json.JSONValue.opIndexAssign!long(ref long value, string key) pure @safeProvides support for index assignments, which sets the
corresponding value of the JSON object's key field to value.
If the JSONValue is JSONType.null_, then this function
initializes it with a JSON object and then performs
the index assignment.
Examples
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
linkMs;
(local variable) std.json.JSONValue samplesample["linkExit"] = 0;
(local variable) std.json.JSONValue samplesample["steps"] = void std.json.JSONValue.opIndexAssign!(std.json.JSONValue[])(ref std.json.JSONValue[] value, string key) pure @safeProvides support for index assignments, which sets the
corresponding value of the JSON object's key field to value.
If the JSONValue is JSONType.null_, then this function
initializes it with a JSON object and then performs
the index assignment.
Examples
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
steps;
(local variable) std.stdio.File samplessamples.void std.stdio.File.writeln!string(string __param_0) @safeWrites its arguments in text format to the file, followed by a newline.
writeln((local variable) std.json.JSONValue samplesample.string std.json.JSONValue.toString(in std.json.JSONOptions options = JSONOptions.none) const @safeImplicitly calls toJSON on this JSONValue.
options can be used to tweak the conversion behavior.
toString);
(local variable) std.stdio.File samplessamples.void std.stdio.File.flush() @trustedFlushes the C FILE buffers.
Calls fflush for the file handle.
flush;
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln((local variable) std.json.JSONValue samplesample.string std.json.JSONValue.toString(in std.json.JSONOptions options = JSONOptions.none) const @safeImplicitly calls toJSON on this JSONValue.
options can be used to tweak the conversion behavior.
toString);
}
return 0;
}
private (alias) object.string = stringstring string build_settings_bench.benchmarkError(in std.json.JSONValue report) @safebenchmarkError(in (struct) std.json.JSONValueJSON value node
JSONValue (parameter) const(std.json.JSONValue) reportreport) @safe
{
if (!(parameter) const(std.json.JSONValue) reportreport["rows"].inout(std.json.JSONValue[]) std.json.JSONValue.arrayNoRef() inout pure @property @trustedValue getter for JSONType.array.
Unlike array, this retrieves the array by value and can be used in @safe code.
One possible caveat is that, if you append to the returned array,
the new values aren't visible in the JSONValue:
JSONValue json;
json.array = [JSONValue("hello")];
json.arrayNoRef ~= JSONValue("world");
assert(json.array.length == 1);
arrayNoRef.(field) ulong const(std.json.JSONValue[]).lengthlength) return "no benchmark cases measured";
foreach ((parameter) const(std.json.JSONValue) rowrow; (parameter) const(std.json.JSONValue) reportreport["rows"].inout(std.json.JSONValue[]) std.json.JSONValue.arrayNoRef() inout pure @property @trustedValue getter for JSONType.array.
Unlike array, this retrieves the array by value and can be used in @safe code.
One possible caveat is that, if you append to the returned array,
the new values aren't visible in the JSONValue:
JSONValue json;
json.array = [JSONValue("hello")];
json.arrayNoRef ~= JSONValue("world");
assert(json.array.length == 1);
arrayNoRef)
if ((local variable) const(std.json.JSONValue) rowrow["error"].string std.json.JSONValue.str() const pure @property return scope @trustedValue getter/setter for JSONType.string.
str.(field) ulong string.lengthlength) return "benchmark row failed: " ~ (local variable) const(std.json.JSONValue) rowrow["error"].string std.json.JSONValue.str() const pure @property return scope @trustedValue getter/setter for JSONType.string.
str;
return null;
}
/// A successful process with no measured cases is not a successful experiment.
@("buildSettings.benchmarkReport.rejectsEmptyAndErrors")
@safe void build_settings_bench.__unittest_L137_C7() @safeA successful process with no measured cases is not a successful experiment.
unittest
{
assert(string build_settings_bench.benchmarkError(in std.json.JSONValue report) @safebenchmarkError(std.json.JSONValue std.json.parseJSON!string(string json, int maxDepth = -1, std.json.JSONOptions options = JSONOptions.none) pure @safeParses a serialized string and returns a tree of JSON values.
parseJSON(`{"rows":[]}`)).(field) ulong string.lengthlength);
assert(string build_settings_bench.benchmarkError(in std.json.JSONValue report) @safebenchmarkError(std.json.JSONValue std.json.parseJSON!string(string json, int maxDepth = -1, std.json.JSONOptions options = JSONOptions.none) pure @safeParses a serialized string and returns a tree of JSON values.
parseJSON(`{"rows":[{"error":"bad result"}]}`)).(field) ulong string.lengthlength);
assert(!string build_settings_bench.benchmarkError(in std.json.JSONValue report) @safebenchmarkError(std.json.JSONValue std.json.parseJSON!string(string json, int maxDepth = -1, std.json.JSONOptions options = JSONOptions.none) pure @safeParses a serialized string and returns a tree of JSON values.
parseJSON(`{"rows":[{"error":""}]}`)).(field) ulong string.lengthlength);
}
private int int build_settings_bench.compare(string[] args) @systemcompare((alias) object.string = stringstring[] (parameter) string[] argsargs) @system
{
assert((parameter) string[] argsargs.(field) ulong string[].lengthlength >= 6, "--compare output-dir baseline-bin selected-bin rounds [runner arguments]");
const (local variable) const(string) outputDiroutputDir = (parameter) string[] argsargs[2];
(local variable) const(string) outputDiroutputDir.void std.file.mkdirRecurse(scope const(char)[] pathname) @safeMake directory and all parent directories as needed.
Does nothing if the directory specified by
pathname already exists.
Examples
import std.path : buildPath;
auto dir = deleteme ~ "dir";
scope(exit) dir.rmdirRecurse;
dir.mkdir;
assert(dir.exists);
dir.mkdirRecurse; // does nothing
// creates all parent directories as needed
auto nested = dir.buildPath("a", "b", "c");
nested.mkdirRecurse;
assert(nested.exists);
import std.exception : assertThrown;
scope(exit) deleteme.remove;
deleteme.write("a");
// cannot make directory as it's already a file
assertThrown!FileException(deleteme.mkdirRecurse);
mkdirRecurse;
auto (local variable) std.stdio.File samplessamples = (struct) std.stdio.FileEncapsulates a FILE*. Generally D does not attempt to provide
thin wrappers over equivalent functions in the C standard library, but
manipulating FILE* values directly is unsafe and error-prone in
many ways. The File type ensures safe manipulation, automatic
file closing, and a lot of convenience.
The underlying FILE* handle is maintained in a reference-counted
manner, such that as soon as the last File variable bound to a
given FILE* goes out of scope, the underlying FILE* is
automatically closed.
Example
// test.d
import std.stdio;
void main(string[] args)
{
auto f = File("test.txt", "w"); // open for writing
f.write("Hello");
if (args.length > 1)
{
auto g = f; // now g and f write to the same file
// internal reference count is 2
g.write(", ", args[1]);
// g exits scope, reference count decreases to 1
}
f.writeln("!");
// f exits scope, reference count falls to zero,
// underlying `FILE*` is closed.
}
% rdmd test.d Jimmy
% cat test.txt
Hello, Jimmy!
% _
File(std.stdio.File std.stdio.File.this(string name, scope const(char)[] stdioOpenmode = "rb") ref @safeConstructor taking the name of the file to open and the open mode.
Copying one File object to another results in the two File
objects referring to the same underlying file.
The destructor automatically closes the file as soon as no File
object refers to it anymore.
outputDir ~ "/samples.jsonl", "a");
foreach ((local variable) uint roundround; 0 .. (parameter) string[] argsargs[5].uint std.conv.to!uint.to!string(string __param_0) pure @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!uint)
foreach ((local variable) int offsetoffset; 0 .. 2)
{
const (local variable) const(uint) selectedselected = ((local variable) uint roundround + (local variable) int offsetoffset) % 2;
const (local variable) const(string) variantvariant = (local variable) const(uint) selectedselected ? "selected" : "baseline";
const (local variable) const(string) stemstem = (local variable) const(string) outputDiroutputDir ~ "/" ~ (local variable) const(string) variantvariant ~ "-" ~ (local variable) uint roundround.string std.conv.to!string.to!uint(uint __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;
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) rr = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute(["taskset", "-c", (class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment.string std.process.environment.get(scope const(char)[] name, string defaultValue = null) @safeRetrieves the value of the environment variable with the given name,
or a default value if the variable doesn't exist.
Unlike environment.opIndex, this function never throws on Posix.
auto sh = environment.get("SHELL", "/bin/sh");
This function is also useful in checking for the existence of an
environment variable.
auto myVar = environment.get("MYVAR");
if (myVar is null)
{
// Environment variable doesn't exist.
// Note that we have to use 'is' for the comparison, since
// myVar == null is also true if the variable exists but is
// empty.
}
get("BUILD_STUDY_CPU", "4"), (parameter) string[] argsargs[3 + (local variable) const(uint) selectedselected]] ~ (parameter) string[] argsargs[6 .. $]
~ ["--bench-json=" ~ (local variable) const(string) stemstem ~ ".json"]);
((local variable) const(string) stemstem ~ ".run.log").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((local variable) const(std.typecons.Tuple!(int, "status", string, "output")) rr.output);
(struct) std.json.JSONValueJSON value node
JSONValue (local variable) std.json.JSONValue samplesample;
(local variable) std.json.JSONValue samplesample["variant"] = void std.json.JSONValue.opIndexAssign!(const(string))(ref const(string) value, string key) pure @safeProvides support for index assignments, which sets the
corresponding value of the JSON object's key field to value.
If the JSONValue is JSONType.null_, then this function
initializes it with a JSON object and then performs
the index assignment.
Examples
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
variant;
(local variable) std.json.JSONValue samplesample["round"] = void std.json.JSONValue.opIndexAssign!uint(ref uint value, string key) pure @safeProvides support for index assignments, which sets the
corresponding value of the JSON object's key field to value.
If the JSONValue is JSONType.null_, then this function
initializes it with a JSON object and then performs
the index assignment.
Examples
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
round;
(local variable) std.json.JSONValue samplesample["runExit"] = void std.json.JSONValue.opIndexAssign!(const(int))(ref const(int) value, string key) pure @safeProvides support for index assignments, which sets the
corresponding value of the JSON object's key field to value.
If the JSONValue is JSONType.null_, then this function
initializes it with a JSON object and then performs
the index assignment.
Examples
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
r.status;
if (!(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) rr.status)
{
auto (local variable) std.json.JSONValue reportreport = std.json.JSONValue std.json.parseJSON!string(string json, int maxDepth = -1, std.json.JSONOptions options = JSONOptions.none) pure @safeParses a serialized string and returns a tree of JSON values.
parseJSON(((local variable) const(string) stemstem ~ ".json").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);
const (local variable) const(string) errorerror = string build_settings_bench.benchmarkError(in std.json.JSONValue report) @safebenchmarkError((local variable) std.json.JSONValue reportreport);
if ((local variable) const(string) errorerror.(field) ulong const(string).lengthlength)
{
(local variable) std.json.JSONValue samplesample["runExit"] = 1;
(local variable) std.json.JSONValue samplesample["validationError"] = void std.json.JSONValue.opIndexAssign!(const(string))(ref const(string) value, string key) pure @safeProvides support for index assignments, which sets the
corresponding value of the JSON object's key field to value.
If the JSONValue is JSONType.null_, then this function
initializes it with a JSON object and then performs
the index assignment.
Examples
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
error;
}
}
(local variable) std.stdio.File samplessamples.void std.stdio.File.writeln!string(string __param_0) @safeWrites its arguments in text format to the file, followed by a newline.
writeln((local variable) std.json.JSONValue samplesample.string std.json.JSONValue.toString(in std.json.JSONOptions options = JSONOptions.none) const @safeImplicitly calls toJSON on this JSONValue.
options can be used to tweak the conversion behavior.
toString);
(local variable) std.stdio.File samplessamples.void std.stdio.File.flush() @trustedFlushes the C FILE buffers.
Calls fflush for the file handle.
flush;
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln((local variable) std.json.JSONValue samplesample.string std.json.JSONValue.toString(in std.json.JSONOptions options = JSONOptions.none) const @safeImplicitly calls toJSON on this JSONValue.
options can be used to tweak the conversion behavior.
toString);
assert((local variable) std.json.JSONValue samplesample["runExit"].long std.json.JSONValue.integer() const pure @property @safeValue getter/setter for JSONType.integer``.
integer == 0, (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) rr.output ~ "\n" ~ (local variable) std.json.JSONValue samplesample.string std.json.JSONValue.toString(in std.json.JSONOptions options = JSONOptions.none) const @safeImplicitly calls toJSON on this JSONValue.
options can be used to tweak the conversion behavior.
toString);
}
return 0;
}
private int int build_settings_bench.checkDebugInfo(string outputDir) @systemcheckDebugInfo((alias) object.string = stringstring (parameter) string outputDiroutputDir) @system
{
(parameter) string outputDiroutputDir.void std.file.mkdirRecurse(scope const(char)[] pathname) @safeMake directory and all parent directories as needed.
Does nothing if the directory specified by
pathname already exists.
Examples
import std.path : buildPath;
auto dir = deleteme ~ "dir";
scope(exit) dir.rmdirRecurse;
dir.mkdir;
assert(dir.exists);
dir.mkdirRecurse; // does nothing
// creates all parent directories as needed
auto nested = dir.buildPath("a", "b", "c");
nested.mkdirRecurse;
assert(nested.exists);
import std.exception : assertThrown;
scope(exit) deleteme.remove;
deleteme.write("a");
// cannot make directory as it's already a file
assertThrown!FileException(deleteme.mkdirRecurse);
mkdirRecurse;
const (local variable) const(string) sourcesource = (parameter) string outputDiroutputDir ~ "/line_table_probe.d";
const (local variable) const(string) binarybinary = (parameter) string outputDiroutputDir ~ "/line_table_probe";
(local variable) const(string) sourcesource.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("module line_table_probe;\nimport std.stdio : writeln;\n"
~ "pragma(inline, false) void leaf() @safe { throw new Exception(\"probe\"); }\n"
~ "pragma(inline, false) void caller() @safe { leaf(); }\n"
~ "void main() @system { try caller(); catch (Exception e) { writeln(e); } }\n");
auto (local variable) std.typecons.Tuple!(int, "status", string, "output") buildbuild = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute(["ldc2", "-g", "--gline-tables-only", "-L--export-dynamic",
(local variable) const(string) sourcesource, "-of=" ~ (local variable) const(string) binarybinary]);
assert((local variable) std.typecons.Tuple!(int, "status", string, "output") buildbuild.status == 0, (field) int std.typecons.Tuple!(int, "status", string, "output").__expand_field_0build.output);
auto (local variable) std.typecons.Tuple!(int, "status", string, "output") runrun = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute([(local variable) const(string) binarybinary]);
((parameter) string outputDiroutputDir ~ "/stack-trace.txt").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((local variable) std.typecons.Tuple!(int, "status", string, "output") runrun.output);
assert((local variable) std.typecons.Tuple!(int, "status", string, "output") runrun.status == 0 && (field) int std.typecons.Tuple!(int, "status", string, "output").__expand_field_0run.output.bool std.algorithm.searching.canFind!().canFind!(string, string)(string haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind("line_table_probe.d:4")
&& (local variable) std.typecons.Tuple!(int, "status", string, "output") runrun.output.bool std.algorithm.searching.canFind!().canFind!(string, string)(string haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind("line_table_probe.caller"), (local variable) std.typecons.Tuple!(int, "status", string, "output") runrun.output);
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln((local variable) std.typecons.Tuple!(int, "status", string, "output") runrun.output);
return 0;
}
version (unittestunittest) {} else
int main(string[] args) @system
{
if (args.length == 3 && args[1] == "--check-runtime-linker") return checkRuntimeLinker(args[2]);
if (args.length > 1 && args[1] == "--compare") return compare(args);
if (args.length > 1 && args[1] == "--compare-graph") return compareGraph(args);
if (args.length == 3 && args[1] == "--check-debug-info") return checkDebugInfo(args[2]);
assert(args.length >= 5, "capture output-dir compile|link|bench rounds [runtime-args...]");
const commands = commandsFrom(args[1].readText);
const outputDir = args[2];
const mode = args[3];
assert(["compile", "link", "bench"].canFind(mode));
outputDir.mkdirRecurse;
string[] variants = mode == "compile"
? ["baseline", "no-linkonce", "singleobj", "no-allinst", "no-debug-info", "line-tables"]
: mode == "link" ? ["gold-shared", "bfd-shared", "lld-shared", "mold-shared", "wild-shared",
"gold-static", "bfd-static", "lld-static", "mold-static", "wild-static"]
: ["baseline", "static", "nobounds", "generic-cpu", "O2", "thin-lto", "assertions", "no-linkonce"];
const selected = environment.get("BUILD_STUDY_VARIANTS", "");
if (selected.length) variants = selected.split(",");
auto results = File(outputDir ~ "/samples.jsonl", "a");
foreach (round; 0 .. args[4].to!uint)
foreach (offset; 0 .. variants.length)
{
const variant = variants[(offset + round) % variants.length];
auto cc = commands.compile.dup;
auto ld = commands.link.dup;
const object = outputDir ~ "/" ~ variant ~ ".o";
const binary = outputDir ~ "/" ~ variant;
foreach (ref t; cc) if (t.startsWith("-of")) t = "-of" ~ object;
foreach (ref t; ld)
{
if (t.startsWith("-of")) t = "-of" ~ binary;
else if (t == commands.object) t = mode == "link" ? commands.object : object;
}
if (mode == "compile")
{
if (variant == "no-linkonce") cc = cc.filter!(t => !t.canFind("linkonce-templates")).array;
if (variant == "singleobj") cc ~= "-singleobj";
if (variant == "no-allinst") cc = cc.filter!(t => t != "-allinst").array;
if (variant == "no-debug-info") cc = cc.filter!(t => t != "-g").array;
if (variant == "line-tables") { cc = cc.filter!(t => t != "-g").array; cc ~= "--gline-tables-only"; }
}
else if (mode == "link")
{
ld = ld.filter!(t => !t.canFind("linker=") && !t.canFind("link-defaultlib-shared")).array;
const parts = variant.split("-");
ld ~= parts[0] == "wild" ? "-Xcc=-B" ~ environment.get("BUILD_STUDY_WILD_DIR",
"/tmp/opencode/wild-linker") : "--linker=" ~ parts[0];
ld ~= "--link-defaultlib-shared=" ~ (parts[1] == "shared" ? "true" : "false");
if (parts.length > 2) ld ~= "-L--threads=" ~ parts[2][1 .. $];
}
else
{
if (variant == "static")
{
ld = ld.filter!(t => !t.canFind("link-defaultlib-shared")).array;
ld ~= "--link-defaultlib-shared=false";
}
if (variant == "nobounds") cc ~= "--boundscheck=off";
if (variant == "assertions") cc = cc.filter!(t => t != "-release").array;
if (variant == "no-linkonce") cc = cc.filter!(t => !t.canFind("linkonce-templates")).array;
if (variant == "generic-cpu") cc = cc.filter!(t => !t.startsWith("-mcpu=")).array;
if (variant == "O2") { cc = cc.filter!(t => t != "-O3").array; cc ~= "-O2"; }
if (variant == "thin-lto")
{
cc ~= "--flto=thin";
ld = ld.filter!(t => !t.canFind("linker=")).array;
ld ~= ["--flto=thin", "--linker=lld"];
}
}
JSONValue record;
record["variant"] = variant;
record["round"] = round;
foreach (phase; mode == "link" ? ["link"] : ["compile", "link"])
{
const command = (phase == "compile" ? cc : ld).join(" ");
(outputDir ~ "/" ~ variant ~ "." ~ phase ~ ".command").write(command ~ "\n");
auto timer = StopWatch();
timer.start;
auto r = executeShell(command);
timer.stop;
record[phase ~ "Ms"] = timer.peek.total!"msecs";
record[phase ~ "Exit"] = r.status;
(outputDir ~ "/" ~ variant ~ "." ~ phase ~ ".log").write(r.output);
if (r.status) break;
}
if (mode == "bench" && record.object.get("linkExit", JSONValue(-1)).integer == 0)
{
auto r = execute(["taskset", "-c", environment.get("BUILD_STUDY_CPU", "4"), binary] ~ args[5 .. $]
~ ["--bench-json=" ~ outputDir ~ "/" ~ variant ~ "-" ~ round.to!string ~ ".json"]);
record["runExit"] = r.status;
(outputDir ~ "/" ~ variant ~ "-" ~ round.to!string ~ ".run.log").write(r.output);
if (!r.status)
{
const error = benchmarkError(parseJSON((outputDir ~ "/" ~ variant
~ "-" ~ round.to!string ~ ".json").readText));
if (error.length)
{
record["runExit"] = 1;
record["validationError"] = error;
}
}
}
if (binary.exists)
{
record["binaryBytes"] = binary.getSize;
(outputDir ~ "/" ~ variant ~ ".identity.log").write(execute(["readelf", "-p", ".comment", binary]).output);
(outputDir ~ "/" ~ variant ~ ".ldd.log").write(execute(["ldd", binary]).output);
}
if (object.exists) record["objectBytes"] = object.getSize;
results.writeln(record.toString);
results.flush;
writeln(record.toString);
}
return 0;
}
// Exercise the real pkg-config -> compiler -> ELF-loader seam. Merely linking
// successfully misses the Nix RPATH regression; execute without LD_LIBRARY_PATH.
private int int build_settings_bench.checkRuntimeLinker(string outputDir) @systemcheckRuntimeLinker((alias) object.string = stringstring (parameter) string outputDiroutputDir) @system
{
(parameter) string outputDiroutputDir.void std.file.mkdirRecurse(scope const(char)[] pathname) @safeMake directory and all parent directories as needed.
Does nothing if the directory specified by
pathname already exists.
Examples
import std.path : buildPath;
auto dir = deleteme ~ "dir";
scope(exit) dir.rmdirRecurse;
dir.mkdir;
assert(dir.exists);
dir.mkdirRecurse; // does nothing
// creates all parent directories as needed
auto nested = dir.buildPath("a", "b", "c");
nested.mkdirRecurse;
assert(nested.exists);
import std.exception : assertThrown;
scope(exit) deleteme.remove;
deleteme.write("a");
// cannot make directory as it's already a file
assertThrown!FileException(deleteme.mkdirRecurse);
mkdirRecurse;
const (local variable) const(string) sourcesource = (parameter) string outputDiroutputDir ~ "/runtime_linker_probe.d";
(local variable) const(string) sourcesource.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("module runtime_linker_probe;\n"
~ "extern(C) void* ts_parser_new();\n"
~ "extern(C) void ts_parser_delete(void*);\n"
~ "void main() @system { auto p = ts_parser_new(); assert(p); ts_parser_delete(p); }\n");
auto (local variable) std.typecons.Tuple!(int, "status", string, "output") librarieslibraries = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute(["pkg-config", "--libs", "tree-sitter"]);
assert(!(local variable) std.typecons.Tuple!(int, "status", string, "output") librarieslibraries.status, (field) int std.typecons.Tuple!(int, "status", string, "output").__expand_field_0libraries.output);
(alias) object.string = stringstring[] (local variable) string[] flagsflags;
foreach ((parameter) string flagflag; (local variable) std.typecons.Tuple!(int, "status", string, "output") librarieslibraries.output.string[] std.array.split!string(string s) pure @safeEagerly splits range into an array, using sep as the delimiter.
When no delimiter is provided, strings are split into an array of words,
using whitespace as delimiter.
Runs of whitespace are merged together (no empty words are produced).
The range must be a forward range.
The separator can be a value of the same type as the elements in range
or it can be another forward range.
Examples
import std.uni : isWhite;
assert("Learning,D,is,fun".split(",") == ["Learning", "D", "is", "fun"]);
assert("Learning D is fun".split!isWhite == ["Learning", "D", "is", "fun"]);
assert("Learning D is fun".split(" D ") == ["Learning", "is fun"]);
string str = "Hello World!";
assert(str.split == ["Hello", "World!"]);
string str2 = "Hello\t\tWorld\t!";
assert(str2.split == ["Hello", "World", "!"]);
assert(split("hello world") == ["hello","world"]);
assert(split("192.168.0.1", ".") == ["192", "168", "0", "1"]);
auto a = split([1, 2, 3, 4, 5, 1, 2, 3, 4, 5], [2, 3]);
assert(a == [[1], [4, 5, 1], [4, 5]]);
split) (field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1flags ~= "-L" ~ (local variable) string flagflag;
foreach ((parameter) string compilercompiler; ["ldc2", "dmd"])
{
const (local variable) const(string) binarybinary = (parameter) string outputDiroutputDir ~ "/probe-" ~ (local variable) string compilercompiler;
const (local variable) const(string[]) optionsoptions = (local variable) string compilercompiler == "ldc2"
? ["--linker=lld", "--link-defaultlib-shared"]
: ["-L-fuse-ld=lld", "-defaultlib=libphobos2.so"];
auto (local variable) std.typecons.Tuple!(int, "status", string, "output") buildbuild = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute([(local variable) string compilercompiler, (local variable) const(string) sourcesource, "-of=" ~ (local variable) const(string) binarybinary] ~ (local variable) const(string[]) optionsoptions ~ (local variable) string[] flagsflags);
((parameter) string outputDiroutputDir ~ "/" ~ (local variable) string compilercompiler ~ ".build.log").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((local variable) std.typecons.Tuple!(int, "status", string, "output") buildbuild.output);
assert(!(local variable) std.typecons.Tuple!(int, "status", string, "output") buildbuild.status, (field) int std.typecons.Tuple!(int, "status", string, "output").__expand_field_0build.output);
auto (local variable) string[string] envenv = (class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment.string[string] std.process.environment.toAA() @trustedCopies all environment variables into an associative array.
Windows specific
While Windows environment variable names are case insensitive, D's
built-in associative arrays are not. This function will store all
variable names in uppercase (e.g. PATH).
toAA;
(local variable) string[string] envenv.remove("LD_LIBRARY_PATH");
auto (local variable) std.typecons.Tuple!(int, "status", string, "output") depsdeps = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute(["ldd", (local variable) const(string) binarybinary], (local variable) string[string] envenv);
((parameter) string outputDiroutputDir ~ "/" ~ (local variable) string compilercompiler ~ ".ldd.log").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((local variable) std.typecons.Tuple!(int, "status", string, "output") depsdeps.output);
assert(!(local variable) std.typecons.Tuple!(int, "status", string, "output") depsdeps.status && !(field) int std.typecons.Tuple!(int, "status", string, "output").__expand_field_0deps.output.bool std.algorithm.searching.canFind!().canFind!(string, string)(string haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind("not found"), (local variable) std.typecons.Tuple!(int, "status", string, "output") depsdeps.output);
auto (local variable) std.typecons.Tuple!(int, "status", string, "output") runrun = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute([(local variable) const(string) binarybinary], (local variable) string[string] envenv);
assert(!(local variable) std.typecons.Tuple!(int, "status", string, "output") runrun.status, (field) int std.typecons.Tuple!(int, "status", string, "output").__expand_field_0run.output);
void std.stdio.writeln!(string, string)(string __param_0, string __param_1) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln((local variable) string compilercompiler, ": shared runtime and tree-sitter resolved without LD_LIBRARY_PATH");
}
return 0;
}