driver.dhover×1425all
/**
 * Process orchestration for the `--better-c`, `--wasm` and `--wasm-bare` runner modes:
 * extract the annotated tests (see $(MREF sparkles,test_runner,extract)),
 * generate a standalone program, compile it for the special environment, and
 * execute it.
 *
 * Uses only `std.process`/`std.file` so it works in every host package —
 * including `sparkles:base`, whose test build has no `core-cli`.
 */
module 
(package) sparkles
sparkles
.
(package) sparkles.test_runner
test_runner
.
(module) sparkles.test_runner.driver

Process orchestration for the --better-c, --wasm and --wasm-bare runner modes: extract the annotated tests (see sparkles.test_runner.extract), generate a standalone program, compile it for the special environment, and execute it.

Uses only std.process/std.file so it works in every host package — including sparkles:base, whose test build has no core-cli.

driver
;
import
(package) sparkles
sparkles
.
(package) sparkles.test_runner
test_runner
.
(module) sparkles.test_runner.extract

Source extraction of unittest bodies and generation of standalone -betterC / WebAssembly test programs.

unittest blocks cannot run under -betterC (druntime's test driver is absent) or on wasm32 targets, so the runner's --better-c / --wasm modes extract the annotated tests: each test's body is sliced out of its source file (located via __traits(getLocation) metadata gathered at discovery), re-emitted as a named function in a generated program with a hand-rolled main, compiled for the special environment, and executed. The same approach — reflection-driven instead of parser-driven — replaces dlang's libdparse-based tests_extractor.

Extracted tests import their module, so they can only reference its public symbols. By default the driver also compiles that module into the generated program (-i=<module>), so ordinary functions are reachable and not just templates; a test that opts out with @betterC(selfContained: true) keeps its module out entirely and is then limited to templates and CTFE-able code (the phobos @betterC suite's model, and what lets a module that cannot itself compile under -betterC still host such a test).

This module also generates the @ctfe probe program (see generateCtfeProgram), which involves no extraction at all: the probe imports the tests' modules and selects tests by reflection, so their bodies stay in place.

Everything in this module is pure string processing — the process orchestration lives in sparkles.test_runner.driver.

extract
:
(struct) sparkles.test_runner.extract.CtfeTarget

One @ctfe test to force through CTFE in a generated probe program.

CtfeTarget
,
(struct) sparkles.test_runner.extract.ExtractedTest

One extracted test, ready to be emitted into a generated program.

ExtractedTest
,
(alias) sparkles.test_runner.driver.extractUnittestBody = string sparkles.test_runner.extract.extractUnittestBody(string source, ulong line) pure @safe

Extracts the body of the unittest block declared at line (its __traits(getLocation) line): the text between the block's braces, without the braces themselves. Returns null when no block is found.

extractUnittestBody
,
(alias) sparkles.test_runner.driver.generateBetterCProgram = string sparkles.test_runner.extract.generateBetterCProgram(in sparkles.test_runner.extract.ExtractedTest[] tests) pure @safe

A complete standalone -betterC program running the given tests: the extracted functions plus an extern(C) main announcing each test before running it (so an assert abort is attributable).

generateBetterCProgram
,
(alias) sparkles.test_runner.driver.generateCtfeProgram = string sparkles.test_runner.extract.generateCtfeProgram(in sparkles.test_runner.extract.CtfeTarget[] targets) pure @safe

A complete probe program forcing the given @ctfe tests through CTFE.

The probe imports each test's module and selects the tests by reflection (matching __traits(getLocation) lines), so test bodies stay in their home modules — private symbols keep working and no source extraction is involved. It is meant to be compiled with -o- -unittest together with the modules' source files: semantic analysis (and therefore CTFE) only, no code generation. A failing test is a compile error whose closing error instantiating line carries the test's display name.

generateCtfeProgram
,
(alias) sparkles.test_runner.driver.generateWasiProgram = string sparkles.test_runner.extract.generateWasiProgram(in sparkles.test_runner.extract.ExtractedTest[] tests) pure @safe

A complete WASI program running the given tests (--wasm): the extracted functions plus a main that announces and runs each one, catching what it throws, so one failing test does not hide the rest. The full druntime is there, so a failed assert is an AssertError like any other Throwable. The exit status is 1 when any test failed.

generateWasiProgram
,
(alias) sparkles.test_runner.driver.generateWasmBareJsShim = string sparkles.test_runner.extract.generateWasmBareJsShim(in sparkles.test_runner.extract.ExtractedTest[] tests, string wasmFile) pure @safe

The JavaScript shim executing a generated wasm test module under node, deno, or bun: instantiates the module and calls each run_test_<i> export, reporting per-test outcomes.

generateWasmBareJsShim
,
(alias) sparkles.test_runner.driver.generateWasmBareProgram = string sparkles.test_runner.extract.generateWasmBareProgram(in sparkles.test_runner.extract.ExtractedTest[] tests) pure @safe

A complete bare wasm32 test module (--wasm-bare): the extracted functions, each exported as test_<i> for individual invocation by the host shim, plus a trapping __assert handler (there is no libc on bare wasm32, so a failed assert traps and surfaces as a host-side RuntimeError).

generateWasmBareProgram
,
(alias) sparkles.test_runner.driver.sourceRootOf = string sparkles.test_runner.extract.sourceRootOf(string file, string moduleName) pure nothrow @safe

Derives the source root of a module from its file path and dotted name: ("libs/base/src/sparkles/base/buffer.d", "sparkles.base.buffer") yields "libs/base/src". Returns null when the path does not end with the module path. Either separator matches: on Windows the compiler reports libs\base\src\sparkles\base\buffer.d, and the root keeps its own separators.

sourceRootOf
;
import
(package) sparkles
sparkles
.
(package) sparkles.test_runner
test_runner
.
(module) sparkles.test_runner.model

Data model of the test runner: descriptions of discovered tests and the results of executing them.

Everything here is runtime data — the compile-time discovery that produces it lives in sparkles.test_runner.discovery.

model
:
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
;
/// Where the modes' messages go. The core prints nothing (process-model /// TRM1): its client renders these, to a terminal or as task output. struct
(struct) sparkles.test_runner.driver.ModeReport

Where the modes' messages go. The core prints nothing (process-model TRM1): its client renders these, to a terminal or as task output.

ModeReport
{ /// A mode's report: per-test lines, the tests' own output. void delegate(
(alias) object.string = string
string
) @safe
(field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.output

A mode's report: per-test lines, the tests' own output.

output
;
/// Why a mode skipped or failed, and the commands echoed under `-v`. void delegate(
(alias) object.string = string
string
) @safe
(field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.diagnostics

Why a mode skipped or failed, and the commands echoed under -v.

diagnostics
;
} /// `args` and a line feed, to `report`'s output. private void
void sparkles.test_runner.driver.say!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safe

args and a line feed, to report's output.

say
(Args...)(in
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
,
Args
Args
(parameter) Args args
args
)
{ import
(package) std
std
.
(module) std.conv

A 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

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Shin Fujishiro, Adam D. Ruppe, Kenji Hara
conv
:
(alias template) text = std.conv.text(T...)(T args) if (T.length > 0)

Convenience functions for converting one or more arguments of any type into _text (the three character widths).

text
;
if (
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.report

where the modes' messages go

report
.
(field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.output

A mode's report: per-test lines, the tests' own output.

output
!is null)
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.report

where the modes' messages go

report
.
(field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.output

A mode's report: per-test lines, the tests' own output.

output
(
string std.conv.text!(string, string)(string __param_0, string __param_1) pure nothrow @safe

Convenience functions for converting one or more arguments of any type into text (the three character widths).

text
(args, "\n"));
} /// `text`, as it is, to `report`'s output. private void
void sparkles.test_runner.driver.sayRaw(in sparkles.test_runner.driver.DriverOptions options, string text)

text, as it is, to report's output.

sayRaw
(in
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
,
(alias) object.string = string
string
(parameter) string text
text
)
{ if (
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.report

where the modes' messages go

report
.
(field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.output

A mode's report: per-test lines, the tests' own output.

output
!is null)
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.report

where the modes' messages go

report
.
(field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.output

A mode's report: per-test lines, the tests' own output.

output
(
(parameter) string text
text
);
} /// `args` and a line feed, to `report`'s diagnostics. private void
void sparkles.test_runner.driver.warn!(string, string, string, string, string, string, string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2, string __param_3, string __param_4, string __param_5, string __param_6, string __param_7, string __param_8) @safe

args and a line feed, to report's diagnostics.

warn
(Args...)(in
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
,
Args
Args
(parameter) Args args
args
)
{
void sparkles.test_runner.driver.warnTo!(string, string, string, string, string, string, string, string)(in sparkles.test_runner.driver.ModeReport report, string __param_1, string __param_2, string __param_3, string __param_4, string __param_5, string __param_6, string __param_7, string __param_8) @safe

args and a line feed, to report's diagnostics.

warnTo
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.report

where the modes' messages go

report
, args);
} /// ditto private void
void sparkles.test_runner.driver.warnTo!(string, string, string, string, string, string, string, string)(in sparkles.test_runner.driver.ModeReport report, string __param_1, string __param_2, string __param_3, string __param_4, string __param_5, string __param_6, string __param_7, string __param_8) @safe

args and a line feed, to report's diagnostics.

warnTo
(Args...)(in
(struct) sparkles.test_runner.driver.ModeReport

Where the modes' messages go. The core prints nothing (process-model TRM1): its client renders these, to a terminal or as task output.

ModeReport
(parameter) const(sparkles.test_runner.driver.ModeReport) report
report
,
Args
Args
(parameter) Args args
args
)
{ import
(package) std
std
.
(module) std.conv

A 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

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Shin Fujishiro, Adam D. Ruppe, Kenji Hara
conv
:
(alias template) text = std.conv.text(T...)(T args) if (T.length > 0)

Convenience functions for converting one or more arguments of any type into _text (the three character widths).

text
;
if (
(parameter) const(sparkles.test_runner.driver.ModeReport) report
report
.
(field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.diagnostics

Why a mode skipped or failed, and the commands echoed under -v.

diagnostics
!is null)
(parameter) const(sparkles.test_runner.driver.ModeReport) report
report
.
(field) void delegate(string) @safe sparkles.test_runner.driver.ModeReport.diagnostics

Why a mode skipped or failed, and the commands echoed under -v.

diagnostics
(
string std.conv.text!(string, string, string, string, string, string, string, string, string)(string __param_0, string __param_1, string __param_2, string __param_3, string __param_4, string __param_5, string __param_6, string __param_7, string __param_8) pure nothrow @safe

Convenience functions for converting one or more arguments of any type into text (the three character widths).

text
(args, "\n"));
} /// Options shared by both driver modes. struct
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
{
(alias) object.string = string
string
(field) string sparkles.test_runner.driver.DriverOptions.compiler

explicit D compiler; empty = $DC, then ldc2, dmd

compiler
; /// explicit D compiler; empty = `$DC`, then `ldc2`, `dmd`
(alias) object.string = string
string
[]
(field) string[] sparkles.test_runner.driver.DriverOptions.importPaths

extra -I paths

importPaths
; /// extra `-I` paths
(alias) object.string = string
string
[]
(field) string[] sparkles.test_runner.driver.DriverOptions.includeImports

extra -i=<pattern> module-inclusion patterns

includeImports
; /// extra `-i=<pattern>` module-inclusion patterns
bool
(field) bool sparkles.test_runner.driver.DriverOptions.noAutoInclude

don't compile the extracted tests' own modules in

noAutoInclude
; /// don't compile the extracted tests' own modules in
bool
(field) bool sparkles.test_runner.driver.DriverOptions.keep

keep the generated files and print their location

keep
; /// keep the generated files and print their location
bool
(field) bool sparkles.test_runner.driver.DriverOptions.verbose

echo the commands that are run

verbose
; /// echo the commands that are run
(struct) sparkles.test_runner.driver.ModeReport

Where the modes' messages go. The core prints nothing (process-model TRM1): its client renders these, to a terminal or as task output.

ModeReport
(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.report

where the modes' messages go

report
; /// where the modes' messages go
(alias) object.string = string
string
[]
(field) string[] sparkles.test_runner.driver.DriverOptions.stringImportPaths

extra -J paths

stringImportPaths
; /// extra `-J` paths
(alias) object.string = string
string
[]
(field) string[] sparkles.test_runner.driver.DriverOptions.versions

version identifiers

versions
; /// version identifiers
(alias) object.string = string
string
[]
(field) string[] sparkles.test_runner.driver.DriverOptions.dflags

extra compiler flags

dflags
; /// extra compiler flags
(alias) object.string = string
string
(field) string sparkles.test_runner.driver.DriverOptions.probeDir

where generated programs go; empty = the temp directory

probeDir
; /// where generated programs go; empty = the temp directory
bool
(field) bool sparkles.test_runner.driver.DriverOptions.noDub

never run dub describe (process-model TRX2)

noDub
; /// never run `dub describe` (process-model TRX2)
(alias) object.string = string
string
[]
(field) string[] sparkles.test_runner.driver.DriverOptions.harnessRoots

the source roots the test binary reported

harnessRoots
; /// the source roots the test binary reported
} /// The probe directory of the current run (`DriverOptions.probeDir`). private __gshared
(alias) object.string = string
string
(__gshared global) string sparkles.test_runner.driver.probeRoot

The probe directory of the current run (DriverOptions.probeDir).

probeRoot
;
/// Sets where generated programs go for the rest of the run. void
void sparkles.test_runner.driver.setProbeDir(string dir)

Sets where generated programs go for the rest of the run.

setProbeDir
(
(alias) object.string = string
string
(parameter) string dir
dir
)
{
(__gshared global) string sparkles.test_runner.driver.probeRoot

The probe directory of the current run (DriverOptions.probeDir).

probeRoot
=
(parameter) string dir
dir
;
} /// The outcome of one driver run. struct
(struct) sparkles.test_runner.driver.DriverOutcome

The outcome of one driver run.

DriverOutcome
{
(alias) object.size_t = ulong
size_t
(field) ulong sparkles.test_runner.driver.DriverOutcome.testCount
testCount
;
bool
(field) bool sparkles.test_runner.driver.DriverOutcome.succeeded
succeeded
= true;
bool
(field) bool sparkles.test_runner.driver.DriverOutcome.skipped

missing toolchain — reported but not a failure

skipped
; /// missing toolchain — reported but not a failure
} // ───────────────────────────────────────────────────────────────────────────── // Helpers // ───────────────────────────────────────────────────────────────────────────── /// Whether an executable is reachable through `searchPath` (`$PATH` by /// default). On Windows the file is `name.exe`, as `CreateProcess` finds it: /// `$DC=ldc2` names `ldc2.exe` there. /// /// A local re-implementation rather than `sparkles.core_cli.process_utils.isInPath`: /// this module is source-compiled into `base`'s test build, which has no /// `core-cli` dependency (the impl-library cycle is `impl → base`). private bool
bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safe

Whether an executable is reachable through searchPath ($PATH by default). On Windows the file is ``name.exe, as CreateProcess finds it: $DC=ldc2 names ldc2.exe there.

A local re-implementation rather than sparkles.core_cli.process_utils.isInPath: this module is source-compiled into base's test build, which has no core-cli dependency (the impl-library cycle is impl → base).

inPath
(
(alias) object.string = string
string
(parameter) string name
name
,
(alias) object.string = string
string
(parameter) string searchPath
searchPath
= null) @safe
{ import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.iteration

This is a submodule of std.algorithm. It contains generic iteration algorithms.

Function Name Description
cache Eagerly evaluates and caches another range's front.
lazyCache Lazily evaluates and caches another range's front, unlike cache.
cacheBidirectional As above, but also provides back and popBack.
chunkBy chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]]) returns a range containing 3 subranges: the first with just [1, 1]; the second with the elements [1, 2] and [2, 2]; and the third with just [2, 1].
cumulativeFold cumulativeFold!((a, b) => a + b)([1, 2, 3, 4]) returns a lazily-evaluated range containing the successive reduced values 1, 3, 6, 10.
each each!writeln([1, 2, 3]) eagerly prints the numbers 1, 2 and 3 on their own lines.
filter filter!(a => a > 0)([1, -1, 2, 0, -3]) iterates over elements 1 and 2.
filterBidirectional Similar to filter, but also provides back and popBack at a small increase in cost.
fold fold!((a, b) => a + b)([1, 2, 3, 4]) returns 10.
group group([5, 2, 2, 3, 3]) returns a range containing the tuples tuple(5, 1), tuple(2, 2), and tuple(3, 2).
joiner joiner(["hello", "world!"], "; ") returns a range that iterates over the characters "hello; world!". No new string is created - the existing inputs are iterated.
map map!(a => a * 2)([1, 2, 3]) lazily returns a range with the numbers 2, 4, 6.
mean Colloquially known as the average, mean([1, 2, 3]) returns 2.
permutations Lazily computes all permutations using Heap's algorithm.
reduce reduce!((a, b) => a + b)([1, 2, 3, 4]) returns 10. This is the old implementation of fold.
splitWhen Lazily splits a range by comparing adjacent elements.
splitter Lazily splits a range by a separator, element predicate or whitespace.
substitute [1, 2].substitute(1, 0.1) returns [0.1, 2].
sum Same as fold, but specialized for accurate summation.
uniq Iterates over the unique elements in a range, which is assumed sorted.

Source

std/algorithm/iteration.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
iteration
:
(alias template) splitter = std.algorithm.iteration.splitter(alias pred = "a == b", Flag keepSeparators = No.keepSeparators, Range, Separator)(Range r, Separator s) if (is(typeof(binaryFun!pred(r.front, s)) : bool) && (hasSlicing!Range && hasLength!Range || isNarrowString!Range) && (is(ElementType!Range : Separator) || !(isForwardRange!Separator && (hasLength!Separator || isNarrowString!Separator))))

Lazily splits a range using an element or range as a separator. Separator ranges can be any narrow string type or sliceable range type.

Two adjacent separators are considered to surround an empty element in the split range. Use filter!(a => !a.empty) on the result to compress empty elements.

The predicate is passed to $(REF binaryFun, std,functional) and accepts any callable function that can be executed via pred(element, s).

Note: If splitting a string on whitespace and token compression is desired, consider using the splitter(r) overload.

Params: pred = The predicate for comparing each element with the separator, defaulting to "a == b". r = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives) to be split. Must support slicing and .length or be a narrow string type. s = The element (or range) to be treated as the separator between range segments to be split. keepSeparators = The flag for deciding if the separators are kept

Constraints: The predicate pred needs to accept an element of r and the separator s.

Returns: An input range of the subranges of elements between separators. If r is a $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) or $(REF_ALTTEXT bidirectional range, isBidirectionalRange, std,range,primitives), the returned range will be likewise. When a range is used a separator, bidirectionality isn't possible.

    If `keepSeparators` is equal to `Yes.keepSeparators` the output will also contain the
    separators.

    If an empty range is given, the result is an empty range. If a range with
    one separator is given, the result is a range with two empty elements.

See_Also:

  • $(REF _splitter, std,regex) for a version that splits using a regular expression defined separator.

  • $(REF _split, std,array) for a version that splits eagerly.

  • $(LREF splitWhen), which compares adjacent elements instead of element against separator.

splitter
;
import
(package) std
std
.
(module) std.file

Utilities 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

@copyrightCopyright The D Language Foundation 2007 - 2011.@seeThe official tutorial for an introduction to working with files in D, module std.stdio for opening files and manipulating them via handles, and module std.path for manipulating path strings.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis
file
:
(alias template) exists = std.file.exists(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)

Determine whether the given file (or directory) _exists. Params: name = string or range of characters representing the file _name Returns: true if the file name specified as input exists

exists
,
(alias template) isFile = std.file.isFile(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)

Returns whether the given file (or directory) is a file.

    On Windows, if a file is not a directory, then it's a file. So,
    either `isFile` or `isDir` will return true for any given file.

    On POSIX systems, if `isFile` is `true`, that indicates that the file
    is a regular file (e.g. not a block not device). So, on POSIX systems, it's
    possible for both `isFile` and `isDir` to be `false` for a
    particular file (in which case, it's a special file). You can use
    `getAttributes` to get the attributes to figure out what type of special
    it is, or you can use `DirEntry` to get at its `statBuf`, which is the
    result from `stat`. In either case, see the man page for `stat` for
    more information.

    Params:
        name = The path to the file.

    Returns:
        true if name specifies a file

    Throws:
        $(LREF FileException) if the given file does not exist.
isFile
;
import
(package) std
std
.
(module) std.path

This module is used to manipulate path strings.

All functions, with the exception of expandTilde (and in some cases absolutePath and relativePath), are pure string manipulation functions; they don't depend on any state outside the program, nor do they perform any actual file system actions. This has the consequence that the module does not make any distinction between a path that points to a directory and a path that points to a file, and it does not know whether or not the object pointed to by the path actually exists in the file system. To differentiate between these cases, use isDir and exists.

Note that on Windows, both the backslash (\) and the slash (/) are in principle valid directory separators. This module treats them both on equal footing, but in cases where a new separator is added, a backslash will be used. Furthermore, the buildNormalizedPath function will replace all slashes with backslashes on that platform.

In general, the functions in this module assume that the input paths are well-formed. (That is, they should not contain invalid characters, they should follow the file system's path format, etc.) The result of calling a function on an ill-formed path is undefined. When there is a chance that a path or a file name is invalid (for instance, when it has been input by the user), it may sometimes be desirable to use the isValidFilename and isValidPath functions to check this.

Most functions do not perform any memory allocations, and if a string is returned, it is usually a slice of an input string. If a function allocates, this is explicitly mentioned in the documentation.

Category Functions
Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde
Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive
Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath
Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension
Other filenameCharCmp filenameCmp globMatch CaseSensitive

Source

std/path.d

@authorsLars Tandle Kyllingstad, Walter Bright, Grzegorz Adam Hankiewicz, Thomas Khne, Andrei Alexandrescu@copyrightCopyright (c) 2000-2014, the authors. All rights reserved.@licenseBoost License 1.0
path
:
(alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))

Combines one or more path segments.

    This function takes a set of path segments, given as an input
    range of string elements or as a set of string arguments,
    and concatenates them with each other.  Directory separators
    are inserted between segments if necessary.  If any of the
    path segments are absolute (as defined by $(LREF isAbsolute)), the
    preceding segments will be dropped.

    On Windows, if one of the path segments are rooted, but not absolute
    (e.g. $(D `\foo`)), all preceding path segments down to the previous
    root will be dropped.  (See below for an example.)

    This function always allocates memory to hold the resulting path.
    The variadic overload is guaranteed to only perform a single
    allocation, as is the range version if `paths` is a forward
    range.

    Params:
        segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
        of segments to assemble the path from.
    Returns: The assembled path.
buildPath
,
(alias template) extension = std.path.extension(R)(R path) if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) || is(StringTypeOf!R))

Params: path = A path name. Returns: The _extension part of a file name, including the dot.

    If there is no _extension, `null` is returned.
extension
,
(alias constant) pathSeparator = string std.path.pathSeparator = ":"

Path separator string. A colon under POSIX, a semicolon under Windows.

pathSeparator
;
import
(package) std
std
.
(module) std.process

Functions 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.

@authorsLars Tandle Kyllingstad, Steven Schveighoffer, Vladimir Panteleev@copyrightCopyright (c) 2013, the authors. All rights reserved.@licenseBoost License 1.0.
process
:
(class) std.process.environment

Manipulates 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
;
if (
(parameter) string searchPath
searchPath
is null)
(parameter) string searchPath
searchPath
=
(class) std.process.environment

Manipulates 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) @safe

Retrieves 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.
}
@paramname name of the environment variable to retrieve@paramdefaultValue default value to return if the environment variable doesn't exist.@returnsthe value of the environment variable if found, otherwise null if the environment doesn't exist.@throwsUTFException if the variable contains invalid UTF-16 characters (Windows only).
get
("PATH", "");
version (
Windows
Windows
)
const file = name.extension.length ? name : name ~ ".exe"; else const
(local variable) const(string) file
file
=
(parameter) string name
name
;
foreach (
(local variable) string dir
dir
;
(parameter) string searchPath
searchPath
.
std.algorithm.iteration.splitter!("a == b", Flag.no, string, string).Result std.algorithm.iteration.splitter!("a == b", Flag.no, string, string)(string r, string s) pure nothrow @nogc @safe

Splitter returns bidirectional ranges if the delimiter is a single element

splitter
(
(constant) string std.path.pathSeparator = ":"

Path separator string. A colon under POSIX, a semicolon under Windows.

pathSeparator
))
{ const
(local variable) const(string) candidate
candidate
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) string dir
dir
,
(local variable) const(string) file
file
);
if (
(local variable) string dir
dir
.
(field) ulong string.length
length
&&
(local variable) const(string) candidate
candidate
.
bool std.file.exists!string(string name) nothrow @nogc @safe

Determine whether the given file (or directory) exists.

@paramname string or range of characters representing the file name@returnstrue if the file name specified as input exists
exists
&&
(local variable) const(string) candidate
candidate
.
bool std.file.isFile!string(string name) @property @safe

Returns whether the given file (or directory) is a file.

On Windows, if a file is not a directory, then it's a file. So, either isFile or isDir will return true for any given file.

On POSIX systems, if isFile is true, that indicates that the file is a regular file (e.g. not a block not device). So, on POSIX systems, it's possible for both isFile and isDir to be false for a particular file (in which case, it's a special file). You can use getAttributes to get the attributes to figure out what type of special it is, or you can use DirEntry to get at its statBuf, which is the result from stat. In either case, see the man page for stat for more information.

@paramname The path to the file.@returnstrue if name specifies a file@throwsFileException if the given file does not exist.
isFile
)
return true; } return false; } @("inPath.platformExecutableName") @safe unittest { import
(package) std
std
.
(module) std.conv

A 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

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Shin Fujishiro, Adam D. Ruppe, Kenji Hara
conv
:
(alias template) text = std.conv.text(T...)(T args) if (T.length > 0)

Convenience functions for converting one or more arguments of any type into _text (the three character widths).

text
;
import
(package) std
std
.
(module) std.file

Utilities 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

@copyrightCopyright The D Language Foundation 2007 - 2011.@seeThe official tutorial for an introduction to working with files in D, module std.stdio for opening files and manipulating them via handles, and module std.path for manipulating path strings.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis
file
:
(alias) mkdirRecurse = void std.file.mkdirRecurse(scope const(char)[] pathname) @safe

Make directory and all parent directories as needed.

Does nothing if the directory specified by pathname already exists.

Params: pathname = the full path of the directory to create

Throws: $(LREF FileException) on error.

mkdirRecurse
,
(alias) rmdirRecurse = void std.file.rmdirRecurse(scope const(char)[] pathname) @safe

Remove directory and all of its content and subdirectories, recursively.

    Params:
        pathname = the path of the directory to completely remove
        de = The $(LREF DirEntry) to remove

    Throws:
        $(LREF FileException) if there is an error (including if the given
        file is not a directory).
rmdirRecurse
,
(alias) tempDir = string std.file.tempDir() @trusted

Returns the path to a directory for temporary files. On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist: $(OL $(LI The directory given by the TMPDIR environment variable.) $(LI The directory given by the `TEMP` environment variable.) $(LI The directory given by the TMP environment variable.) $(LI `/tmp/`) $(LI /var/tmp/) $(LI /usr/tmp/) )

On all platforms, tempDir returns the current working directory on failure.

The return value of the function is cached, so the procedures described below will only be performed the first time the function is called. All subsequent runs will return the same string, regardless of whether environment variables and directory structures have changed in the meantime.

The POSIX tempDir algorithm is inspired by Python's $(LINK2 http://docs.python.org/library/tempfile.html#tempfile.tempdir, tempfile.tempdir).

Returns: On Windows, this function returns the result of calling the Windows API function $(LINK2 http://msdn.microsoft.com/en-us/library/windows/desktop/aa364992.aspx, GetTempPath).

    On POSIX platforms, it searches through the following list of directories
    and returns the first one which is found to exist:
    $(OL
        $(LI The directory given by the `TMPDIR` environment variable.)
        $(LI The directory given by the `TEMP` environment variable.)
        $(LI The directory given by the `TMP` environment variable.)
        $(LI `/tmp`)
        $(LI `/var/tmp`)
        $(LI `/usr/tmp`)
    )

    On all platforms, `tempDir` returns `"."` on failure, representing
    the current working directory.
tempDir
,
(alias template) 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.

Params: name = string or range of characters representing the file _name buffer = data to be written to file

Throws: $(LREF FileException) on error.

See_also: $(REF toFile, std,stdio)

write
;
import
(package) std
std
.
(module) std.path

This module is used to manipulate path strings.

All functions, with the exception of expandTilde (and in some cases absolutePath and relativePath), are pure string manipulation functions; they don't depend on any state outside the program, nor do they perform any actual file system actions. This has the consequence that the module does not make any distinction between a path that points to a directory and a path that points to a file, and it does not know whether or not the object pointed to by the path actually exists in the file system. To differentiate between these cases, use isDir and exists.

Note that on Windows, both the backslash (\) and the slash (/) are in principle valid directory separators. This module treats them both on equal footing, but in cases where a new separator is added, a backslash will be used. Furthermore, the buildNormalizedPath function will replace all slashes with backslashes on that platform.

In general, the functions in this module assume that the input paths are well-formed. (That is, they should not contain invalid characters, they should follow the file system's path format, etc.) The result of calling a function on an ill-formed path is undefined. When there is a chance that a path or a file name is invalid (for instance, when it has been input by the user), it may sometimes be desirable to use the isValidFilename and isValidPath functions to check this.

Most functions do not perform any memory allocations, and if a string is returned, it is usually a slice of an input string. If a function allocates, this is explicitly mentioned in the documentation.

Category Functions
Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde
Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive
Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath
Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension
Other filenameCharCmp filenameCmp globMatch CaseSensitive

Source

std/path.d

@authorsLars Tandle Kyllingstad, Walter Bright, Grzegorz Adam Hankiewicz, Thomas Khne, Andrei Alexandrescu@copyrightCopyright (c) 2000-2014, the authors. All rights reserved.@licenseBoost License 1.0
path
:
(alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))

Combines one or more path segments.

    This function takes a set of path segments, given as an input
    range of string elements or as a set of string arguments,
    and concatenates them with each other.  Directory separators
    are inserted between segments if necessary.  If any of the
    path segments are absolute (as defined by $(LREF isAbsolute)), the
    preceding segments will be dropped.

    On Windows, if one of the path segments are rooted, but not absolute
    (e.g. $(D `\foo`)), all preceding path segments down to the previous
    root will be dropped.  (See below for an example.)

    This function always allocates memory to hold the resulting path.
    The variadic overload is guaranteed to only perform a single
    allocation, as is the range version if `paths` is a forward
    range.

    Params:
        segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
        of segments to assemble the path from.
    Returns: The assembled path.
buildPath
,
(alias constant) pathSeparator = string std.path.pathSeparator = ":"

Path separator string. A colon under POSIX, a semicolon under Windows.

pathSeparator
;
import
(package) std
std
.
(module) std.process

Functions 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.

@authorsLars Tandle Kyllingstad, Steven Schveighoffer, Vladimir Panteleev@copyrightCopyright (c) 2013, the authors. All rights reserved.@licenseBoost License 1.0.
process
:
(alias) thisProcessID = int std.process.thisProcessID() nothrow @nogc @property @trusted

Returns the process ID of the current process, which is guaranteed to be unique on the system.

Example:

writefln("Current process ID: %d", thisProcessID); ---

thisProcessID
;
const
(local variable) const(string) dir
dir
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
string std.file.tempDir() @trusted

Returns the path to a directory for temporary files. On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp/

  5. /var/tmp/

  6. /usr/tmp/

On all platforms, tempDir returns the current working directory on failure.

The return value of the function is cached, so the procedures described below will only be performed the first time the function is called. All subsequent runs will return the same string, regardless of whether environment variables and directory structures have changed in the meantime.

The POSIX tempDir algorithm is inspired by Python's tempfile.tempdir.

Examples

import std.ascii : letters;
import std.conv : to;
import std.path : buildPath;
import std.random : randomSample;
import std.utf : byCodeUnit;

// random id with 20 letters
auto id = letters.byCodeUnit.randomSample(20).to!string;
auto myFile = tempDir.buildPath(id ~ "my_tmp_file");
scope(exit) myFile.remove;

myFile.write("hello");
assert(myFile.readText == "hello");
@returns

On Windows, this function returns the result of calling the Windows API function GetTempPath.

On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp

  5. /var/tmp

  6. /usr/tmp

On all platforms, tempDir returns "." on failure, representing the current working directory.

tempDir
,
string std.conv.text!(string, int)(string __param_0, int __param_1) pure nothrow @safe

Convenience functions for converting one or more arguments of any type into text (the three character widths).

text
("sparkles-inpath-",
int std.process.thisProcessID() nothrow @nogc @property @trusted

Returns the process ID of the current process, which is guaranteed to be unique on the system.

Example

writefln("Current process ID: %d", thisProcessID);
thisProcessID
));
void std.file.mkdirRecurse(scope const(char)[] pathname) @safe

Make 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);
@parampathname the full path of the directory to create@throwsFileException on error.
mkdirRecurse
(
(local variable) const(string) dir
dir
);
scope (exit)
void std.file.rmdirRecurse(scope const(char)[] pathname) @safe

Remove directory and all of its content and subdirectories, recursively.

@parampathname the path of the directory to completely remove@paramde The DirEntry to remove@throwsFileException if there is an error (including if the given file is not a directory).
rmdirRecurse
(
(local variable) const(string) dir
dir
);
version (
Windows
Windows
)
write(buildPath(dir, "probe-tool.exe"), ""); else
void std.file.write!string(string name, const(void[]) buffer) @safe

Write 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);
@paramname string or range of characters representing the file name@parambuffer data to be written to file@throwsFileException on error.@seetoFile
write
(
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) const(string) dir
dir
, "probe-tool"), "");
const
(local variable) const(string) search
search
= "" ~
(constant) string std.path.pathSeparator = ":"

Path separator string. A colon under POSIX, a semicolon under Windows.

pathSeparator
~
(local variable) const(string) dir
dir
;
assert(
bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safe

Whether an executable is reachable through searchPath ($PATH by default). On Windows the file is ``name.exe, as CreateProcess finds it: $DC=ldc2 names ldc2.exe there.

A local re-implementation rather than sparkles.core_cli.process_utils.isInPath: this module is source-compiled into base's test build, which has no core-cli dependency (the impl-library cycle is impl → base).

inPath
("probe-tool",
(local variable) const(string) search
search
), "found by the name a caller spawns");
assert(!
bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safe

Whether an executable is reachable through searchPath ($PATH by default). On Windows the file is ``name.exe, as CreateProcess finds it: $DC=ldc2 names ldc2.exe there.

A local re-implementation rather than sparkles.core_cli.process_utils.isInPath: this module is source-compiled into base's test build, which has no core-cli dependency (the impl-library cycle is impl → base).

inPath
("absent-tool",
(local variable) const(string) search
search
));
} /// The D compiler to use: explicit choice, `$DC`, or the first of /// `ldc2`/`dmd` found in `$PATH` (empty string when none). An explicit choice /// that doesn't resolve is reported to `report` and treated as "no compiler", so /// the caller's toolchain-missing skip fires instead of a raw /// `ProcessException` escaping from the spawn.
(alias) object.string = string
string
string sparkles.test_runner.driver.detectCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report = ModeReport(null, null)) @safe

The D compiler to use: explicit choice, $DC, or the first of ldc2/dmd found in $PATH (empty string when none). An explicit choice that doesn't resolve is reported to report and treated as "no compiler", so the caller's toolchain-missing skip fires instead of a raw ProcessException escaping from the spawn.

detectCompiler
(
(alias) object.string = string
string
(parameter) string preferred
preferred
, in
(struct) sparkles.test_runner.driver.ModeReport

Where the modes' messages go. The core prints nothing (process-model TRM1): its client renders these, to a terminal or as task output.

ModeReport
(parameter) const(sparkles.test_runner.driver.ModeReport) report
report
=
(struct) sparkles.test_runner.driver.ModeReport

Where the modes' messages go. The core prints nothing (process-model TRM1): its client renders these, to a terminal or as task output.

ModeReport
.
(constant) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.ModeReport.init = ModeReport(null, null)
init
) @safe
{ import
(package) std
std
.
(module) std.process

Functions 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.

@authorsLars Tandle Kyllingstad, Steven Schveighoffer, Vladimir Panteleev@copyrightCopyright (c) 2013, the authors. All rights reserved.@licenseBoost License 1.0.
process
:
(class) std.process.environment

Manipulates 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
;
static bool
bool sparkles.test_runner.driver.detectCompiler.resolves(string compiler) @safe
resolves
(
(alias) object.string = string
string
(parameter) string compiler
compiler
) @safe
{ import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.searching

This is a submodule of std.algorithm. It contains generic searching algorithms.

Function Name Description
all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive
any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive
balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses.
boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm.
canFind canFind("hello world", "or") returns true.
count Counts all elements or elements matching a predicate, specific element or sub-range.

count([1, 2, 1]) returns 3, count([1, 2, 1], 1) returns 2 and count!"a < 0"([1, -3, 0]) returns 1. | | countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. | | commonPrefix | commonPrefix("parakeet", "parachute") returns "para". | | endsWith | endsWith("rocks", "ks") returns true. | | extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. | | find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) | | findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. | | findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". | | findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. | | findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". | | findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". | | findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". | | minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). | | maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). | | minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. | | maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. | | minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. | | maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. | | minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. | | maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. | | skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. | | startsWith | startsWith("hello, world", "hello") returns true. | | until | Lazily iterates a range until a specific value is found. |

Source

std/algorithm/searching.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
searching
:
(alias template) 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 $(LREF find).

See_Also: $(REF among, std,algorithm,comparison) for checking a value against multiple arguments.

canFind
;
import
(package) std
std
.
(module) std.file

Utilities 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

@copyrightCopyright The D Language Foundation 2007 - 2011.@seeThe official tutorial for an introduction to working with files in D, module std.stdio for opening files and manipulating them via handles, and module std.path for manipulating path strings.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis
file
:
(alias template) exists = std.file.exists(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)

Determine whether the given file (or directory) _exists. Params: name = string or range of characters representing the file _name Returns: true if the file name specified as input exists

exists
,
(alias template) isFile = std.file.isFile(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)

Returns whether the given file (or directory) is a file.

    On Windows, if a file is not a directory, then it's a file. So,
    either `isFile` or `isDir` will return true for any given file.

    On POSIX systems, if `isFile` is `true`, that indicates that the file
    is a regular file (e.g. not a block not device). So, on POSIX systems, it's
    possible for both `isFile` and `isDir` to be `false` for a
    particular file (in which case, it's a special file). You can use
    `getAttributes` to get the attributes to figure out what type of special
    it is, or you can use `DirEntry` to get at its `statBuf`, which is the
    result from `stat`. In either case, see the man page for `stat` for
    more information.

    Params:
        name = The path to the file.

    Returns:
        true if name specifies a file

    Throws:
        $(LREF FileException) if the given file does not exist.
isFile
;
return
(parameter) string compiler
compiler
.
bool std.algorithm.searching.canFind!().canFind!(string, char)(string haystack, scope char needle) pure @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
('/') ||
(parameter) string compiler
compiler
.
bool std.algorithm.searching.canFind!().canFind!(string, char)(string haystack, scope char needle) pure @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
('\\')
?
(parameter) string compiler
compiler
.
bool std.file.exists!string(string name) nothrow @nogc @safe

Determine whether the given file (or directory) exists.

@paramname string or range of characters representing the file name@returnstrue if the file name specified as input exists
exists
&&
(parameter) string compiler
compiler
.
bool std.file.isFile!string(string name) @property @safe

Returns whether the given file (or directory) is a file.

On Windows, if a file is not a directory, then it's a file. So, either isFile or isDir will return true for any given file.

On POSIX systems, if isFile is true, that indicates that the file is a regular file (e.g. not a block not device). So, on POSIX systems, it's possible for both isFile and isDir to be false for a particular file (in which case, it's a special file). You can use getAttributes to get the attributes to figure out what type of special it is, or you can use DirEntry to get at its statBuf, which is the result from stat. In either case, see the man page for stat for more information.

@paramname The path to the file.@returnstrue if name specifies a file@throwsFileException if the given file does not exist.
isFile
:
bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safe

Whether an executable is reachable through searchPath ($PATH by default). On Windows the file is ``name.exe, as CreateProcess finds it: $DC=ldc2 names ldc2.exe there.

A local re-implementation rather than sparkles.core_cli.process_utils.isInPath: this module is source-compiled into base's test build, which has no core-cli dependency (the impl-library cycle is impl → base).

inPath
(
(parameter) string compiler
compiler
);
}
(alias) object.string = string
string
string sparkles.test_runner.driver.detectCompiler.checked(string compiler, string origin) @safe
checked
(
(alias) object.string = string
string
(parameter) string compiler
compiler
,
(alias) object.string = string
string
(parameter) string origin
origin
) @safe
{ if (
bool sparkles.test_runner.driver.detectCompiler.resolves(string compiler) @safe
resolves
(
(parameter) string compiler
compiler
))
return
(parameter) string compiler
compiler
;
void sparkles.test_runner.driver.warnTo!(string, string, string, string)(in sparkles.test_runner.driver.ModeReport report, string __param_1, string __param_2, string __param_3, string __param_4) @safe

args and a line feed, to report's diagnostics.

warnTo
(
(parameter) const(sparkles.test_runner.driver.ModeReport) report
report
,
(parameter) string origin
origin
, ": compiler '",
(parameter) string compiler
compiler
, "' not found");
return null; } if (
(parameter) string preferred
preferred
.
(field) ulong string.length
length
)
return
string sparkles.test_runner.driver.detectCompiler.checked(string compiler, string origin) @safe
checked
(
(parameter) string preferred
preferred
, "--compiler");
if (const
(local variable) const(string) dc
dc
=
(class) std.process.environment

Manipulates 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) @safe

Retrieves 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.
}
@paramname name of the environment variable to retrieve@paramdefaultValue default value to return if the environment variable doesn't exist.@returnsthe value of the environment variable if found, otherwise null if the environment doesn't exist.@throwsUTFException if the variable contains invalid UTF-16 characters (Windows only).
get
("DC", null))
return
string sparkles.test_runner.driver.detectCompiler.checked(string compiler, string origin) @safe
checked
(
(local variable) const(string) dc
dc
, "$DC");
foreach (
(parameter) string candidate
candidate
; ["ldc2", "dmd"])
if (
bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safe

Whether an executable is reachable through searchPath ($PATH by default). On Windows the file is ``name.exe, as CreateProcess finds it: $DC=ldc2 names ldc2.exe there.

A local re-implementation rather than sparkles.core_cli.process_utils.isInPath: this module is source-compiled into base's test build, which has no core-cli dependency (the impl-library cycle is impl → base).

inPath
(
(local variable) string candidate
candidate
))
return
(local variable) string candidate
candidate
;
return null; } /// `-I` roots derived from every discovered test's module-name ↔ file-path /// pair, after the extras: the user's, then the harness roots the binary /// reported. Never the runner's own root: the pinned runner's copy of the /// attributes is not the one the tested package was compiled against /// (process-model TRX4).
(alias) object.string = string
string
[]
string[] sparkles.test_runner.driver.deriveImportPaths(in sparkles.test_runner.model.Test[] allTests, in string[] extra) pure @safe

-I roots derived from every discovered test's module-name ↔ file-path pair, after the extras: the user's, then the harness roots the binary reported. Never the runner's own root: the pinned runner's copy of the attributes is not the one the tested package was compiled against (process-model TRX4).

deriveImportPaths
(in
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
[]
(parameter) const(sparkles.test_runner.model.Test[]) allTests
allTests
, in
(alias) object.string = string
string
[]
(parameter) const(string[]) extra
extra
) @safe pure
{ import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.searching

This is a submodule of std.algorithm. It contains generic searching algorithms.

Function Name Description
all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive
any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive
balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses.
boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm.
canFind canFind("hello world", "or") returns true.
count Counts all elements or elements matching a predicate, specific element or sub-range.

count([1, 2, 1]) returns 3, count([1, 2, 1], 1) returns 2 and count!"a < 0"([1, -3, 0]) returns 1. | | countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. | | commonPrefix | commonPrefix("parakeet", "parachute") returns "para". | | endsWith | endsWith("rocks", "ks") returns true. | | extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. | | find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) | | findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. | | findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". | | findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. | | findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". | | findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". | | findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". | | minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). | | maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). | | minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. | | maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. | | minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. | | maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. | | minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. | | maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. | | skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. | | startsWith | startsWith("hello, world", "hello") returns true. | | until | Lazily iterates a range until a specific value is found. |

Source

std/algorithm/searching.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
searching
:
(alias template) 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 $(LREF find).

See_Also: $(REF among, std,algorithm,comparison) for checking a value against multiple arguments.

canFind
;
(alias) object.string = string
string
[]
(local variable) string[] roots
roots
=
(parameter) const(string[]) extra
extra
.
string[] object.dup!string(const(string)[] a) pure nothrow @property @safe
dup
;
foreach (ref
(parameter) const(sparkles.test_runner.model.Test) test
test
;
(parameter) const(sparkles.test_runner.model.Test[]) allTests
allTests
)
{ const
(local variable) const(string) root
root
=
string sparkles.test_runner.extract.sourceRootOf(string file, string moduleName) pure nothrow @safe

Derives the source root of a module from its file path and dotted name: ("libs/base/src/sparkles/base/buffer.d", "sparkles.base.buffer") yields "libs/base/src". Returns null when the path does not end with the module path. Either separator matches: on Windows the compiler reports libs\base\src\sparkles\base\buffer.d, and the root keeps its own separators.

sourceRootOf
(
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) string sparkles.test_runner.model.TestLocation.file
file
,
string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safe

The actual module containing test: ``test.moduleName with aggregate qualifiers stripped (a nested test's fullName includes its aggregate), found by peeling trailing components until the name matches the file path.

probeModuleName
(
(local variable) const(sparkles.test_runner.model.Test) test
test
));
if (
(local variable) const(string) root
root
!is null && !
(local variable) string[] roots
roots
.
bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
(
(local variable) const(string) root
root
))
(local variable) string[] roots
roots
~=
(local variable) const(string) root
root
;
} return
(local variable) string[] roots
roots
;
} @("deriveImportPaths.uniqueRoots") @safe pure unittest { import
(package) sparkles
sparkles
.
(package) sparkles.test_runner
test_runner
.
(module) sparkles.test_runner.model

Data model of the test runner: descriptions of discovered tests and the results of executing them.

Everything here is runtime data — the compile-time discovery that produces it lives in sparkles.test_runner.discovery.

model
:
(struct) sparkles.test_runner.model.TestLocation

Source location of a unittest block, from __traits(getLocation). The file path is as the compiler saw it (usually relative to the package root that dub test runs in).

TestLocation
;
const
(local variable) const(sparkles.test_runner.model.Test[]) tests
tests
= [
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
(fullName: "pkg.a.__unittest_L1_C1", name: "a",
location:
(struct) sparkles.test_runner.model.TestLocation

Source location of a unittest block, from __traits(getLocation). The file path is as the compiler saw it (usually relative to the package root that dub test runs in).

TestLocation
(file: "src/pkg/a.d", line: 1, column: 1)),
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
(fullName: "pkg.b.__unittest_L1_C1", name: "b",
location:
(struct) sparkles.test_runner.model.TestLocation

Source location of a unittest block, from __traits(getLocation). The file path is as the compiler saw it (usually relative to the package root that dub test runs in).

TestLocation
(file: "src/pkg/b.d", line: 1, column: 1)),
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
(fullName: "other.c.__unittest_L1_C1", name: "c",
location:
(struct) sparkles.test_runner.model.TestLocation

Source location of a unittest block, from __traits(getLocation). The file path is as the compiler saw it (usually relative to the package root that dub test runs in).

TestLocation
(file: "lib2/src/other/c.d", line: 1, column: 1)),
]; assert(
string[] sparkles.test_runner.driver.deriveImportPaths(in sparkles.test_runner.model.Test[] allTests, in string[] extra) pure @safe

-I roots derived from every discovered test's module-name ↔ file-path pair, after the extras: the user's, then the harness roots the binary reported. Never the runner's own root: the pinned runner's copy of the attributes is not the one the tested package was compiled against (process-model TRX4).

deriveImportPaths
(
(local variable) const(sparkles.test_runner.model.Test[]) tests
tests
, ["extra"]) == ["extra", "src", "lib2/src"]);
} /// The dub package root containing `sourceRoot`: the nearest ancestor /// directory (including itself) with a `dub.sdl`/`dub.json`, or `null`. private
(alias) object.string = string
string
string sparkles.test_runner.driver.findPackageRoot(string sourceRoot) @safe

The dub package root containing sourceRoot: the nearest ancestor directory (including itself) with a dub.sdl/dub.json, or null.

findPackageRoot
(
(alias) object.string = string
string
(parameter) string sourceRoot
sourceRoot
) @safe
{ import
(package) std
std
.
(module) std.file

Utilities 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

@copyrightCopyright The D Language Foundation 2007 - 2011.@seeThe official tutorial for an introduction to working with files in D, module std.stdio for opening files and manipulating them via handles, and module std.path for manipulating path strings.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis
file
:
(alias template) exists = std.file.exists(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)

Determine whether the given file (or directory) _exists. Params: name = string or range of characters representing the file _name Returns: true if the file name specified as input exists

exists
;
import
(package) std
std
.
(module) std.path

This module is used to manipulate path strings.

All functions, with the exception of expandTilde (and in some cases absolutePath and relativePath), are pure string manipulation functions; they don't depend on any state outside the program, nor do they perform any actual file system actions. This has the consequence that the module does not make any distinction between a path that points to a directory and a path that points to a file, and it does not know whether or not the object pointed to by the path actually exists in the file system. To differentiate between these cases, use isDir and exists.

Note that on Windows, both the backslash (\) and the slash (/) are in principle valid directory separators. This module treats them both on equal footing, but in cases where a new separator is added, a backslash will be used. Furthermore, the buildNormalizedPath function will replace all slashes with backslashes on that platform.

In general, the functions in this module assume that the input paths are well-formed. (That is, they should not contain invalid characters, they should follow the file system's path format, etc.) The result of calling a function on an ill-formed path is undefined. When there is a chance that a path or a file name is invalid (for instance, when it has been input by the user), it may sometimes be desirable to use the isValidFilename and isValidPath functions to check this.

Most functions do not perform any memory allocations, and if a string is returned, it is usually a slice of an input string. If a function allocates, this is explicitly mentioned in the documentation.

Category Functions
Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde
Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive
Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath
Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension
Other filenameCharCmp filenameCmp globMatch CaseSensitive

Source

std/path.d

@authorsLars Tandle Kyllingstad, Walter Bright, Grzegorz Adam Hankiewicz, Thomas Khne, Andrei Alexandrescu@copyrightCopyright (c) 2000-2014, the authors. All rights reserved.@licenseBoost License 1.0
path
:
(alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))

Combines one or more path segments.

    This function takes a set of path segments, given as an input
    range of string elements or as a set of string arguments,
    and concatenates them with each other.  Directory separators
    are inserted between segments if necessary.  If any of the
    path segments are absolute (as defined by $(LREF isAbsolute)), the
    preceding segments will be dropped.

    On Windows, if one of the path segments are rooted, but not absolute
    (e.g. $(D `\foo`)), all preceding path segments down to the previous
    root will be dropped.  (See below for an example.)

    This function always allocates memory to hold the resulting path.
    The variadic overload is guaranteed to only perform a single
    allocation, as is the range version if `paths` is a forward
    range.

    Params:
        segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
        of segments to assemble the path from.
    Returns: The assembled path.
buildPath
,
(alias template) dirName = std.path.dirName(R)(return scope R path) if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R)

Returns the parent directory of path. On Windows, this includes the drive letter if present. If path is a relative path and the parent directory is the current working directory, returns ".".

    Params:
        path = A path name.

    Returns:
        A slice of `path` or `"."`.

    Standards:
    This function complies with
    $(LINK2 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/dirname.html,
    the POSIX requirements for the 'dirname' shell utility)
    (with suitable adaptations for Windows paths).
dirName
;
for (
(alias) object.string = string
string
(local variable) string dir
dir
=
(parameter) string sourceRoot
sourceRoot
; dir.length && dir != "/" && dir != ".";
dir = dir.dirName) { if (
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) string dir
dir
, "dub.sdl").
bool std.file.exists!string(string name) nothrow @nogc @safe

Determine whether the given file (or directory) exists.

@paramname string or range of characters representing the file name@returnstrue if the file name specified as input exists
exists
||
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) string dir
dir
, "dub.json").
bool std.file.exists!string(string name) nothrow @nogc @safe

Determine whether the given file (or directory) exists.

@paramname string or range of characters representing the file name@returnstrue if the file name specified as input exists
exists
)
return
(local variable) string dir
dir
;
} return null; } /// Import paths reported by `dub describe` for the packages containing the /// derived source roots — this is how paths of registry dependencies (e.g. /// `expected`) are found. Best-effort: failures yield an empty list. private
(alias) object.string = string
string
[]
string[] sparkles.test_runner.driver.dubDescribeImportPaths(in string[] sourceRoots, in sparkles.test_runner.driver.DriverOptions options)

Import paths reported by dub describe for the packages containing the derived source roots — this is how paths of registry dependencies (e.g. expected) are found. Best-effort: failures yield an empty list.

dubDescribeImportPaths
(in
(alias) object.string = string
string
[]
(parameter) const(string[]) sourceRoots
sourceRoots
, in
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
)
{ import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.iteration

This is a submodule of std.algorithm. It contains generic iteration algorithms.

Function Name Description
cache Eagerly evaluates and caches another range's front.
lazyCache Lazily evaluates and caches another range's front, unlike cache.
cacheBidirectional As above, but also provides back and popBack.
chunkBy chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]]) returns a range containing 3 subranges: the first with just [1, 1]; the second with the elements [1, 2] and [2, 2]; and the third with just [2, 1].
cumulativeFold cumulativeFold!((a, b) => a + b)([1, 2, 3, 4]) returns a lazily-evaluated range containing the successive reduced values 1, 3, 6, 10.
each each!writeln([1, 2, 3]) eagerly prints the numbers 1, 2 and 3 on their own lines.
filter filter!(a => a > 0)([1, -1, 2, 0, -3]) iterates over elements 1 and 2.
filterBidirectional Similar to filter, but also provides back and popBack at a small increase in cost.
fold fold!((a, b) => a + b)([1, 2, 3, 4]) returns 10.
group group([5, 2, 2, 3, 3]) returns a range containing the tuples tuple(5, 1), tuple(2, 2), and tuple(3, 2).
joiner joiner(["hello", "world!"], "; ") returns a range that iterates over the characters "hello; world!". No new string is created - the existing inputs are iterated.
map map!(a => a * 2)([1, 2, 3]) lazily returns a range with the numbers 2, 4, 6.
mean Colloquially known as the average, mean([1, 2, 3]) returns 2.
permutations Lazily computes all permutations using Heap's algorithm.
reduce reduce!((a, b) => a + b)([1, 2, 3, 4]) returns 10. This is the old implementation of fold.
splitWhen Lazily splits a range by comparing adjacent elements.
splitter Lazily splits a range by a separator, element predicate or whitespace.
substitute [1, 2].substitute(1, 0.1) returns [0.1, 2].
sum Same as fold, but specialized for accurate summation.
uniq Iterates over the unique elements in a range, which is assumed sorted.

Source

std/algorithm/iteration.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
iteration
:
(alias template) 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 $(REF unaryFun, std,functional), and can be either a string, or any callable that can be executed via pred(element).

Params: predicate = Function to apply to each element of range

Returns: An input range that contains the filtered elements. If range is at least a forward range, the return value of filter will also be a forward range.

See_Also: $(HTTP en.wikipedia.org/wiki/Filter_(higher-order_function), Filter (higher-order function)), $(REF filterBidirectional, std,algorithm,iteration)

filter
;
import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.searching

This is a submodule of std.algorithm. It contains generic searching algorithms.

Function Name Description
all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive
any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive
balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses.
boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm.
canFind canFind("hello world", "or") returns true.
count Counts all elements or elements matching a predicate, specific element or sub-range.

count([1, 2, 1]) returns 3, count([1, 2, 1], 1) returns 2 and count!"a < 0"([1, -3, 0]) returns 1. | | countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. | | commonPrefix | commonPrefix("parakeet", "parachute") returns "para". | | endsWith | endsWith("rocks", "ks") returns true. | | extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. | | find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) | | findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. | | findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". | | findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. | | findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". | | findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". | | findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". | | minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). | | maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). | | minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. | | maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. | | minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. | | maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. | | minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. | | maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. | | skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. | | startsWith | startsWith("hello, world", "hello") returns true. | | until | Lazily iterates a range until a specific value is found. |

Source

std/algorithm/searching.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
searching
:
(alias template) 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 $(LREF find).

See_Also: $(REF among, std,algorithm,comparison) for checking a value against multiple arguments.

canFind
;
import
(package) std
std
.
(module) std.string

String 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

@seestd.algorithm and std.range for generic range algorithms , std.ascii for functions that work with ASCII strings , std.uni for functions that work with unicode strings@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis, and David L. 'SpottedTiger' Davis
string
:
(alias template) 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", $(REF lineSep, std,uni), $(REF paraSep, std,uni) 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 $(HTTP www.unicode.org/versions/Unicode7.0.0/ch05.pdf, Unicode 7.0).

    Does not allocate memory.

Params: r = array of chars, wchars, or dchars or a slicable range keepTerm = whether delimiter is included or not in the results Returns: range of slices of the input range r

See_Also: $(LREF splitLines) $(REF splitter, std,algorithm) $(REF splitter, std,regex)

lineSplitter
;
if (!
bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safe

Whether an executable is reachable through searchPath ($PATH by default). On Windows the file is ``name.exe, as CreateProcess finds it: $DC=ldc2 names ldc2.exe there.

A local re-implementation rather than sparkles.core_cli.process_utils.isInPath: this module is source-compiled into base's test build, which has no core-cli dependency (the impl-library cycle is impl → base).

inPath
("dub"))
return null;
(alias) object.string = string
string
[]
(local variable) string[] packageRoots
packageRoots
;
foreach (
(parameter) const(string) root
root
;
(parameter) const(string[]) sourceRoots
sourceRoots
)
{ const
(local variable) const(string) packageRoot
packageRoot
=
string sparkles.test_runner.driver.findPackageRoot(string sourceRoot) @safe

The dub package root containing sourceRoot: the nearest ancestor directory (including itself) with a dub.sdl/dub.json, or null.

findPackageRoot
(
(local variable) const(string) root
root
);
if (
(local variable) const(string) packageRoot
packageRoot
!is null && !
(local variable) string[] packageRoots
packageRoots
.
bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
(
(local variable) const(string) packageRoot
packageRoot
))
(local variable) string[] packageRoots
packageRoots
~=
(local variable) const(string) packageRoot
packageRoot
;
}
(alias) object.string = string
string
[]
(local variable) string[] paths
paths
;
foreach (
(local variable) string packageRoot
packageRoot
;
(local variable) string[] packageRoots
packageRoots
)
{ // The unittest configuration first: the tests' modules import what // only it depends on (`sparkles:dql`'s integration schemas import // `sparkles:input`). A package without one falls back to its default. auto
(local variable) std.typecons.Tuple!(int, "status", string, "output") result
result
=
std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safe

Runs command, echoing it when verbose, and returns (status, output). A spawn failure (compiler binary vanished between the detectCompiler check and here, or an unlaunchable absolute path) becomes a failed result instead of a ProcessException stack trace.

run
(["dub", "describe", "--root",
(local variable) string packageRoot
packageRoot
, "--config=unittest",
"--data=import-paths", "--data-list"],
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
);
if (
(local variable) std.typecons.Tuple!(int, "status", string, "output") result
result
.status != 0)
(local variable) std.typecons.Tuple!(int, "status", string, "output") result
result
=
std.typecons.Tuple!(int, "status", string, "output") std.typecons.Tuple!(int, "status", string, "output").opAssign!(std.typecons.Tuple!(int, "status", string, "output"))(std.typecons.Tuple!(int, "status", string, "output") rhs) pure nothrow @nogc ref @safe

Assignment from another Tuple.

@paramrhs The source Tuple to assign from. Each element of the source Tuple must be implicitly assignable to each respective element of the target Tuple.
run
(["dub", "describe", "--root",
(local variable) string packageRoot
packageRoot
,
"--data=import-paths", "--data-list"],
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
);
if (
(local variable) std.typecons.Tuple!(int, "status", string, "output") result
result
.status != 0)
continue; foreach (
(local variable) string line
line
;
(local variable) std.typecons.Tuple!(int, "status", string, "output") result
result
.
(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1
output
.
std.string.LineSplitter!(Flag.no, string) std.string.lineSplitter!(Flag.no, immutable(char))(string r) pure nothrow @nogc @safe

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.

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);
@paramr array of chars, wchars, or dchars or a slicable range@paramkeepTerm whether delimiter is included or not in the results@returnsrange of slices of the input range r@seesplitLines splitter splitter
lineSplitter
.
sparkles.test_runner.driver.dubDescribeImportPaths.FilterResult!(__lambda_L271_C59, LineSplitter!(Flag.no, string)) sparkles.test_runner.driver.dubDescribeImportPaths.filter!(std.string.LineSplitter!(Flag.no, string))(std.string.LineSplitter!(Flag.no, string) range) pure nothrow @nogc @safe

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).

Examples

import std.algorithm.comparison : equal;
import std.math.operations : isClose;
import std.range;

int[] arr = [ 1, 2, 3, 4, 5 ];

// Filter below 3
auto small = filter!(a => a < 3)(arr);
assert(equal(small, [ 1, 2 ]));

// Filter again, but with Uniform Function Call Syntax (UFCS)
auto sum = arr.filter!(a => a < 3);
assert(equal(sum, [ 1, 2 ]));

// In combination with chain() to span multiple ranges
int[] a = [ 3, -2, 400 ];
int[] b = [ 100, -101, 102 ];
auto r = chain(a, b).filter!(a => a > 0);
assert(equal(r, [ 3, 400, 100, 102 ]));

// Mixing convertible types is fair game, too
double[] c = [ 2.5, 3.0 ];
auto r1 = chain(c, a, b).filter!(a => cast(int) a != a);
assert(isClose(r1, [ 2.5 ]));
@parampredicate Function to apply to each element of range@returnsAn input range that contains the filtered elements. If range is at least a forward range, the return value of filter will also be a forward range.@seeFilter (higher-order function), filterBidirectional@paramrange An input range of elements@returnsA range containing only elements x in range for which predicate(x) returns true.
filter
!(l => l.length))
if (!
(local variable) string[] paths
paths
.
bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
(
(local variable) string line
line
))
(local variable) string[] paths
paths
~=
(local variable) string line
line
;
} return
(local variable) string[] paths
paths
;
} /++ The language-semantics switches (`-preview=`, `-revert=`, `-transition=`) that `dub describe` reports for the packages containing the derived source roots. A program compiled outside dub needs them to see the packages' code the way their own builds do (`-preview=dip1000` changes attribute inference). Best-effort: failures yield an empty list. +/ private
(alias) object.string = string
string
[]
string[] sparkles.test_runner.driver.dubDescribeLanguageFlags(in string[] sourceRoots, in sparkles.test_runner.driver.DriverOptions options)

The language-semantics switches (-preview=, -revert=, -transition=) that dub describe reports for the packages containing the derived source roots. A program compiled outside dub needs them to see the packages' code the way their own builds do (-preview=dip1000 changes attribute inference). Best-effort: failures yield an empty list.

dubDescribeLanguageFlags
(in
(alias) object.string = string
string
[]
(parameter) const(string[]) sourceRoots
sourceRoots
, in
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
)
{ import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.searching

This is a submodule of std.algorithm. It contains generic searching algorithms.

Function Name Description
all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive
any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive
balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses.
boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm.
canFind canFind("hello world", "or") returns true.
count Counts all elements or elements matching a predicate, specific element or sub-range.

count([1, 2, 1]) returns 3, count([1, 2, 1], 1) returns 2 and count!"a < 0"([1, -3, 0]) returns 1. | | countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. | | commonPrefix | commonPrefix("parakeet", "parachute") returns "para". | | endsWith | endsWith("rocks", "ks") returns true. | | extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. | | find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) | | findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. | | findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". | | findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. | | findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". | | findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". | | findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". | | minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). | | maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). | | minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. | | maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. | | minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. | | maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. | | minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. | | maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. | | skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. | | startsWith | startsWith("hello, world", "hello") returns true. | | until | Lazily iterates a range until a specific value is found. |

Source

std/algorithm/searching.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
searching
:
(alias template) 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 $(LREF find).

See_Also: $(REF among, std,algorithm,comparison) for checking a value against multiple arguments.

canFind
,
(alias template) 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 $(REF_ALTTEXT input range, isInputRange, std,range,primitives) 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 $(LREF find).

Params:

    pred = Predicate to use in comparing the elements of the haystack and the
        needle(s). Mandatory if no needles are given.

    doesThisStart = The input range to check.

    withOneOfThese = The needles against which the range is to be checked,
        which may be individual elements or input ranges of elements.

    withThis = The single needle to check, which may be either a single element
        or an input range of elements.

Returns:

0 if the needle(s) do not occur at the beginning of the given range; otherwise the position of the matching needle, that is, 1 if the range starts with withOneOfThese[0], 2 if it starts with withOneOfThese[1], and so on.

In the case where doesThisStart starts with multiple of the ranges or elements in withOneOfThese, then the shortest one matches (if there are two which match which are of the same length (e.g. "a" and 'a'), then the left-most of them in the argument list matches).

In the case when no needle parameters are given, return true iff front of doesThisStart fulfils predicate pred.

startsWith
;
import
(package) std
std
.
(module) std.string

String 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

@seestd.algorithm and std.range for generic range algorithms , std.ascii for functions that work with ASCII strings , std.uni for functions that work with unicode strings@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis, and David L. 'SpottedTiger' Davis
string
:
(alias template) 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", $(REF lineSep, std,uni), $(REF paraSep, std,uni) 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 $(HTTP www.unicode.org/versions/Unicode7.0.0/ch05.pdf, Unicode 7.0).

    Does not allocate memory.

Params: r = array of chars, wchars, or dchars or a slicable range keepTerm = whether delimiter is included or not in the results Returns: range of slices of the input range r

See_Also: $(LREF splitLines) $(REF splitter, std,algorithm) $(REF splitter, std,regex)

lineSplitter
;
if (!
bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safe

Whether an executable is reachable through searchPath ($PATH by default). On Windows the file is ``name.exe, as CreateProcess finds it: $DC=ldc2 names ldc2.exe there.

A local re-implementation rather than sparkles.core_cli.process_utils.isInPath: this module is source-compiled into base's test build, which has no core-cli dependency (the impl-library cycle is impl → base).

inPath
("dub"))
return null;
(alias) object.string = string
string
[]
(local variable) string[] packageRoots
packageRoots
;
foreach (
(parameter) const(string) root
root
;
(parameter) const(string[]) sourceRoots
sourceRoots
)
{ const
(local variable) const(string) packageRoot
packageRoot
=
string sparkles.test_runner.driver.findPackageRoot(string sourceRoot) @safe

The dub package root containing sourceRoot: the nearest ancestor directory (including itself) with a dub.sdl/dub.json, or null.

findPackageRoot
(
(local variable) const(string) root
root
);
if (
(local variable) const(string) packageRoot
packageRoot
!is null && !
(local variable) string[] packageRoots
packageRoots
.
bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
(
(local variable) const(string) packageRoot
packageRoot
))
(local variable) string[] packageRoots
packageRoots
~=
(local variable) const(string) packageRoot
packageRoot
;
}
(alias) object.string = string
string
[]
(local variable) string[] flags
flags
;
foreach (
(local variable) string packageRoot
packageRoot
;
(local variable) string[] packageRoots
packageRoots
)
{ const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
=
std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safe

Runs command, echoing it when verbose, and returns (status, output). A spawn failure (compiler binary vanished between the detectCompiler check and here, or an unlaunchable absolute path) becomes a failed result instead of a ProcessException stack trace.

run
(["dub", "describe", "--root",
(local variable) string packageRoot
packageRoot
,
"--data=dflags", "--data-list"],
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
);
if (
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
.status != 0)
continue; foreach (
(local variable) string line
line
;
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
.
(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1
output
.
std.string.LineSplitter!(Flag.no, string) std.string.lineSplitter!(Flag.no, immutable(char))(string r) pure nothrow @nogc @safe

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.

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);
@paramr array of chars, wchars, or dchars or a slicable range@paramkeepTerm whether delimiter is included or not in the results@returnsrange of slices of the input range r@seesplitLines splitter splitter
lineSplitter
)
if ((
(local variable) string line
line
.
bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safe

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.

@parampred Predicate to use in comparing the elements of the haystack and the needle(s). Mandatory if no needles are given.@paramdoesThisStart The input range to check.@paramwithOneOfThese The needles against which the range is to be checked, which may be individual elements or input ranges of elements.@paramwithThis The single needle to check, which may be either a single element or an input range of elements.@returns

0 if the needle(s) do not occur at the beginning of the given range; otherwise the position of the matching needle, that is, 1 if the range starts with withOneOfThese[0], 2 if it starts with withOneOfThese[1], and so on.

In the case where doesThisStart starts with multiple of the ranges or elements in withOneOfThese, then the shortest one matches (if there are two which match which are of the same length (e.g. "a" and 'a'), then the left-most of them in the argument list matches).

In the case when no needle parameters are given, return true iff front of doesThisStart fulfils predicate pred.

startsWith
("-preview=") ||
(local variable) string line
line
.
bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safe

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.

@parampred Predicate to use in comparing the elements of the haystack and the needle(s). Mandatory if no needles are given.@paramdoesThisStart The input range to check.@paramwithOneOfThese The needles against which the range is to be checked, which may be individual elements or input ranges of elements.@paramwithThis The single needle to check, which may be either a single element or an input range of elements.@returns

0 if the needle(s) do not occur at the beginning of the given range; otherwise the position of the matching needle, that is, 1 if the range starts with withOneOfThese[0], 2 if it starts with withOneOfThese[1], and so on.

In the case where doesThisStart starts with multiple of the ranges or elements in withOneOfThese, then the shortest one matches (if there are two which match which are of the same length (e.g. "a" and 'a'), then the left-most of them in the argument list matches).

In the case when no needle parameters are given, return true iff front of doesThisStart fulfils predicate pred.

startsWith
("-revert=")
||
(local variable) string line
line
.
bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safe

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.

@parampred Predicate to use in comparing the elements of the haystack and the needle(s). Mandatory if no needles are given.@paramdoesThisStart The input range to check.@paramwithOneOfThese The needles against which the range is to be checked, which may be individual elements or input ranges of elements.@paramwithThis The single needle to check, which may be either a single element or an input range of elements.@returns

0 if the needle(s) do not occur at the beginning of the given range; otherwise the position of the matching needle, that is, 1 if the range starts with withOneOfThese[0], 2 if it starts with withOneOfThese[1], and so on.

In the case where doesThisStart starts with multiple of the ranges or elements in withOneOfThese, then the shortest one matches (if there are two which match which are of the same length (e.g. "a" and 'a'), then the left-most of them in the argument list matches).

In the case when no needle parameters are given, return true iff front of doesThisStart fulfils predicate pred.

startsWith
("-transition=")) && !
(local variable) string[] flags
flags
.
bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
(
(local variable) string line
line
))
(local variable) string[] flags
flags
~=
(local variable) string line
line
.
string object.idup!(immutable(char))(string a) pure nothrow @property @safe

Provide the .idup array property, which creates an immutable duplicate.

idup
;
} return
(local variable) string[] flags
flags
;
} /// Slices the bodies of `tests` out of their source files. Files are read /// relative to the working directory — the same place the compiler resolved /// them from when the test build was created.
(struct) sparkles.test_runner.extract.ExtractedTest

One extracted test, ready to be emitted into a generated program.

ExtractedTest
[]
sparkles.test_runner.extract.ExtractedTest[] sparkles.test_runner.driver.extractTests(in sparkles.test_runner.model.Test[] tests)

Slices the bodies of tests out of their source files. Files are read relative to the working directory — the same place the compiler resolved them from when the test build was created.

extractTests
(in
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
[]
(parameter) const(sparkles.test_runner.model.Test[]) tests
tests
)
{ import
(package) std
std
.
(module) std.conv

A 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

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Shin Fujishiro, Adam D. Ruppe, Kenji Hara
conv
:
(alias template) text = std.conv.text(T...)(T args) if (T.length > 0)

Convenience functions for converting one or more arguments of any type into _text (the three character widths).

text
;
import
(package) std
std
.
(module) std.file

Utilities 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

@copyrightCopyright The D Language Foundation 2007 - 2011.@seeThe official tutorial for an introduction to working with files in D, module std.stdio for opening files and manipulating them via handles, and module std.path for manipulating path strings.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis
file
:
(alias template) readText = std.file.readText(S = string, R)(auto ref R name) if (isSomeString!S && (isSomeFiniteCharInputRange!R || is(StringTypeOf!R)))

Reads and validates (using $(REF validate, std, utf)) 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.

    Params:
        S = the string type of the file
        name = string or range of characters representing the file _name

    Returns: Array of characters read.

    Throws: $(LREF FileException) if there is an error reading the file,
            $(REF UTFException, std, utf) on UTF decoding error.

    See_Also: $(REF read, std,file) for reading a binary file.
readText
;
(alias) object.string = string
string
[
(alias) object.string = string
string
]
(local variable) string[string] sources
sources
;
(struct) sparkles.test_runner.extract.ExtractedTest

One extracted test, ready to be emitted into a generated program.

ExtractedTest
[]
(local variable) sparkles.test_runner.extract.ExtractedTest[] extracted
extracted
;
foreach (ref
(parameter) const(sparkles.test_runner.model.Test) test
test
;
(parameter) const(sparkles.test_runner.model.Test[]) tests
tests
)
{ auto
(local variable) string* source
source
=
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) string sparkles.test_runner.model.TestLocation.file
file
in
(local variable) string[string] sources
sources
;
if (
(local variable) string* source
source
is null)
{
string* core.internal.newaa._d_aaGetY!(string, string, string[string], string, string, const(string))(ref scope string[string] aa, ref const(string) key, out bool found) pure nothrow @safe

Lookup key in aa. Called only from implementation of (aa[`key`]) expressions when value is mutable.

@paramaa associative array@paramkey reference to the key value@paramfound returns whether the key was found or a new entry was added@returnsif key was in the aa, a mutable pointer to the existing value. If key was not in the aa, a mutable pointer to newly inserted value which is set to zero
sources
[
string* core.internal.newaa._d_aaGetY!(string, string, string[string], string, string, const(string))(ref scope string[string] aa, ref const(string) key, out bool found) pure nothrow @safe

Lookup key in aa. Called only from implementation of (aa[`key`]) expressions when value is mutable.

@paramaa associative array@paramkey reference to the key value@paramfound returns whether the key was found or a new entry was added@returnsif key was in the aa, a mutable pointer to the existing value. If key was not in the aa, a mutable pointer to newly inserted value which is set to zero
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) string sparkles.test_runner.model.TestLocation.file
file
] =
string std.file.readText!(string, const(string))(ref const(string) name) @safe

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.

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");
@paramS the string type of the file@paramname string or range of characters representing the file name@returnsArray of characters read.@throwsFileException if there is an error reading the file, UTFException on UTF decoding error.@seeread for reading a binary file.
readText
(
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) string sparkles.test_runner.model.TestLocation.file
file
);
(local variable) string* source
source
=
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) string sparkles.test_runner.model.TestLocation.file
file
in
(local variable) string[string] sources
sources
;
} const
(local variable) const(string) body_
body_
=
string sparkles.test_runner.extract.extractUnittestBody(string source, ulong line) pure @safe

Extracts the body of the unittest block declared at line (its __traits(getLocation) line): the text between the block's braces, without the braces themselves. Returns null when no block is found.

extractUnittestBody
(*
(local variable) string* source
source
,
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) ulong sparkles.test_runner.model.TestLocation.line
line
);
if (
(local variable) const(string) body_
body_
is null)
throw new
(class) object.Exception

The base class of all errors that are safe to catch and handle.

In principle, only thrown objects derived from this class are safe to catch inside a catch block. Thrown objects not derived from Exception represent runtime errors that should not be caught, as certain runtime guarantees may not hold, making it unsafe to continue program execution.

Examples

bool gotCaught;
try
{
    throw new Exception("msg");
}
catch (Exception e)
{
    gotCaught = true;
    assert(e.msg == "msg");
}
assert(gotCaught);
Exception
(
string std.conv.text!(string, string, string, const(ulong), string, string, string)(string __param_0, string __param_1, string __param_2, const(ulong) __param_3, string __param_4, string __param_5, string __param_6) pure nothrow @safe

Convenience functions for converting one or more arguments of any type into text (the three character widths).

text
("could not extract the unittest at ",
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) string sparkles.test_runner.model.TestLocation.file
file
, ":",
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) ulong sparkles.test_runner.model.TestLocation.line
line
, " (",
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) string sparkles.test_runner.model.Test.name

Display name: the first string UDA, or the symbol identifier.

name
, ")"));
(local variable) sparkles.test_runner.extract.ExtractedTest[] extracted
extracted
~=
(struct) sparkles.test_runner.extract.ExtractedTest

One extracted test, ready to be emitted into a generated program.

ExtractedTest
(
name:
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) string sparkles.test_runner.model.Test.name

Display name: the first string UDA, or the symbol identifier.

name
,
// Strip aggregate qualifiers so a test nested in a struct/class emits // `import pkg.mod;`, not `import pkg.mod.Aggregate;` (mirrors the @ctfe // path, which also uses probeModuleName). moduleName:
string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safe

The actual module containing test: ``test.moduleName with aggregate qualifiers stripped (a nested test's fullName includes its aggregate), found by peeling trailing components until the name matches the file path.

probeModuleName
(
(local variable) const(sparkles.test_runner.model.Test) test
test
),
file:
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) string sparkles.test_runner.model.TestLocation.file
file
,
line:
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) ulong sparkles.test_runner.model.TestLocation.line
line
,
functionAttributes:
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestTraits sparkles.test_runner.model.Test.traits
traits
.
(field) string sparkles.test_runner.model.TestTraits.functionAttributes

The test's safety/purity attributes ("@safe pure nothrow @nogc"), re-applied to extracted @betterC/@wasm test functions.

functionAttributes
,
body_:
(local variable) const(string) body_
body_
,
); } return
(local variable) sparkles.test_runner.extract.ExtractedTest[] extracted
extracted
;
} /// A fresh scratch directory for the generated program: beneath `own`, the /// run's `DriverOptions.probeDir`, when it names one, so clients that run /// several modes at once in one process keep them apart; else beneath /// `setProbeDir`'s. private
(alias) object.string = string
string
string sparkles.test_runner.driver.makeWorkDir(string flavor, string own = null)

A fresh scratch directory for the generated program: beneath own, the run's DriverOptions.probeDir, when it names one, so clients that run several modes at once in one process keep them apart; else beneath setProbeDir's.

makeWorkDir
(
(alias) object.string = string
string
(parameter) string flavor
flavor
,
(alias) object.string = string
string
(parameter) string own
own
= null)
{ import
(package) std
std
.
(module) std.conv

A 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

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Shin Fujishiro, Adam D. Ruppe, Kenji Hara
conv
:
(alias template) text = std.conv.text(T...)(T args) if (T.length > 0)

Convenience functions for converting one or more arguments of any type into _text (the three character widths).

text
;
import
(package) std
std
.
(module) std.file

Utilities 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

@copyrightCopyright The D Language Foundation 2007 - 2011.@seeThe official tutorial for an introduction to working with files in D, module std.stdio for opening files and manipulating them via handles, and module std.path for manipulating path strings.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis
file
:
(alias) mkdirRecurse = void std.file.mkdirRecurse(scope const(char)[] pathname) @safe

Make directory and all parent directories as needed.

Does nothing if the directory specified by pathname already exists.

Params: pathname = the full path of the directory to create

Throws: $(LREF FileException) on error.

mkdirRecurse
,
(alias) tempDir = string std.file.tempDir() @trusted

Returns the path to a directory for temporary files. On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist: $(OL $(LI The directory given by the TMPDIR environment variable.) $(LI The directory given by the `TEMP` environment variable.) $(LI The directory given by the TMP environment variable.) $(LI `/tmp/`) $(LI /var/tmp/) $(LI /usr/tmp/) )

On all platforms, tempDir returns the current working directory on failure.

The return value of the function is cached, so the procedures described below will only be performed the first time the function is called. All subsequent runs will return the same string, regardless of whether environment variables and directory structures have changed in the meantime.

The POSIX tempDir algorithm is inspired by Python's $(LINK2 http://docs.python.org/library/tempfile.html#tempfile.tempdir, tempfile.tempdir).

Returns: On Windows, this function returns the result of calling the Windows API function $(LINK2 http://msdn.microsoft.com/en-us/library/windows/desktop/aa364992.aspx, GetTempPath).

    On POSIX platforms, it searches through the following list of directories
    and returns the first one which is found to exist:
    $(OL
        $(LI The directory given by the `TMPDIR` environment variable.)
        $(LI The directory given by the `TEMP` environment variable.)
        $(LI The directory given by the `TMP` environment variable.)
        $(LI `/tmp`)
        $(LI `/var/tmp`)
        $(LI `/usr/tmp`)
    )

    On all platforms, `tempDir` returns `"."` on failure, representing
    the current working directory.
tempDir
;
import
(package) std
std
.
(module) std.path

This module is used to manipulate path strings.

All functions, with the exception of expandTilde (and in some cases absolutePath and relativePath), are pure string manipulation functions; they don't depend on any state outside the program, nor do they perform any actual file system actions. This has the consequence that the module does not make any distinction between a path that points to a directory and a path that points to a file, and it does not know whether or not the object pointed to by the path actually exists in the file system. To differentiate between these cases, use isDir and exists.

Note that on Windows, both the backslash (\) and the slash (/) are in principle valid directory separators. This module treats them both on equal footing, but in cases where a new separator is added, a backslash will be used. Furthermore, the buildNormalizedPath function will replace all slashes with backslashes on that platform.

In general, the functions in this module assume that the input paths are well-formed. (That is, they should not contain invalid characters, they should follow the file system's path format, etc.) The result of calling a function on an ill-formed path is undefined. When there is a chance that a path or a file name is invalid (for instance, when it has been input by the user), it may sometimes be desirable to use the isValidFilename and isValidPath functions to check this.

Most functions do not perform any memory allocations, and if a string is returned, it is usually a slice of an input string. If a function allocates, this is explicitly mentioned in the documentation.

Category Functions
Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde
Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive
Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath
Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension
Other filenameCharCmp filenameCmp globMatch CaseSensitive

Source

std/path.d

@authorsLars Tandle Kyllingstad, Walter Bright, Grzegorz Adam Hankiewicz, Thomas Khne, Andrei Alexandrescu@copyrightCopyright (c) 2000-2014, the authors. All rights reserved.@licenseBoost License 1.0
path
:
(alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))

Combines one or more path segments.

    This function takes a set of path segments, given as an input
    range of string elements or as a set of string arguments,
    and concatenates them with each other.  Directory separators
    are inserted between segments if necessary.  If any of the
    path segments are absolute (as defined by $(LREF isAbsolute)), the
    preceding segments will be dropped.

    On Windows, if one of the path segments are rooted, but not absolute
    (e.g. $(D `\foo`)), all preceding path segments down to the previous
    root will be dropped.  (See below for an example.)

    This function always allocates memory to hold the resulting path.
    The variadic overload is guaranteed to only perform a single
    allocation, as is the range version if `paths` is a forward
    range.

    Params:
        segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
        of segments to assemble the path from.
    Returns: The assembled path.
buildPath
;
import
(package) std
std
.
(module) std.process

Functions 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.

@authorsLars Tandle Kyllingstad, Steven Schveighoffer, Vladimir Panteleev@copyrightCopyright (c) 2013, the authors. All rights reserved.@licenseBoost License 1.0.
process
:
(alias) thisProcessID = int std.process.thisProcessID() nothrow @nogc @property @trusted

Returns the process ID of the current process, which is guaranteed to be unique on the system.

Example:

writefln("Current process ID: %d", thisProcessID); ---

thisProcessID
;
const
(local variable) const(string) root
root
=
(parameter) string own
own
.
(field) ulong string.length
length
?
(parameter) string own
own
:
(__gshared global) string sparkles.test_runner.driver.probeRoot

The probe directory of the current run (DriverOptions.probeDir).

probeRoot
;
const
(local variable) const(string) dir
dir
=
(local variable) const(string) root
root
.
(field) ulong const(string).length
length
?
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) const(string) root
root
,
(parameter) string flavor
flavor
) :
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
string std.file.tempDir() @trusted

Returns the path to a directory for temporary files. On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp/

  5. /var/tmp/

  6. /usr/tmp/

On all platforms, tempDir returns the current working directory on failure.

The return value of the function is cached, so the procedures described below will only be performed the first time the function is called. All subsequent runs will return the same string, regardless of whether environment variables and directory structures have changed in the meantime.

The POSIX tempDir algorithm is inspired by Python's tempfile.tempdir.

Examples

import std.ascii : letters;
import std.conv : to;
import std.path : buildPath;
import std.random : randomSample;
import std.utf : byCodeUnit;

// random id with 20 letters
auto id = letters.byCodeUnit.randomSample(20).to!string;
auto myFile = tempDir.buildPath(id ~ "my_tmp_file");
scope(exit) myFile.remove;

myFile.write("hello");
assert(myFile.readText == "hello");
@returns

On Windows, this function returns the result of calling the Windows API function GetTempPath.

On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp

  5. /var/tmp

  6. /usr/tmp

On all platforms, tempDir returns "." on failure, representing the current working directory.

tempDir
,
string std.conv.text!(string, string, string, int)(string __param_0, string __param_1, string __param_2, int __param_3) pure nothrow @safe

Convenience functions for converting one or more arguments of any type into text (the three character widths).

text
("sparkles-test-runner-",
(parameter) string flavor
flavor
, "-",
int std.process.thisProcessID() nothrow @nogc @property @trusted

Returns the process ID of the current process, which is guaranteed to be unique on the system.

Example

writefln("Current process ID: %d", thisProcessID);
thisProcessID
));
void std.file.mkdirRecurse(scope const(char)[] pathname) @safe

Make 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);
@parampathname the full path of the directory to create@throwsFileException on error.
mkdirRecurse
(
(local variable) const(string) dir
dir
);
return
(local variable) const(string) dir
dir
;
} /// Runs `command`, echoing it when `verbose`, and returns (status, output). /// A spawn failure (compiler binary vanished between the `detectCompiler` /// check and here, or an unlaunchable absolute path) becomes a failed result /// instead of a `ProcessException` stack trace. private auto
std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safe

Runs command, echoing it when verbose, and returns (status, output). A spawn failure (compiler binary vanished between the detectCompiler check and here, or an unlaunchable absolute path) becomes a failed result instead of a ProcessException stack trace.

run
(const(
(alias) object.string = string
string
)[]
(parameter) const(string)[] command
command
, in
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
)
{ import
(package) std
std
.
(module) std.process

Functions 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.

@authorsLars Tandle Kyllingstad, Steven Schveighoffer, Vladimir Panteleev@copyrightCopyright (c) 2013, the authors. All rights reserved.@licenseBoost License 1.0.
process
:
(alias) 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) @safe

Executes the given program or shell command and returns its exit code and output.

execute and executeShell start a new process using $(LREF spawnProcess) and $(LREF 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.

Params: args = An array which contains the program name as the zeroth element and any command-line arguments in the following elements. (See $(LREF spawnProcess) for details.) program = The program name, $(I without) command-line arguments. (See $(LREF spawnProcess) for details.) command = A shell command which is passed verbatim to the command interpreter. (See $(LREF spawnShell) for details.) env = Additional environment variables for the child process. (See $(LREF spawnProcess) for details.) config = Flags that control process creation. See $(LREF Config) for an overview of available flags, and note that the retainStd... flags have no effect in this function. maxOutput = The maximum number of bytes of output that should be captured. workDir = The working directory for the new process. By default the child process inherits the parent's working directory. shellPath = The path to the shell to use to run the specified program. By default this is $(LREF nativeShell).

Returns: An $(D std.typecons.Tuple!(int, "status", string, "output")).

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 $(LREF wait) for details.)

Throws: $(LREF ProcessException) on failure to start the process.$(BR) $(REF StdioException, std,stdio) on failure to capture output.

execute
,
(class) std.process.ProcessException

An exception that signals a problem with starting or waiting for a process.

ProcessException
;
if (
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) bool sparkles.test_runner.driver.DriverOptions.verbose

echo the commands that are run

verbose
)
{ import
(package) std
std
.
(module) std.string

String 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

@seestd.algorithm and std.range for generic range algorithms , std.ascii for functions that work with ASCII strings , std.uni for functions that work with unicode strings@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis, and David L. 'SpottedTiger' Davis
string
:
(alias template) 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.

Params: ror = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) of input ranges sep = An input range, or a single element, to join the ranges on

Returns: An array of elements

See_Also: For a lazy version, see $(REF joiner, std,algorithm,iteration)

join
;
void sparkles.test_runner.driver.warn!(string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2) @safe

args and a line feed, to report's diagnostics.

warn
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "$ ",
(parameter) const(string)[] command
command
.
string std.array.join!(const(string)[], string)(const(string)[] ror, string sep) pure nothrow @safe

Eagerly concatenates all of the ranges in ror together (with the GC) into one array using sep as the separator if present.

@paramror An input range of input ranges@paramsep An input range, or a single element, to join the ranges on@returnsAn array of elements@seeFor a lazy version, see joiner
join
(" "));
} try return
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) @safe

Executes 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.)

@paramargs An array which contains the program name as the zeroth element and any command-line arguments in the following elements. (See spawnProcess for details.)@paramprogram The program name, without command-line arguments. (See spawnProcess for details.)@paramcommand A shell command which is passed verbatim to the command interpreter. (See spawnShell for details.)@paramenv Additional environment variables for the child process. (See spawnProcess for details.)@paramconfig Flags that control process creation. See Config for an overview of available flags, and note that the retainStd... flags have no effect in this function.@parammaxOutput The maximum number of bytes of output that should be captured.@paramworkDir The working directory for the new process. By default the child process inherits the parent's working directory.@paramshellPath The path to the shell to use to run the specified program. By default this is nativeShell.@returnsAn std.typecons.Tuple!(int, "status", string, "output").@throws

ProcessException on failure to start the process.

StdioException on failure to capture output.

execute
(
(parameter) const(string)[] command
command
);
catch (
(class) std.process.ProcessException

An exception that signals a problem with starting or waiting for a process.

ProcessException
(local variable) std.process.ProcessException e
e
)
return typeof(execute(command))(-1, "failed to launch '" ~
(parameter) const(string)[] command
command
[0] ~ "': " ~
(local variable) std.process.ProcessException e
e
.
(field) string object.Throwable.msg

A message describing the error.

msg
);
} /// The extra `-i=<pattern>` flags requested with `--include-import` (e.g. /// `--include-import=std.ascii` to compile a std module in when an extracted /// test needs one of its non-template functions). private
(alias) object.string = string
string
[]
string[] sparkles.test_runner.driver.includeFlags(in sparkles.test_runner.driver.DriverOptions options) pure @safe

The extra -i=<pattern> flags requested with --include-import (e.g. --include-import=std.ascii to compile a std module in when an extracted test needs one of its non-template functions).

includeFlags
(in
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
) @safe pure
{ import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.iteration

This is a submodule of std.algorithm. It contains generic iteration algorithms.

Function Name Description
cache Eagerly evaluates and caches another range's front.
lazyCache Lazily evaluates and caches another range's front, unlike cache.
cacheBidirectional As above, but also provides back and popBack.
chunkBy chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]]) returns a range containing 3 subranges: the first with just [1, 1]; the second with the elements [1, 2] and [2, 2]; and the third with just [2, 1].
cumulativeFold cumulativeFold!((a, b) => a + b)([1, 2, 3, 4]) returns a lazily-evaluated range containing the successive reduced values 1, 3, 6, 10.
each each!writeln([1, 2, 3]) eagerly prints the numbers 1, 2 and 3 on their own lines.
filter filter!(a => a > 0)([1, -1, 2, 0, -3]) iterates over elements 1 and 2.
filterBidirectional Similar to filter, but also provides back and popBack at a small increase in cost.
fold fold!((a, b) => a + b)([1, 2, 3, 4]) returns 10.
group group([5, 2, 2, 3, 3]) returns a range containing the tuples tuple(5, 1), tuple(2, 2), and tuple(3, 2).
joiner joiner(["hello", "world!"], "; ") returns a range that iterates over the characters "hello; world!". No new string is created - the existing inputs are iterated.
map map!(a => a * 2)([1, 2, 3]) lazily returns a range with the numbers 2, 4, 6.
mean Colloquially known as the average, mean([1, 2, 3]) returns 2.
permutations Lazily computes all permutations using Heap's algorithm.
reduce reduce!((a, b) => a + b)([1, 2, 3, 4]) returns 10. This is the old implementation of fold.
splitWhen Lazily splits a range by comparing adjacent elements.
splitter Lazily splits a range by a separator, element predicate or whitespace.
substitute [1, 2].substitute(1, 0.1) returns [0.1, 2].
sum Same as fold, but specialized for accurate summation.
uniq Iterates over the unique elements in a range, which is assumed sorted.

Source

std/algorithm/iteration.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
iteration
:
(alias template) map = std.algorithm.iteration.map(fun...) if (fun.length >= 1)

Implements the homonym function (also known as transform) present in many languages of functional flavor. The call map!(fun)(range) returns a range of which elements are obtained by applying fun(a) left to right for all elements a in range. The original ranges are not changed. Evaluation is done lazily.

Params: fun = one or more transformation functions

See_Also: $(HTTP en.wikipedia.org/wiki/Map_(higher-order_function), Map (higher-order function))

map
;
import
(package) std
std
.
(module) std.array

Functions and types that manipulate built-in arrays and associative arrays.

This module provides all kinds of functions to create, manipulate or convert arrays:

Function Name Description

| array | Returns a copy of the input in a newly allocated dynamic array. | | appender | Returns a new Appender or RefAppender initialized with a given array. | | assocArray | Returns a newly allocated associative array from a range/ranges of keys and values. | | byPair | Construct a range iterating over an associative array by key/value tuples. | | insertInPlace | Inserts into an existing array at a given position. | | join | Concatenates a range of ranges into one array. | | minimallyInitializedArray | Returns a new array of type T. | | replace | Returns a new array with all occurrences of a certain subrange replaced. | | replaceFirst | Returns a new array with the first occurrence of a certain subrange replaced. | | replaceInPlace | Replaces all occurrences of a certain subrange and puts the result into a given array. | | replaceInto | Replaces all occurrences of a certain subrange and puts the result into an output range. | | replaceLast | Returns a new array with the last occurrence of a certain subrange replaced. | | replaceSlice | Returns a new array with a given slice replaced. | | replicate | Creates a new array out of several copies of an input array or range. | | sameHead | Checks if the initial segments of two arrays refer to the same place in memory. | | sameTail | Checks if the final segments of two arrays refer to the same place in memory. | | split | Eagerly split a range or string into an array. | | staticArray | Creates a new static array from given data. | | uninitializedArray | Returns a new array of type T without initializing its elements. |

Source

std/array.d

@copyrightCopyright Andrei Alexandrescu 2008- and Jonathan M Davis 2011-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu and Jonathan M Davis
array
:
(alias template) 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.

Params: r = range (or aggregate with opApply function) whose elements are copied into the allocated array Returns: allocated and initialized array

array
;
return
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string[] sparkles.test_runner.driver.DriverOptions.includeImports

extra -i=<pattern> module-inclusion patterns

includeImports
.
sparkles.test_runner.driver.includeFlags.MapResult!(__lambda_L402_C40, const(string)[]) sparkles.test_runner.driver.includeFlags.map!(const(string)[])(const(string)[] r) pure nothrow @nogc @safe

Implements the homonym function (also known as transform) present in many languages of functional flavor. The call ``map!(fun)(range) returns a range of which elements are obtained by applying fun(a) left to right for all elements a in range. The original ranges are not changed. Evaluation is done lazily.

Examples

import std.algorithm.comparison : equal;
import std.range : chain, only;
auto squares =
    chain(only(1, 2, 3, 4), only(5, 6)).map!(a => a * a);
assert(equal(squares, only(1, 4, 9, 16, 25, 36)));

Multiple functions can be passed to map. In that case, the element type of map is a tuple containing one element for each function.

auto sums = [2, 4, 6, 8];
auto products = [1, 4, 9, 16];

size_t i = 0;
foreach (result; [ 1, 2, 3, 4 ].map!("a + a", "a * a"))
{
    assert(result[0] == sums[i]);
    assert(result[1] == products[i]);
    ++i;
}

You may alias map with some function(s) to a symbol and use it separately:

import std.algorithm.comparison : equal;
import std.conv : to;

alias stringize = map!(to!string);
assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ]));
@paramfun one or more transformation functions@seeMap (higher-order function)@paramr an input range@returnsA range with each fun applied to all the elements. If there is more than one fun, the element type will be Tuple containing one element for each fun.
map
!(p => "-i=" ~ p).
string[] std.array.array!(sparkles.test_runner.driver.includeFlags.MapResult!(__lambda_L402_C40, const(string)[]))(sparkles.test_runner.driver.includeFlags.MapResult!(__lambda_L402_C40, const(string)[]) r) pure @safe

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.

@paramr range (or aggregate with opApply function) whose elements are copied into the allocated array@returnsallocated and initialized array
array
;
} /// The `-i=<module>` flags derived from the tests being extracted: one per /// distinct module that owns a test, minus the ones whose tests all opted out /// with `selfContained`. /// /// Compiling the owning module in is the useful default. Without it an /// extracted program links against nothing but templates, so a `@betterC` /// test that calls any ordinary function of the very module it lives in — /// the common case — fails at link time with an undefined reference, which /// made the marker attribute effectively decorative for such tests. /// /// The opt-out is per test (`@betterC(selfContained: true)`) rather than /// global because it is a property of the test: a module that is not itself /// `-betterC`-codegen-clean can still host a template-only test, and that /// self-containment is exactly what such a test asserts. `--no-auto-include` /// disables the whole derivation for a one-off run.
(alias) object.string = string
string
[]
string[] sparkles.test_runner.driver.autoIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safe

The -i=<module> flags derived from the tests being extracted: one per distinct module that owns a test, minus the ones whose tests all opted out with selfContained.

Compiling the owning module in is the useful default. Without it an extracted program links against nothing but templates, so a @betterC test that calls any ordinary function of the very module it lives in — the common case — fails at link time with an undefined reference, which made the marker attribute effectively decorative for such tests.

The opt-out is per test (@betterC(selfContained: true)) rather than global because it is a property of the test: a module that is not itself -betterC-codegen-clean can still host a template-only test, and that self-containment is exactly what such a test asserts. --no-auto-include disables the whole derivation for a one-off run.

autoIncludeFlags
(in
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
[]
(parameter) const(sparkles.test_runner.model.Test[]) extracted
extracted
, in
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
) @safe pure
{ import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.searching

This is a submodule of std.algorithm. It contains generic searching algorithms.

Function Name Description
all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive
any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive
balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses.
boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm.
canFind canFind("hello world", "or") returns true.
count Counts all elements or elements matching a predicate, specific element or sub-range.

count([1, 2, 1]) returns 3, count([1, 2, 1], 1) returns 2 and count!"a < 0"([1, -3, 0]) returns 1. | | countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. | | commonPrefix | commonPrefix("parakeet", "parachute") returns "para". | | endsWith | endsWith("rocks", "ks") returns true. | | extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. | | find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) | | findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. | | findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". | | findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. | | findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". | | findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". | | findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". | | minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). | | maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). | | minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. | | maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. | | minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. | | maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. | | minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. | | maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. | | skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. | | startsWith | startsWith("hello, world", "hello") returns true. | | until | Lazily iterates a range until a specific value is found. |

Source

std/algorithm/searching.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
searching
:
(alias template) 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 $(LREF find).

See_Also: $(REF among, std,algorithm,comparison) for checking a value against multiple arguments.

canFind
;
if (
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) bool sparkles.test_runner.driver.DriverOptions.noAutoInclude

don't compile the extracted tests' own modules in

noAutoInclude
)
return null;
(alias) object.string = string
string
[]
(local variable) string[] flags
flags
;
foreach (ref
(parameter) const(sparkles.test_runner.model.Test) test
test
;
(parameter) const(sparkles.test_runner.model.Test[]) extracted
extracted
)
{ if (
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestTraits sparkles.test_runner.model.Test.traits
traits
.
(field) bool sparkles.test_runner.model.TestTraits.selfContained

The test asserts it needs nothing linked from its own module, so the extracted --better-c / --wasm program leaves that module out (see betterC.selfContained``). One flag covers both modes: a test marked self-contained under either is self-contained under both.

selfContained
)
continue; const
(local variable) const(string) flag
flag
= "-i=" ~
(local variable) const(sparkles.test_runner.model.Test) test
test
.
string sparkles.test_runner.model.Test.moduleName() const pure nothrow @nogc return scope @safe

The module part of fullName (everything before the last .).

moduleName
;
if (!
(local variable) string[] flags
flags
.
bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
(
(local variable) const(string) flag
flag
))
(local variable) string[] flags
flags
~=
(local variable) const(string) flag
flag
;
} return
(local variable) string[] flags
flags
;
} @("driver.autoIncludeFlags.oneFlagPerOwningModule") @safe pure unittest { static
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
(
(alias) object.string = string
string
(parameter) string fullName
fullName
, bool
(parameter) bool selfContained
selfContained
= false)
{
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
(local variable) sparkles.test_runner.model.Test t
t
;
(local variable) sparkles.test_runner.model.Test t
t
.
(field) string sparkles.test_runner.model.Test.fullName

Fully qualified name of the unittest symbol, e.g. sparkles.base.buffer.__unittest_L42_C1.

fullName
=
(parameter) string fullName
fullName
;
(local variable) sparkles.test_runner.model.Test t
t
.
(field) sparkles.test_runner.model.TestTraits sparkles.test_runner.model.Test.traits
traits
.
(field) bool sparkles.test_runner.model.TestTraits.selfContained

The test asserts it needs nothing linked from its own module, so the extracted --better-c / --wasm program leaves that module out (see betterC.selfContained``). One flag covers both modes: a test marked self-contained under either is self-contained under both.

selfContained
=
(parameter) bool selfContained
selfContained
;
return
(local variable) sparkles.test_runner.model.Test t
t
;
} // One flag per distinct module, in first-seen order, deduplicated. assert(
string[] sparkles.test_runner.driver.autoIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safe

The -i=<module> flags derived from the tests being extracted: one per distinct module that owns a test, minus the ones whose tests all opted out with selfContained.

Compiling the owning module in is the useful default. Without it an extracted program links against nothing but templates, so a @betterC test that calls any ordinary function of the very module it lives in — the common case — fails at link time with an undefined reference, which made the marker attribute effectively decorative for such tests.

The opt-out is per test (@betterC(selfContained: true)) rather than global because it is a property of the test: a module that is not itself -betterC-codegen-clean can still host a template-only test, and that self-containment is exactly what such a test asserts. --no-auto-include disables the whole derivation for a one-off run.

autoIncludeFlags
([
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
("pkg.a.__unittest_L1_C1"),
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
("pkg.b.__unittest_L2_C1"),
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
("pkg.a.__unittest_L3_C1"),
],
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
.
(constant) sparkles.test_runner.driver.DriverOptions sparkles.test_runner.driver.DriverOptions.init = DriverOptions(null, null, null, false, false, false, ModeReport(null, null), null, null, null, null, false, null)
init
) == ["-i=pkg.a", "-i=pkg.b"]);
// A self-contained test contributes nothing — that is what lets a module // which cannot compile under -betterC still host a template-only test. assert(
string[] sparkles.test_runner.driver.autoIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safe

The -i=<module> flags derived from the tests being extracted: one per distinct module that owns a test, minus the ones whose tests all opted out with selfContained.

Compiling the owning module in is the useful default. Without it an extracted program links against nothing but templates, so a @betterC test that calls any ordinary function of the very module it lives in — the common case — fails at link time with an undefined reference, which made the marker attribute effectively decorative for such tests.

The opt-out is per test (@betterC(selfContained: true)) rather than global because it is a property of the test: a module that is not itself -betterC-codegen-clean can still host a template-only test, and that self-containment is exactly what such a test asserts. --no-auto-include disables the whole derivation for a one-off run.

autoIncludeFlags
([
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
("pkg.a.__unittest_L1_C1", true),
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
("pkg.b.__unittest_L2_C1"),
],
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
.
(constant) sparkles.test_runner.driver.DriverOptions sparkles.test_runner.driver.DriverOptions.init = DriverOptions(null, null, null, false, false, false, ModeReport(null, null), null, null, null, null, false, null)
init
) == ["-i=pkg.b"]);
// ... but only when *every* test in that module opted out. assert(
string[] sparkles.test_runner.driver.autoIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safe

The -i=<module> flags derived from the tests being extracted: one per distinct module that owns a test, minus the ones whose tests all opted out with selfContained.

Compiling the owning module in is the useful default. Without it an extracted program links against nothing but templates, so a @betterC test that calls any ordinary function of the very module it lives in — the common case — fails at link time with an undefined reference, which made the marker attribute effectively decorative for such tests.

The opt-out is per test (@betterC(selfContained: true)) rather than global because it is a property of the test: a module that is not itself -betterC-codegen-clean can still host a template-only test, and that self-containment is exactly what such a test asserts. --no-auto-include disables the whole derivation for a one-off run.

autoIncludeFlags
([
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
("pkg.a.__unittest_L1_C1", true),
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
("pkg.a.__unittest_L2_C1"),
],
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
.
(constant) sparkles.test_runner.driver.DriverOptions sparkles.test_runner.driver.DriverOptions.init = DriverOptions(null, null, null, false, false, false, ModeReport(null, null), null, null, null, null, false, null)
init
) == ["-i=pkg.a"]);
// --no-auto-include restores the strict template-only behavior. assert(
string[] sparkles.test_runner.driver.autoIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safe

The -i=<module> flags derived from the tests being extracted: one per distinct module that owns a test, minus the ones whose tests all opted out with selfContained.

Compiling the owning module in is the useful default. Without it an extracted program links against nothing but templates, so a @betterC test that calls any ordinary function of the very module it lives in — the common case — fails at link time with an undefined reference, which made the marker attribute effectively decorative for such tests.

The opt-out is per test (@betterC(selfContained: true)) rather than global because it is a property of the test: a module that is not itself -betterC-codegen-clean can still host a template-only test, and that self-containment is exactly what such a test asserts. --no-auto-include disables the whole derivation for a one-off run.

autoIncludeFlags
(
[
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L441_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
("pkg.a.__unittest_L1_C1")],
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(noAutoInclude: true)) == []);
} /// The compile context's flags: `-I` for the derived source roots, the /// harness roots, `dub describe`d dependency paths unless `noDub`, and the /// user's extras, then the string import paths, versions and flags /// (process-model TRX1–TRX4). private
(alias) object.string = string
string
[]
string[] sparkles.test_runner.driver.allImportFlags(in sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)

The compile context's flags: -I for the derived source roots, the harness roots, dub described dependency paths unless noDub, and the user's extras, then the string import paths, versions and flags (process-model TRX1–TRX4).

allImportFlags
(in
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
[]
(parameter) const(sparkles.test_runner.model.Test[]) allTests
allTests
, in
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
)
{ import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.iteration

This is a submodule of std.algorithm. It contains generic iteration algorithms.

Function Name Description
cache Eagerly evaluates and caches another range's front.
lazyCache Lazily evaluates and caches another range's front, unlike cache.
cacheBidirectional As above, but also provides back and popBack.
chunkBy chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]]) returns a range containing 3 subranges: the first with just [1, 1]; the second with the elements [1, 2] and [2, 2]; and the third with just [2, 1].
cumulativeFold cumulativeFold!((a, b) => a + b)([1, 2, 3, 4]) returns a lazily-evaluated range containing the successive reduced values 1, 3, 6, 10.
each each!writeln([1, 2, 3]) eagerly prints the numbers 1, 2 and 3 on their own lines.
filter filter!(a => a > 0)([1, -1, 2, 0, -3]) iterates over elements 1 and 2.
filterBidirectional Similar to filter, but also provides back and popBack at a small increase in cost.
fold fold!((a, b) => a + b)([1, 2, 3, 4]) returns 10.
group group([5, 2, 2, 3, 3]) returns a range containing the tuples tuple(5, 1), tuple(2, 2), and tuple(3, 2).
joiner joiner(["hello", "world!"], "; ") returns a range that iterates over the characters "hello; world!". No new string is created - the existing inputs are iterated.
map map!(a => a * 2)([1, 2, 3]) lazily returns a range with the numbers 2, 4, 6.
mean Colloquially known as the average, mean([1, 2, 3]) returns 2.
permutations Lazily computes all permutations using Heap's algorithm.
reduce reduce!((a, b) => a + b)([1, 2, 3, 4]) returns 10. This is the old implementation of fold.
splitWhen Lazily splits a range by comparing adjacent elements.
splitter Lazily splits a range by a separator, element predicate or whitespace.
substitute [1, 2].substitute(1, 0.1) returns [0.1, 2].
sum Same as fold, but specialized for accurate summation.
uniq Iterates over the unique elements in a range, which is assumed sorted.

Source

std/algorithm/iteration.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
iteration
:
(alias template) map = std.algorithm.iteration.map(fun...) if (fun.length >= 1)

Implements the homonym function (also known as transform) present in many languages of functional flavor. The call map!(fun)(range) returns a range of which elements are obtained by applying fun(a) left to right for all elements a in range. The original ranges are not changed. Evaluation is done lazily.

Params: fun = one or more transformation functions

See_Also: $(HTTP en.wikipedia.org/wiki/Map_(higher-order_function), Map (higher-order function))

map
;
import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.searching

This is a submodule of std.algorithm. It contains generic searching algorithms.

Function Name Description
all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive
any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive
balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses.
boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm.
canFind canFind("hello world", "or") returns true.
count Counts all elements or elements matching a predicate, specific element or sub-range.

count([1, 2, 1]) returns 3, count([1, 2, 1], 1) returns 2 and count!"a < 0"([1, -3, 0]) returns 1. | | countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. | | commonPrefix | commonPrefix("parakeet", "parachute") returns "para". | | endsWith | endsWith("rocks", "ks") returns true. | | extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. | | find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) | | findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. | | findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". | | findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. | | findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". | | findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". | | findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". | | minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). | | maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). | | minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. | | maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. | | minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. | | maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. | | minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. | | maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. | | skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. | | startsWith | startsWith("hello, world", "hello") returns true. | | until | Lazily iterates a range until a specific value is found. |

Source

std/algorithm/searching.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
searching
:
(alias template) 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 $(LREF find).

See_Also: $(REF among, std,algorithm,comparison) for checking a value against multiple arguments.

canFind
;
import
(package) std
std
.
(module) std.array

Functions and types that manipulate built-in arrays and associative arrays.

This module provides all kinds of functions to create, manipulate or convert arrays:

Function Name Description

| array | Returns a copy of the input in a newly allocated dynamic array. | | appender | Returns a new Appender or RefAppender initialized with a given array. | | assocArray | Returns a newly allocated associative array from a range/ranges of keys and values. | | byPair | Construct a range iterating over an associative array by key/value tuples. | | insertInPlace | Inserts into an existing array at a given position. | | join | Concatenates a range of ranges into one array. | | minimallyInitializedArray | Returns a new array of type T. | | replace | Returns a new array with all occurrences of a certain subrange replaced. | | replaceFirst | Returns a new array with the first occurrence of a certain subrange replaced. | | replaceInPlace | Replaces all occurrences of a certain subrange and puts the result into a given array. | | replaceInto | Replaces all occurrences of a certain subrange and puts the result into an output range. | | replaceLast | Returns a new array with the last occurrence of a certain subrange replaced. | | replaceSlice | Returns a new array with a given slice replaced. | | replicate | Creates a new array out of several copies of an input array or range. | | sameHead | Checks if the initial segments of two arrays refer to the same place in memory. | | sameTail | Checks if the final segments of two arrays refer to the same place in memory. | | split | Eagerly split a range or string into an array. | | staticArray | Creates a new static array from given data. | | uninitializedArray | Returns a new array of type T without initializing its elements. |

Source

std/array.d

@copyrightCopyright Andrei Alexandrescu 2008- and Jonathan M Davis 2011-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu and Jonathan M Davis
array
:
(alias template) 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.

Params: r = range (or aggregate with opApply function) whose elements are copied into the allocated array Returns: allocated and initialized array

array
;
import
(package) std
std
.
(module) std.path

This module is used to manipulate path strings.

All functions, with the exception of expandTilde (and in some cases absolutePath and relativePath), are pure string manipulation functions; they don't depend on any state outside the program, nor do they perform any actual file system actions. This has the consequence that the module does not make any distinction between a path that points to a directory and a path that points to a file, and it does not know whether or not the object pointed to by the path actually exists in the file system. To differentiate between these cases, use isDir and exists.

Note that on Windows, both the backslash (\) and the slash (/) are in principle valid directory separators. This module treats them both on equal footing, but in cases where a new separator is added, a backslash will be used. Furthermore, the buildNormalizedPath function will replace all slashes with backslashes on that platform.

In general, the functions in this module assume that the input paths are well-formed. (That is, they should not contain invalid characters, they should follow the file system's path format, etc.) The result of calling a function on an ill-formed path is undefined. When there is a chance that a path or a file name is invalid (for instance, when it has been input by the user), it may sometimes be desirable to use the isValidFilename and isValidPath functions to check this.

Most functions do not perform any memory allocations, and if a string is returned, it is usually a slice of an input string. If a function allocates, this is explicitly mentioned in the documentation.

Category Functions
Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde
Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive
Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath
Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension
Other filenameCharCmp filenameCmp globMatch CaseSensitive

Source

std/path.d

@authorsLars Tandle Kyllingstad, Walter Bright, Grzegorz Adam Hankiewicz, Thomas Khne, Andrei Alexandrescu@copyrightCopyright (c) 2000-2014, the authors. All rights reserved.@licenseBoost License 1.0
path
:
(alias template) baseName = std.path.baseName(R)(return scope R path) if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) && !isSomeString!R)

Params: cs = Whether or not suffix matching is case-sensitive. path = A path name. It can be a string, or any random-access range of characters. suffix = An optional suffix to be removed from the file name. Returns: The name of the file in the path name, without any leading directory and with an optional suffix chopped off.

    If `suffix` is specified, it will be compared to `path`
    using `filenameCmp!cs`,
    where `cs` is an optional template parameter determining whether
    the comparison is case sensitive or not.  See the
    $(LREF filenameCmp) documentation for details.

    Note:
    This function $(I only) strips away the specified suffix, which
    doesn't necessarily have to represent an extension.
    To remove the extension from a path, regardless of what the extension
    is, use $(LREF stripExtension).
    To obtain the filename without leading directories and without
    an extension, combine the functions like this:
    ---
    assert(baseName(stripExtension("dir/file.ext")) == "file");
    ---

    Standards:
    This function complies with
    $(LINK2 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/basename.html,
    the POSIX requirements for the 'basename' shell utility)
    (with suitable adaptations for Windows paths).
baseName
;
auto
(local variable) string[] roots
roots
=
string[] sparkles.test_runner.driver.deriveImportPaths(in sparkles.test_runner.model.Test[] allTests, in string[] extra) pure @safe

-I roots derived from every discovered test's module-name ↔ file-path pair, after the extras: the user's, then the harness roots the binary reported. Never the runner's own root: the pinned runner's copy of the attributes is not the one the tested package was compiled against (process-model TRX4).

deriveImportPaths
(
(parameter) const(sparkles.test_runner.model.Test[]) allTests
allTests
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string[] sparkles.test_runner.driver.DriverOptions.importPaths

extra -I paths

importPaths
~
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string[] sparkles.test_runner.driver.DriverOptions.harnessRoots

the source roots the test binary reported

harnessRoots
);
if (!
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) bool sparkles.test_runner.driver.DriverOptions.noDub

never run dub describe (process-model TRX2)

noDub
)
foreach (
(parameter) string path
path
;
string[] sparkles.test_runner.driver.dubDescribeImportPaths(in string[] sourceRoots, in sparkles.test_runner.driver.DriverOptions options)

Import paths reported by dub describe for the packages containing the derived source roots — this is how paths of registry dependencies (e.g. expected) are found. Best-effort: failures yield an empty list.

dubDescribeImportPaths
(
(local variable) string[] roots
roots
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
))
if (!
(local variable) string[] roots
roots
.
bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
(
(local variable) string path
path
))
(local variable) string[] roots
roots
~=
(local variable) string path
path
;
const
(local variable) const(bool) ldc
ldc
=
string sparkles.test_runner.driver.detectCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report = ModeReport(null, null)) @safe

The D compiler to use: explicit choice, $DC, or the first of ldc2/dmd found in $PATH (empty string when none). An explicit choice that doesn't resolve is reported to report and treated as "no compiler", so the caller's toolchain-missing skip fires instead of a raw ProcessException escaping from the spawn.

detectCompiler
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string sparkles.test_runner.driver.DriverOptions.compiler

explicit D compiler; empty = $DC, then ldc2, dmd

compiler
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.report

where the modes' messages go

report
).
string std.path.baseName!(immutable(char))(return scope string path) pure nothrow @nogc @safe

Note

This function only strips away the specified suffix, which doesn't necessarily have to represent an extension. To remove the extension from a path, regardless of what the extension is, use stripExtension. To obtain the filename without leading directories and without an extension, combine the functions like this:

assert(baseName(stripExtension("dir/file.ext")) == "file");
@paramcs Whether or not suffix matching is case-sensitive.@parampath A path name. It can be a string, or any random-access range of characters.@paramsuffix An optional suffix to be removed from the file name.@returns

The name of the file in the path name, without any leading directory and with an optional suffix chopped off.

If suffix is specified, it will be compared to path using filenameCmp!cs, where cs is an optional template parameter determining whether the comparison is case sensitive or not. See the filenameCmp documentation for details.

@standardsThis function complies with the POSIX requirements for the 'basename' shell utility (with suitable adaptations for Windows paths).
baseName
.
bool std.algorithm.searching.canFind!().canFind!(string, string)(string haystack, scope string needle) pure nothrow @nogc @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
("ldc");
return
(local variable) string[] roots
roots
.
sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L494_C23, string[]) sparkles.test_runner.driver.allImportFlags.map!(string[])(string[] r) pure nothrow @nogc @safe

Implements the homonym function (also known as transform) present in many languages of functional flavor. The call ``map!(fun)(range) returns a range of which elements are obtained by applying fun(a) left to right for all elements a in range. The original ranges are not changed. Evaluation is done lazily.

Examples

import std.algorithm.comparison : equal;
import std.range : chain, only;
auto squares =
    chain(only(1, 2, 3, 4), only(5, 6)).map!(a => a * a);
assert(equal(squares, only(1, 4, 9, 16, 25, 36)));

Multiple functions can be passed to map. In that case, the element type of map is a tuple containing one element for each function.

auto sums = [2, 4, 6, 8];
auto products = [1, 4, 9, 16];

size_t i = 0;
foreach (result; [ 1, 2, 3, 4 ].map!("a + a", "a * a"))
{
    assert(result[0] == sums[i]);
    assert(result[1] == products[i]);
    ++i;
}

You may alias map with some function(s) to a symbol and use it separately:

import std.algorithm.comparison : equal;
import std.conv : to;

alias stringize = map!(to!string);
assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ]));
@paramfun one or more transformation functions@seeMap (higher-order function)@paramr an input range@returnsA range with each fun applied to all the elements. If there is more than one fun, the element type will be Tuple containing one element for each fun.
map
!(p => "-I" ~ p).
string[] std.array.array!(sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L494_C23, string[]))(sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L494_C23, string[]) r) pure @safe

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.

@paramr range (or aggregate with opApply function) whose elements are copied into the allocated array@returnsallocated and initialized array
array
~
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string[] sparkles.test_runner.driver.DriverOptions.stringImportPaths

extra -J paths

stringImportPaths
.
sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L495_C42, const(string)[]) sparkles.test_runner.driver.allImportFlags.map!(const(string)[])(const(string)[] r) pure nothrow @nogc @safe

Implements the homonym function (also known as transform) present in many languages of functional flavor. The call ``map!(fun)(range) returns a range of which elements are obtained by applying fun(a) left to right for all elements a in range. The original ranges are not changed. Evaluation is done lazily.

Examples

import std.algorithm.comparison : equal;
import std.range : chain, only;
auto squares =
    chain(only(1, 2, 3, 4), only(5, 6)).map!(a => a * a);
assert(equal(squares, only(1, 4, 9, 16, 25, 36)));

Multiple functions can be passed to map. In that case, the element type of map is a tuple containing one element for each function.

auto sums = [2, 4, 6, 8];
auto products = [1, 4, 9, 16];

size_t i = 0;
foreach (result; [ 1, 2, 3, 4 ].map!("a + a", "a * a"))
{
    assert(result[0] == sums[i]);
    assert(result[1] == products[i]);
    ++i;
}

You may alias map with some function(s) to a symbol and use it separately:

import std.algorithm.comparison : equal;
import std.conv : to;

alias stringize = map!(to!string);
assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ]));
@paramfun one or more transformation functions@seeMap (higher-order function)@paramr an input range@returnsA range with each fun applied to all the elements. If there is more than one fun, the element type will be Tuple containing one element for each fun.
map
!(p => "-J" ~ p).
string[] std.array.array!(sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L495_C42, const(string)[]))(sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L495_C42, const(string)[]) r) pure @safe

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.

@paramr range (or aggregate with opApply function) whose elements are copied into the allocated array@returnsallocated and initialized array
array
~
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string[] sparkles.test_runner.driver.DriverOptions.versions

version identifiers

versions
.
sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L496_C33, const(string)[]) sparkles.test_runner.driver.allImportFlags.map!(const(string)[])(const(string)[] r) pure nothrow @nogc @safe

Implements the homonym function (also known as transform) present in many languages of functional flavor. The call ``map!(fun)(range) returns a range of which elements are obtained by applying fun(a) left to right for all elements a in range. The original ranges are not changed. Evaluation is done lazily.

Examples

import std.algorithm.comparison : equal;
import std.range : chain, only;
auto squares =
    chain(only(1, 2, 3, 4), only(5, 6)).map!(a => a * a);
assert(equal(squares, only(1, 4, 9, 16, 25, 36)));

Multiple functions can be passed to map. In that case, the element type of map is a tuple containing one element for each function.

auto sums = [2, 4, 6, 8];
auto products = [1, 4, 9, 16];

size_t i = 0;
foreach (result; [ 1, 2, 3, 4 ].map!("a + a", "a * a"))
{
    assert(result[0] == sums[i]);
    assert(result[1] == products[i]);
    ++i;
}

You may alias map with some function(s) to a symbol and use it separately:

import std.algorithm.comparison : equal;
import std.conv : to;

alias stringize = map!(to!string);
assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ]));
@paramfun one or more transformation functions@seeMap (higher-order function)@paramr an input range@returnsA range with each fun applied to all the elements. If there is more than one fun, the element type will be Tuple containing one element for each fun.
map
!(v => (ldc ? "-d-version=" : "-version=") ~ v).
string[] std.array.array!(sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L496_C33, const(string)[]))(sparkles.test_runner.driver.allImportFlags.MapResult!(__lambda_L496_C33, const(string)[]) r) pure @safe

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.

@paramr range (or aggregate with opApply function) whose elements are copied into the allocated array@returnsallocated and initialized array
array
~
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string[] sparkles.test_runner.driver.DriverOptions.dflags

extra compiler flags

dflags
.
string[] object.dup!string(const(string)[] a) pure nothrow @property @safe
dup
;
} // ───────────────────────────────────────────────────────────────────────────── // @ctfe // ───────────────────────────────────────────────────────────────────────────── /// The outcome of evaluating `@ctfe` tests through a probe compile. struct
(struct) sparkles.test_runner.driver.CtfeOutcome

The outcome of evaluating @ctfe tests through a probe compile.

CtfeOutcome
{ bool
(field) bool sparkles.test_runner.driver.CtfeOutcome.skipped

no D compiler found — reported but not a failure

skipped
; /// no D compiler found — reported but not a failure
bool
(field) bool sparkles.test_runner.driver.CtfeOutcome.succeeded

the probe compiled: every selected test passed

succeeded
; /// the probe compiled: every selected test passed
(alias) object.string = string
string
[]
(field) string[] sparkles.test_runner.driver.CtfeOutcome.failedNames

failing tests attributed from the compiler errors

failedNames
; /// failing tests attributed from the compiler errors
(alias) object.string = string
string
(field) string sparkles.test_runner.driver.CtfeOutcome.output

full compiler output (__ctfeWrite text, errors, …)

output
; /// full compiler output (`__ctfeWrite` text, errors, …)
} /// The actual module containing `test`: `test.moduleName` with aggregate /// qualifiers stripped (a nested test's `fullName` includes its aggregate), /// found by peeling trailing components until the name matches the file path.
(alias) object.string = string
string
string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safe

The actual module containing test: ``test.moduleName with aggregate qualifiers stripped (a nested test's fullName includes its aggregate), found by peeling trailing components until the name matches the file path.

probeModuleName
(const
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
(parameter) const(sparkles.test_runner.model.Test) test
test
) @safe pure nothrow
{
(alias) object.string = string
string
(local variable) string candidate
candidate
=
(parameter) const(sparkles.test_runner.model.Test) test
test
.
string sparkles.test_runner.model.Test.moduleName() const pure nothrow @nogc return scope @safe

The module part of fullName (everything before the last .).

moduleName
;
while (
(local variable) string candidate
candidate
.length)
{ if (
string sparkles.test_runner.extract.sourceRootOf(string file, string moduleName) pure nothrow @safe

Derives the source root of a module from its file path and dotted name: ("libs/base/src/sparkles/base/buffer.d", "sparkles.base.buffer") yields "libs/base/src". Returns null when the path does not end with the module path. Either separator matches: on Windows the compiler reports libs\base\src\sparkles\base\buffer.d, and the root keeps its own separators.

sourceRootOf
(
(parameter) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) string sparkles.test_runner.model.TestLocation.file
file
,
(local variable) string candidate
candidate
) !is null)
return
(local variable) string candidate
candidate
;
(alias) object.size_t = ulong
size_t
(local variable) ulong cut
cut
= 0;
foreach_reverse (
(parameter) ulong i
i
,
(parameter) immutable(char) c
c
;
(local variable) string candidate
candidate
)
if (
(local variable) immutable(char) c
c
== '.')
{
(local variable) ulong cut
cut
=
(local variable) ulong i
i
;
break; } if (!
(local variable) ulong cut
cut
)
break;
(local variable) string candidate
candidate
=
(local variable) string candidate
candidate
[0 ..
(local variable) ulong cut
cut
];
} return
(parameter) const(sparkles.test_runner.model.Test) test
test
.
string sparkles.test_runner.model.Test.moduleName() const pure nothrow @nogc return scope @safe

The module part of fullName (everything before the last .).

moduleName
;
} @("probeModuleName.nestedAndPlain") @safe pure unittest { import
(package) sparkles
sparkles
.
(package) sparkles.test_runner
test_runner
.
(module) sparkles.test_runner.model

Data model of the test runner: descriptions of discovered tests and the results of executing them.

Everything here is runtime data — the compile-time discovery that produces it lives in sparkles.test_runner.discovery.

model
:
(struct) sparkles.test_runner.model.TestLocation

Source location of a unittest block, from __traits(getLocation). The file path is as the compiler saw it (usually relative to the package root that dub test runs in).

TestLocation
;
const
(local variable) const(sparkles.test_runner.model.Test) plain
plain
=
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
(fullName: "pkg.mod.__unittest_L1_C1", name: "t",
location:
(struct) sparkles.test_runner.model.TestLocation

Source location of a unittest block, from __traits(getLocation). The file path is as the compiler saw it (usually relative to the package root that dub test runs in).

TestLocation
(file: "src/pkg/mod.d", line: 1, column: 1));
assert(
string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safe

The actual module containing test: ``test.moduleName with aggregate qualifiers stripped (a nested test's fullName includes its aggregate), found by peeling trailing components until the name matches the file path.

probeModuleName
(
(local variable) const(sparkles.test_runner.model.Test) plain
plain
) == "pkg.mod");
const
(local variable) const(sparkles.test_runner.model.Test) nested
nested
=
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
(fullName: "pkg.mod.Host.__unittest_L9_C1", name: "t",
location:
(struct) sparkles.test_runner.model.TestLocation

Source location of a unittest block, from __traits(getLocation). The file path is as the compiler saw it (usually relative to the package root that dub test runs in).

TestLocation
(file: "src/pkg/mod.d", line: 9, column: 1));
assert(
string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safe

The actual module containing test: ``test.moduleName with aggregate qualifiers stripped (a nested test's fullName includes its aggregate), found by peeling trailing components until the name matches the file path.

probeModuleName
(
(local variable) const(sparkles.test_runner.model.Test) nested
nested
) == "pkg.mod");
// Unresolvable path ↔ name pairs fall back to the raw module name. const
(local variable) const(sparkles.test_runner.model.Test) odd
odd
=
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
(fullName: "pkg.mod.__unittest_L1_C1", name: "t",
location:
(struct) sparkles.test_runner.model.TestLocation

Source location of a unittest block, from __traits(getLocation). The file path is as the compiler saw it (usually relative to the package root that dub test runs in).

TestLocation
(file: "elsewhere.d", line: 1, column: 1));
assert(
string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safe

The actual module containing test: ``test.moduleName with aggregate qualifiers stripped (a nested test's fullName includes its aggregate), found by peeling trailing components until the name matches the file path.

probeModuleName
(
(local variable) const(sparkles.test_runner.model.Test) odd
odd
) == "pkg.mod");
// A Windows path names the same module. const
(local variable) const(sparkles.test_runner.model.Test) windows
windows
=
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
(fullName: "pkg.mod.Host.__unittest_L9_C1", name: "t",
location:
(struct) sparkles.test_runner.model.TestLocation

Source location of a unittest block, from __traits(getLocation). The file path is as the compiler saw it (usually relative to the package root that dub test runs in).

TestLocation
(file: `src\pkg\mod.d`, line: 9, column: 1));
assert(
string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safe

The actual module containing test: ``test.moduleName with aggregate qualifiers stripped (a nested test's fullName includes its aggregate), found by peeling trailing components until the name matches the file path.

probeModuleName
(
(local variable) const(sparkles.test_runner.model.Test) windows
windows
) == "pkg.mod");
assert(
string[] sparkles.test_runner.driver.deriveImportPaths(in sparkles.test_runner.model.Test[] allTests, in string[] extra) pure @safe

-I roots derived from every discovered test's module-name ↔ file-path pair, after the extras: the user's, then the harness roots the binary reported. Never the runner's own root: the pinned runner's copy of the attributes is not the one the tested package was compiled against (process-model TRX4).

deriveImportPaths
([
(local variable) const(sparkles.test_runner.model.Test) windows
windows
], null) == [`src`]);
} /// Failing test names attributed from probe-compile output: the display-name /// argument of `ctfePassed!(…, "name")` on `error instantiating` lines.
(alias) object.string = string
string
[]
string[] sparkles.test_runner.driver.parseCtfeFailures(string output) pure @safe

Failing test names attributed from probe-compile output: the display-name argument of ctfePassed!(…, "name") on error instantiating lines.

parseCtfeFailures
(
(alias) object.string = string
string
(parameter) string output
output
) @safe pure
{ import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.searching

This is a submodule of std.algorithm. It contains generic searching algorithms.

Function Name Description
all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive
any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive
balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses.
boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm.
canFind canFind("hello world", "or") returns true.
count Counts all elements or elements matching a predicate, specific element or sub-range.

count([1, 2, 1]) returns 3, count([1, 2, 1], 1) returns 2 and count!"a < 0"([1, -3, 0]) returns 1. | | countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. | | commonPrefix | commonPrefix("parakeet", "parachute") returns "para". | | endsWith | endsWith("rocks", "ks") returns true. | | extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. | | find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) | | findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. | | findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". | | findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. | | findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". | | findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". | | findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". | | minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). | | maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). | | minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. | | maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. | | minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. | | maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. | | minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. | | maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. | | skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. | | startsWith | startsWith("hello, world", "hello") returns true. | | until | Lazily iterates a range until a specific value is found. |

Source

std/algorithm/searching.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
searching
:
(alias template) 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 $(LREF find).

See_Also: $(REF among, std,algorithm,comparison) for checking a value against multiple arguments.

canFind
;
import
(package) std
std
.
(module) std.string

String 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

@seestd.algorithm and std.range for generic range algorithms , std.ascii for functions that work with ASCII strings , std.uni for functions that work with unicode strings@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis, and David L. 'SpottedTiger' Davis
string
:
(alias template) indexOf = std.string.indexOf(Range)(Range s, dchar c, CaseSensitive cs = Yes.caseSensitive) if (isInputRange!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range)

Searches for a character in a string or range.

    Params:
        s = string or InputRange of characters to search for `c` in
        c = character to search for in `s`
        startIdx = index to a well-formed code point in `s` to start
            searching from; defaults to 0
        cs = specifies whether comparisons are case-sensitive
            (`Yes.caseSensitive`) or not (`No.caseSensitive`).

    Returns:
        If `c` is found in `s`, then the index of its first occurrence is
        returned. If `c` is not found or `startIdx` is greater than or equal to
        `s.length`, then -1 is returned. If the parameters are not valid UTF,
        the result will still be either -1 or in the range [`startIdx` ..
        `s.length`], but will not be reliable otherwise.

    Throws:
        If the sequence starting at `startIdx` does not represent a well-formed
        code point, then a $(REF UTFException, std,utf) may be thrown.

    See_Also: $(REF countUntil, std,algorithm,searching)
indexOf
,
(alias template) 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", $(REF lineSep, std,uni), $(REF paraSep, std,uni) 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 $(HTTP www.unicode.org/versions/Unicode7.0.0/ch05.pdf, Unicode 7.0).

    Does not allocate memory.

Params: r = array of chars, wchars, or dchars or a slicable range keepTerm = whether delimiter is included or not in the results Returns: range of slices of the input range r

See_Also: $(LREF splitLines) $(REF splitter, std,algorithm) $(REF splitter, std,regex)

lineSplitter
;
(alias) object.string = string
string
[]
(local variable) string[] names
names
;
foreach (
(local variable) string line
line
;
(parameter) string output
output
.
std.string.LineSplitter!(Flag.no, string) std.string.lineSplitter!(Flag.no, immutable(char))(string r) pure nothrow @nogc @safe

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.

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);
@paramr array of chars, wchars, or dchars or a slicable range@paramkeepTerm whether delimiter is included or not in the results@returnsrange of slices of the input range r@seesplitLines splitter splitter
lineSplitter
)
{ if (!
(local variable) string line
line
.
bool std.algorithm.searching.canFind!().canFind!(string, string)(string haystack, scope string needle) pure nothrow @nogc @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
("error instantiating"))
continue; auto
(local variable) long at
at
=
(local variable) string line
line
.
long std.string.indexOf!(string, char)(string s, const(char)[] sub) pure nothrow @nogc @safe

Searches for a substring in a string or range.

@params string or ForwardRange of characters to search for sub in@paramsub substring to search for in s@paramstartIdx index to a well-formed code point in s to start searching from; defaults to 0@paramcs specifies whether comparisons are case-sensitive (Yes.caseSensitive) or not (No.caseSensitive)@returnsThe index of the first occurrence of sub in s. If sub is not found or startIdx is greater than or equal to s`.length`, then -1 is returned. If the arguments are not valid UTF, the result will still be either -1 or in the range [`startIdx` .. s.length], but will not be reliable otherwise.@throwsIf the sequence starting at startIdx does not represent a well-formed code point, then a UTFException may be thrown.@bugsDoes not work with case-insensitive strings where the mapping of toLower and toUpper is not 1:1.
indexOf
("ctfePassed!(");
if (
(local variable) long at
at
< 0)
continue; const
(local variable) const(long) open
open
=
(local variable) string line
line
.
long std.string.indexOf!char(scope const(char)[] s, dchar c, ulong startIdx, std.typecons.Flag!"caseSensitive" cs = Flag.yes) pure nothrow @nogc @safe

Searches for a character in a string or range.

Examples

import std.typecons : No;

string s = "Hello World";
assert(indexOf(s, 'W') == 6);
assert(indexOf(s, 'Z') == -1);
assert(indexOf(s, 'w', No.caseSensitive) == 6);
import std.typecons : No;

string s = "Hello World";
assert(indexOf(s, 'W', 4) == 6);
assert(indexOf(s, 'Z', 100) == -1);
assert(indexOf(s, 'w', 3, No.caseSensitive) == 6);
@params string or InputRange of characters to search for c in@paramc character to search for in s@paramstartIdx index to a well-formed code point in s to start searching from; defaults to 0@paramcs specifies whether comparisons are case-sensitive (Yes.caseSensitive) or not (No.caseSensitive).@returnsIf c is found in s, then the index of its first occurrence is returned. If c is not found or startIdx is greater than or equal to s`.length`, then -1 is returned. If the parameters are not valid UTF, the result will still be either -1 or in the range [startIdx .. s.length], but will not be reliable otherwise.@throwsIf the sequence starting at startIdx does not represent a well-formed code point, then a UTFException may be thrown.@seecountUntil
indexOf
('"',
(local variable) long at
at
);
if (
(local variable) const(long) open
open
< 0)
continue;
(alias) object.size_t = ulong
size_t
(local variable) ulong close
close
=
(local variable) const(long) open
open
+ 1;
while (
(local variable) ulong close
close
<
(local variable) string line
line
.
(field) ulong string.length
length
&& !(
(local variable) string line
line
[
(local variable) ulong close
close
] == '"' &&
(local variable) string line
line
[
(local variable) ulong close
close
- 1] != '\\'))
(local variable) ulong close
close
++;
if (
(local variable) ulong close
close
>=
(local variable) string line
line
.
(field) ulong string.length
length
)
continue; const
(local variable) const(string) name
name
=
(local variable) string line
line
[
(local variable) const(long) open
open
+ 1 ..
(local variable) ulong close
close
];
if (!
(local variable) string[] names
names
.
bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
(
(local variable) const(string) name
name
))
(local variable) string[] names
names
~=
(local variable) const(string) name
name
;
} return
(local variable) string[] names
names
;
} @("parseCtfeFailures.trailLines") @safe pure unittest { enum
(constant) string sparkles.test_runner.driver.__unittest_L595_C1.output = "src/m.d(12,5): Error: boom\nprobe.d(60,27): Error: template instance `sparkles_test_runner_ctfe.ctfePassed!(__unittest_L12_C1, \"a.one\")` error instantiating\nprobe.d(60,13): while evaluating: `static assert(ctfePassed!(__unittest_L12_C1, \"a.one\"))`\nprobe.d(64,27): Error: template instance `sparkles_test_runner_ctfe.ctfePassed!(__unittest_L30_C1, \"b.two\")` error instantiating\n"
output
= "src/m.d(12,5): Error: boom\n" ~
"probe.d(60,27): Error: template instance " ~ "`sparkles_test_runner_ctfe.ctfePassed!(__unittest_L12_C1, \"a.one\")` " ~ "error instantiating\n" ~ "probe.d(60,13): while evaluating: `static assert(ctfePassed!" ~ "(__unittest_L12_C1, \"a.one\"))`\n" ~ "probe.d(64,27): Error: template instance " ~ "`sparkles_test_runner_ctfe.ctfePassed!(__unittest_L30_C1, \"b.two\")` " ~ "error instantiating\n"; assert(
string[] sparkles.test_runner.driver.parseCtfeFailures(string output) pure @safe

Failing test names attributed from probe-compile output: the display-name argument of ctfePassed!(…, "name") on error instantiating lines.

parseCtfeFailures
(
(constant) string sparkles.test_runner.driver.__unittest_L595_C1.output = "src/m.d(12,5): Error: boom\nprobe.d(60,27): Error: template instance `sparkles_test_runner_ctfe.ctfePassed!(__unittest_L12_C1, \"a.one\")` error instantiating\nprobe.d(60,13): while evaluating: `static assert(ctfePassed!(__unittest_L12_C1, \"a.one\"))`\nprobe.d(64,27): Error: template instance `sparkles_test_runner_ctfe.ctfePassed!(__unittest_L30_C1, \"b.two\")` error instantiating\n"
output
) == ["a.one", "b.two"]);
assert(
string[] sparkles.test_runner.driver.parseCtfeFailures(string output) pure @safe

Failing test names attributed from probe-compile output: the display-name argument of ctfePassed!(…, "name") on error instantiating lines.

parseCtfeFailures
("all fine") == []);
} /// Evaluates the given `@ctfe` tests: generates a probe program selecting /// exactly those tests, and compiles it — together with the tests' module /// sources — with `-o- -unittest` (semantic analysis only, so CTFE runs but /// nothing is codegen'd or linked). When `traceFile` is given, LDC's /// `-ftime-trace` flags are added and the trace is written there.
(struct) sparkles.test_runner.driver.CtfeOutcome

The outcome of evaluating @ctfe tests through a probe compile.

CtfeOutcome
sparkles.test_runner.driver.CtfeOutcome sparkles.test_runner.driver.runCtfeTests(in sparkles.test_runner.model.Test[] ctfeTests, in sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options, string traceFile = null)

Evaluates the given @ctfe tests: generates a probe program selecting exactly those tests, and compiles it — together with the tests' module sources — with -o- -unittest (semantic analysis only, so CTFE runs but nothing is codegen'd or linked). When traceFile is given, LDC's -ftime-trace flags are added and the trace is written there.

runCtfeTests
(
in
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
[]
(parameter) const(sparkles.test_runner.model.Test[]) ctfeTests
ctfeTests
, in
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
[]
(parameter) const(sparkles.test_runner.model.Test[]) allTests
allTests
, in
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
,
(alias) object.string = string
string
(parameter) string traceFile
traceFile
= null)
{ import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.searching

This is a submodule of std.algorithm. It contains generic searching algorithms.

Function Name Description
all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive
any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive
balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses.
boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm.
canFind canFind("hello world", "or") returns true.
count Counts all elements or elements matching a predicate, specific element or sub-range.

count([1, 2, 1]) returns 3, count([1, 2, 1], 1) returns 2 and count!"a < 0"([1, -3, 0]) returns 1. | | countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. | | commonPrefix | commonPrefix("parakeet", "parachute") returns "para". | | endsWith | endsWith("rocks", "ks") returns true. | | extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. | | find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) | | findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. | | findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". | | findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. | | findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". | | findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". | | findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". | | minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). | | maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). | | minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. | | maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. | | minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. | | maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. | | minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. | | maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. | | skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. | | startsWith | startsWith("hello, world", "hello") returns true. | | until | Lazily iterates a range until a specific value is found. |

Source

std/algorithm/searching.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
searching
:
(alias template) 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 $(LREF find).

See_Also: $(REF among, std,algorithm,comparison) for checking a value against multiple arguments.

canFind
;
import
(package) std
std
.
(module) std.file

Utilities 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

@copyrightCopyright The D Language Foundation 2007 - 2011.@seeThe official tutorial for an introduction to working with files in D, module std.stdio for opening files and manipulating them via handles, and module std.path for manipulating path strings.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis
file
:
(alias) mkdirRecurse = void std.file.mkdirRecurse(scope const(char)[] pathname) @safe

Make directory and all parent directories as needed.

Does nothing if the directory specified by pathname already exists.

Params: pathname = the full path of the directory to create

Throws: $(LREF FileException) on error.

mkdirRecurse
,
(alias template) 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.

Params: name = string or range of characters representing the file _name buffer = data to be written to file

Throws: $(LREF FileException) on error.

See_also: $(REF toFile, std,stdio)

write
;
import
(package) std
std
.
(module) std.path

This module is used to manipulate path strings.

All functions, with the exception of expandTilde (and in some cases absolutePath and relativePath), are pure string manipulation functions; they don't depend on any state outside the program, nor do they perform any actual file system actions. This has the consequence that the module does not make any distinction between a path that points to a directory and a path that points to a file, and it does not know whether or not the object pointed to by the path actually exists in the file system. To differentiate between these cases, use isDir and exists.

Note that on Windows, both the backslash (\) and the slash (/) are in principle valid directory separators. This module treats them both on equal footing, but in cases where a new separator is added, a backslash will be used. Furthermore, the buildNormalizedPath function will replace all slashes with backslashes on that platform.

In general, the functions in this module assume that the input paths are well-formed. (That is, they should not contain invalid characters, they should follow the file system's path format, etc.) The result of calling a function on an ill-formed path is undefined. When there is a chance that a path or a file name is invalid (for instance, when it has been input by the user), it may sometimes be desirable to use the isValidFilename and isValidPath functions to check this.

Most functions do not perform any memory allocations, and if a string is returned, it is usually a slice of an input string. If a function allocates, this is explicitly mentioned in the documentation.

Category Functions
Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde
Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive
Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath
Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension
Other filenameCharCmp filenameCmp globMatch CaseSensitive

Source

std/path.d

@authorsLars Tandle Kyllingstad, Walter Bright, Grzegorz Adam Hankiewicz, Thomas Khne, Andrei Alexandrescu@copyrightCopyright (c) 2000-2014, the authors. All rights reserved.@licenseBoost License 1.0
path
:
(alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))

Combines one or more path segments.

    This function takes a set of path segments, given as an input
    range of string elements or as a set of string arguments,
    and concatenates them with each other.  Directory separators
    are inserted between segments if necessary.  If any of the
    path segments are absolute (as defined by $(LREF isAbsolute)), the
    preceding segments will be dropped.

    On Windows, if one of the path segments are rooted, but not absolute
    (e.g. $(D `\foo`)), all preceding path segments down to the previous
    root will be dropped.  (See below for an example.)

    This function always allocates memory to hold the resulting path.
    The variadic overload is guaranteed to only perform a single
    allocation, as is the range version if `paths` is a forward
    range.

    Params:
        segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
        of segments to assemble the path from.
    Returns: The assembled path.
buildPath
,
(alias template) dirName = std.path.dirName(R)(return scope R path) if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R)

Returns the parent directory of path. On Windows, this includes the drive letter if present. If path is a relative path and the parent directory is the current working directory, returns ".".

    Params:
        path = A path name.

    Returns:
        A slice of `path` or `"."`.

    Standards:
    This function complies with
    $(LINK2 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/dirname.html,
    the POSIX requirements for the 'dirname' shell utility)
    (with suitable adaptations for Windows paths).
dirName
;
(struct) sparkles.test_runner.driver.CtfeOutcome

The outcome of evaluating @ctfe tests through a probe compile.

CtfeOutcome
(local variable) sparkles.test_runner.driver.CtfeOutcome outcome
outcome
;
const
(local variable) const(string) compiler
compiler
=
string sparkles.test_runner.driver.detectCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report = ModeReport(null, null)) @safe

The D compiler to use: explicit choice, $DC, or the first of ldc2/dmd found in $PATH (empty string when none). An explicit choice that doesn't resolve is reported to report and treated as "no compiler", so the caller's toolchain-missing skip fires instead of a raw ProcessException escaping from the spawn.

detectCompiler
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string sparkles.test_runner.driver.DriverOptions.compiler

explicit D compiler; empty = $DC, then ldc2, dmd

compiler
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.report

where the modes' messages go

report
);
if (!
(local variable) const(string) compiler
compiler
.
(field) ulong const(string).length
length
)
{
(local variable) sparkles.test_runner.driver.CtfeOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.CtfeOutcome.skipped

no D compiler found — reported but not a failure

skipped
= true;
return
(local variable) sparkles.test_runner.driver.CtfeOutcome outcome
outcome
;
}
(struct) sparkles.test_runner.extract.CtfeTarget

One @ctfe test to force through CTFE in a generated probe program.

CtfeTarget
[]
(local variable) sparkles.test_runner.extract.CtfeTarget[] targets
targets
;
(alias) object.string = string
string
[]
(local variable) string[] moduleFiles
moduleFiles
;
foreach (ref
(parameter) const(sparkles.test_runner.model.Test) test
test
;
(parameter) const(sparkles.test_runner.model.Test[]) ctfeTests
ctfeTests
)
{
(local variable) sparkles.test_runner.extract.CtfeTarget[] targets
targets
~=
(struct) sparkles.test_runner.extract.CtfeTarget

One @ctfe test to force through CTFE in a generated probe program.

CtfeTarget
(
moduleName:
string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safe

The actual module containing test: ``test.moduleName with aggregate qualifiers stripped (a nested test's fullName includes its aggregate), found by peeling trailing components until the name matches the file path.

probeModuleName
(
(local variable) const(sparkles.test_runner.model.Test) test
test
),
file:
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) string sparkles.test_runner.model.TestLocation.file
file
,
line:
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) ulong sparkles.test_runner.model.TestLocation.line
line
,
name:
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) string sparkles.test_runner.model.Test.name

Display name: the first string UDA, or the symbol identifier.

name
,
); if (!
(local variable) string[] moduleFiles
moduleFiles
.
bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
(
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) string sparkles.test_runner.model.TestLocation.file
file
))
(local variable) string[] moduleFiles
moduleFiles
~=
(local variable) const(sparkles.test_runner.model.Test) test
test
.
(field) sparkles.test_runner.model.TestLocation sparkles.test_runner.model.Test.location
location
.
(field) string sparkles.test_runner.model.TestLocation.file
file
;
} const
(local variable) const(string) workDir
workDir
=
string sparkles.test_runner.driver.makeWorkDir(string flavor, string own = null)

A fresh scratch directory for the generated program: beneath own, the run's DriverOptions.probeDir, when it names one, so clients that run several modes at once in one process keep them apart; else beneath setProbeDir's.

makeWorkDir
("ctfe",
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string sparkles.test_runner.driver.DriverOptions.probeDir

where generated programs go; empty = the temp directory

probeDir
);
const
(local variable) const(string) sourceFile
sourceFile
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) const(string) workDir
workDir
, "ctfe_tests.d");
void std.file.write!string(string name, const(void[]) buffer) @safe

Write 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);
@paramname string or range of characters representing the file name@parambuffer data to be written to file@throwsFileException on error.@seetoFile
write
(
(local variable) const(string) sourceFile
sourceFile
,
string sparkles.test_runner.extract.generateCtfeProgram(in sparkles.test_runner.extract.CtfeTarget[] targets) pure @safe

A complete probe program forcing the given @ctfe tests through CTFE.

The probe imports each test's module and selects the tests by reflection (matching __traits(getLocation) lines), so test bodies stay in their home modules — private symbols keep working and no source extraction is involved. It is meant to be compiled with -o- -unittest together with the modules' source files: semantic analysis (and therefore CTFE) only, no code generation. A failing test is a compile error whose closing error instantiating line carries the test's display name.

generateCtfeProgram
(
(local variable) sparkles.test_runner.extract.CtfeTarget[] targets
targets
));
(alias) object.string = string
string
[]
(local variable) string[] traceFlags
traceFlags
;
if (
(parameter) string traceFile
traceFile
.
(field) ulong string.length
length
)
{ try
void std.file.mkdirRecurse(scope const(char)[] pathname) @safe

Make 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);
@parampathname the full path of the directory to create@throwsFileException on error.
mkdirRecurse
(
(parameter) string traceFile
traceFile
.
string std.path.dirName!(immutable(char))(return scope string path) pure nothrow @nogc @safe

Returns the parent directory of path. On Windows, this includes the drive letter if present. If path is a relative path and the parent directory is the current working directory, returns ".".

Examples

assert(dirName("") == ".");
assert(dirName("file"w) == ".");
assert(dirName("dir/"d) == ".");
assert(dirName("dir///") == ".");
assert(dirName("dir/file"w.dup) == "dir");
assert(dirName("dir///file"d.dup) == "dir");
assert(dirName("dir/subdir/") == "dir");
assert(dirName("/dir/file"w) == "/dir");
assert(dirName("/file"d) == "/");
assert(dirName("/") == "/");
assert(dirName("///") == "/");

version (Windows)
{
    assert(dirName(`dir\`) == `.`);
    assert(dirName(`dir\\\`) == `.`);
    assert(dirName(`dir\file`) == `dir`);
    assert(dirName(`dir\\\file`) == `dir`);
    assert(dirName(`dir\subdir\`) == `dir`);
    assert(dirName(`\dir\file`) == `\dir`);
    assert(dirName(`\file`) == `\`);
    assert(dirName(`\`) == `\`);
    assert(dirName(`\\\`) == `\`);
    assert(dirName(`d:`) == `d:`);
    assert(dirName(`d:file`) == `d:`);
    assert(dirName(`d:\`) == `d:\`);
    assert(dirName(`d:\file`) == `d:\`);
    assert(dirName(`d:\dir\file`) == `d:\dir`);
    assert(dirName(`\\server\share\dir\file`) == `\\server\share\dir`);
    assert(dirName(`\\server\share\file`) == `\\server\share`);
    assert(dirName(`\\server\share\`) == `\\server\share`);
    assert(dirName(`\\server\share`) == `\\server\share`);
}
@parampath A path name.@returnsA slice of path or ".".@standardsThis function complies with the POSIX requirements for the 'dirname' shell utility (with suitable adaptations for Windows paths).
dirName
);
catch (
(class) object.Exception

The base class of all errors that are safe to catch and handle.

In principle, only thrown objects derived from this class are safe to catch inside a catch block. Thrown objects not derived from Exception represent runtime errors that should not be caught, as certain runtime guarantees may not hold, making it unsafe to continue program execution.

Examples

bool gotCaught;
try
{
    throw new Exception("msg");
}
catch (Exception e)
{
    gotCaught = true;
    assert(e.msg == "msg");
}
assert(gotCaught);
Exception
(local variable) object.Exception e
e
)
{ // An uncreatable trace directory must not escape the unittest hook // as a raw FileException stack trace; fail readably (the caller // prints `output` and recognizes the `--ctfe-trace:` prefix as an // environment problem, not a test failure). import
(package) std
std
.
(module) std.conv

A 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

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Shin Fujishiro, Adam D. Ruppe, Kenji Hara
conv
:
(alias template) text = std.conv.text(T...)(T args) if (T.length > 0)

Convenience functions for converting one or more arguments of any type into _text (the three character widths).

text
;
(local variable) sparkles.test_runner.driver.CtfeOutcome outcome
outcome
.
(field) string sparkles.test_runner.driver.CtfeOutcome.output

full compiler output (__ctfeWrite text, errors, …)

output
=
string std.conv.text!(string, string, string, string, string)(string __param_0, string __param_1, string __param_2, string __param_3, string __param_4) pure nothrow @safe

Convenience functions for converting one or more arguments of any type into text (the three character widths).

text
("--ctfe-trace: cannot create '",
(parameter) string traceFile
traceFile
.
string std.path.dirName!(immutable(char))(return scope string path) pure nothrow @nogc @safe

Returns the parent directory of path. On Windows, this includes the drive letter if present. If path is a relative path and the parent directory is the current working directory, returns ".".

Examples

assert(dirName("") == ".");
assert(dirName("file"w) == ".");
assert(dirName("dir/"d) == ".");
assert(dirName("dir///") == ".");
assert(dirName("dir/file"w.dup) == "dir");
assert(dirName("dir///file"d.dup) == "dir");
assert(dirName("dir/subdir/") == "dir");
assert(dirName("/dir/file"w) == "/dir");
assert(dirName("/file"d) == "/");
assert(dirName("/") == "/");
assert(dirName("///") == "/");

version (Windows)
{
    assert(dirName(`dir\`) == `.`);
    assert(dirName(`dir\\\`) == `.`);
    assert(dirName(`dir\file`) == `dir`);
    assert(dirName(`dir\\\file`) == `dir`);
    assert(dirName(`dir\subdir\`) == `dir`);
    assert(dirName(`\dir\file`) == `\dir`);
    assert(dirName(`\file`) == `\`);
    assert(dirName(`\`) == `\`);
    assert(dirName(`\\\`) == `\`);
    assert(dirName(`d:`) == `d:`);
    assert(dirName(`d:file`) == `d:`);
    assert(dirName(`d:\`) == `d:\`);
    assert(dirName(`d:\file`) == `d:\`);
    assert(dirName(`d:\dir\file`) == `d:\dir`);
    assert(dirName(`\\server\share\dir\file`) == `\\server\share\dir`);
    assert(dirName(`\\server\share\file`) == `\\server\share`);
    assert(dirName(`\\server\share\`) == `\\server\share`);
    assert(dirName(`\\server\share`) == `\\server\share`);
}
@parampath A path name.@returnsA slice of path or ".".@standardsThis function complies with the POSIX requirements for the 'dirname' shell utility (with suitable adaptations for Windows paths).
dirName
, "': ",
(local variable) object.Exception e
e
.
(field) string object.Throwable.msg

A message describing the error.

msg
, "\n");
(local variable) sparkles.test_runner.driver.CtfeOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.CtfeOutcome.succeeded

the probe compiled: every selected test passed

succeeded
= false;
return
(local variable) sparkles.test_runner.driver.CtfeOutcome outcome
outcome
;
}
(local variable) string[] traceFlags
traceFlags
= ["-ftime-trace", "-ftime-trace-file=" ~
(parameter) string traceFile
traceFile
,
"--ftime-trace-granularity=0"]; } // -verrors=0 lifts the default 20-error limit: parseCtfeFailures attributes // failures from the `error instantiating` trail lines, and a truncated // trail would report the cut-off failing tests as passed. const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compile
compile
=
std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safe

Runs command, echoing it when verbose, and returns (status, output). A spawn failure (compiler binary vanished between the detectCompiler check and here, or an unlaunchable absolute path) becomes a failed result instead of a ProcessException stack trace.

run
(
[
(local variable) const(string) compiler
compiler
, "-o-", "-unittest", "-checkaction=context", "-verrors=0"]
~
(local variable) string[] traceFlags
traceFlags
~
string[] sparkles.test_runner.driver.includeFlags(in sparkles.test_runner.driver.DriverOptions options) pure @safe

The extra -i=<pattern> flags requested with --include-import (e.g. --include-import=std.ascii to compile a std module in when an extracted test needs one of its non-template functions).

includeFlags
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
)
~
string[] sparkles.test_runner.driver.allImportFlags(in sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)

The compile context's flags: -I for the derived source roots, the harness roots, dub described dependency paths unless noDub, and the user's extras, then the string import paths, versions and flags (process-model TRX1–TRX4).

allImportFlags
(
(parameter) const(sparkles.test_runner.model.Test[]) allTests
allTests
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
) ~
(local variable) string[] moduleFiles
moduleFiles
~ [
(local variable) const(string) sourceFile
sourceFile
],
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
);
(local variable) sparkles.test_runner.driver.CtfeOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.CtfeOutcome.succeeded

the probe compiled: every selected test passed

succeeded
=
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compile
compile
.status == 0;
(local variable) sparkles.test_runner.driver.CtfeOutcome outcome
outcome
.
(field) string sparkles.test_runner.driver.CtfeOutcome.output

full compiler output (__ctfeWrite text, errors, …)

output
=
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compile
compile
.
(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1
output
;
if (!
(local variable) sparkles.test_runner.driver.CtfeOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.CtfeOutcome.succeeded

the probe compiled: every selected test passed

succeeded
)
(local variable) sparkles.test_runner.driver.CtfeOutcome outcome
outcome
.
(field) string[] sparkles.test_runner.driver.CtfeOutcome.failedNames

failing tests attributed from the compiler errors

failedNames
=
string[] sparkles.test_runner.driver.parseCtfeFailures(string output) pure @safe

Failing test names attributed from probe-compile output: the display-name argument of ctfePassed!(…, "name") on error instantiating lines.

parseCtfeFailures
(
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compile
compile
.
(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1
output
);
if (
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) bool sparkles.test_runner.driver.DriverOptions.keep

keep the generated files and print their location

keep
)
void sparkles.test_runner.driver.say!(string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2) @safe

args and a line feed, to report's output.

say
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "generated files kept in ",
(local variable) const(string) workDir
workDir
);
return
(local variable) sparkles.test_runner.driver.CtfeOutcome outcome
outcome
;
} // ───────────────────────────────────────────────────────────────────────────── // --better-c // ───────────────────────────────────────────────────────────────────────────── /// Extracts the `@betterC` tests, compiles them with `-betterC` (no /// druntime), runs the result, and reports.
(struct) sparkles.test_runner.driver.DriverOutcome

The outcome of one driver run.

DriverOutcome
sparkles.test_runner.driver.DriverOutcome sparkles.test_runner.driver.runBetterCTests(sparkles.test_runner.model.Test[] betterCTests, sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)

Extracts the @betterC tests, compiles them with -betterC (no druntime), runs the result, and reports.

runBetterCTests
(
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
[]
(parameter) sparkles.test_runner.model.Test[] betterCTests
betterCTests
,
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
[]
(parameter) sparkles.test_runner.model.Test[] allTests
allTests
, in
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
)
{ import
(package) std
std
.
(module) std.array

Functions and types that manipulate built-in arrays and associative arrays.

This module provides all kinds of functions to create, manipulate or convert arrays:

Function Name Description

| array | Returns a copy of the input in a newly allocated dynamic array. | | appender | Returns a new Appender or RefAppender initialized with a given array. | | assocArray | Returns a newly allocated associative array from a range/ranges of keys and values. | | byPair | Construct a range iterating over an associative array by key/value tuples. | | insertInPlace | Inserts into an existing array at a given position. | | join | Concatenates a range of ranges into one array. | | minimallyInitializedArray | Returns a new array of type T. | | replace | Returns a new array with all occurrences of a certain subrange replaced. | | replaceFirst | Returns a new array with the first occurrence of a certain subrange replaced. | | replaceInPlace | Replaces all occurrences of a certain subrange and puts the result into a given array. | | replaceInto | Replaces all occurrences of a certain subrange and puts the result into an output range. | | replaceLast | Returns a new array with the last occurrence of a certain subrange replaced. | | replaceSlice | Returns a new array with a given slice replaced. | | replicate | Creates a new array out of several copies of an input array or range. | | sameHead | Checks if the initial segments of two arrays refer to the same place in memory. | | sameTail | Checks if the final segments of two arrays refer to the same place in memory. | | split | Eagerly split a range or string into an array. | | staticArray | Creates a new static array from given data. | | uninitializedArray | Returns a new array of type T without initializing its elements. |

Source

std/array.d

@copyrightCopyright Andrei Alexandrescu 2008- and Jonathan M Davis 2011-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu and Jonathan M Davis
array
:
(alias template) 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.

Params: r = range (or aggregate with opApply function) whose elements are copied into the allocated array Returns: allocated and initialized array

array
;
import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.iteration

This is a submodule of std.algorithm. It contains generic iteration algorithms.

Function Name Description
cache Eagerly evaluates and caches another range's front.
lazyCache Lazily evaluates and caches another range's front, unlike cache.
cacheBidirectional As above, but also provides back and popBack.
chunkBy chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]]) returns a range containing 3 subranges: the first with just [1, 1]; the second with the elements [1, 2] and [2, 2]; and the third with just [2, 1].
cumulativeFold cumulativeFold!((a, b) => a + b)([1, 2, 3, 4]) returns a lazily-evaluated range containing the successive reduced values 1, 3, 6, 10.
each each!writeln([1, 2, 3]) eagerly prints the numbers 1, 2 and 3 on their own lines.
filter filter!(a => a > 0)([1, -1, 2, 0, -3]) iterates over elements 1 and 2.
filterBidirectional Similar to filter, but also provides back and popBack at a small increase in cost.
fold fold!((a, b) => a + b)([1, 2, 3, 4]) returns 10.
group group([5, 2, 2, 3, 3]) returns a range containing the tuples tuple(5, 1), tuple(2, 2), and tuple(3, 2).
joiner joiner(["hello", "world!"], "; ") returns a range that iterates over the characters "hello; world!". No new string is created - the existing inputs are iterated.
map map!(a => a * 2)([1, 2, 3]) lazily returns a range with the numbers 2, 4, 6.
mean Colloquially known as the average, mean([1, 2, 3]) returns 2.
permutations Lazily computes all permutations using Heap's algorithm.
reduce reduce!((a, b) => a + b)([1, 2, 3, 4]) returns 10. This is the old implementation of fold.
splitWhen Lazily splits a range by comparing adjacent elements.
splitter Lazily splits a range by a separator, element predicate or whitespace.
substitute [1, 2].substitute(1, 0.1) returns [0.1, 2].
sum Same as fold, but specialized for accurate summation.
uniq Iterates over the unique elements in a range, which is assumed sorted.

Source

std/algorithm/iteration.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
iteration
:
(alias template) map = std.algorithm.iteration.map(fun...) if (fun.length >= 1)

Implements the homonym function (also known as transform) present in many languages of functional flavor. The call map!(fun)(range) returns a range of which elements are obtained by applying fun(a) left to right for all elements a in range. The original ranges are not changed. Evaluation is done lazily.

Params: fun = one or more transformation functions

See_Also: $(HTTP en.wikipedia.org/wiki/Map_(higher-order_function), Map (higher-order function))

map
;
import
(package) std
std
.
(module) std.file

Utilities 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

@copyrightCopyright The D Language Foundation 2007 - 2011.@seeThe official tutorial for an introduction to working with files in D, module std.stdio for opening files and manipulating them via handles, and module std.path for manipulating path strings.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis
file
:
(alias template) 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.

Params: name = string or range of characters representing the file _name buffer = data to be written to file

Throws: $(LREF FileException) on error.

See_also: $(REF toFile, std,stdio)

write
;
import
(package) std
std
.
(module) std.path

This module is used to manipulate path strings.

All functions, with the exception of expandTilde (and in some cases absolutePath and relativePath), are pure string manipulation functions; they don't depend on any state outside the program, nor do they perform any actual file system actions. This has the consequence that the module does not make any distinction between a path that points to a directory and a path that points to a file, and it does not know whether or not the object pointed to by the path actually exists in the file system. To differentiate between these cases, use isDir and exists.

Note that on Windows, both the backslash (\) and the slash (/) are in principle valid directory separators. This module treats them both on equal footing, but in cases where a new separator is added, a backslash will be used. Furthermore, the buildNormalizedPath function will replace all slashes with backslashes on that platform.

In general, the functions in this module assume that the input paths are well-formed. (That is, they should not contain invalid characters, they should follow the file system's path format, etc.) The result of calling a function on an ill-formed path is undefined. When there is a chance that a path or a file name is invalid (for instance, when it has been input by the user), it may sometimes be desirable to use the isValidFilename and isValidPath functions to check this.

Most functions do not perform any memory allocations, and if a string is returned, it is usually a slice of an input string. If a function allocates, this is explicitly mentioned in the documentation.

Category Functions
Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde
Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive
Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath
Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension
Other filenameCharCmp filenameCmp globMatch CaseSensitive

Source

std/path.d

@authorsLars Tandle Kyllingstad, Walter Bright, Grzegorz Adam Hankiewicz, Thomas Khne, Andrei Alexandrescu@copyrightCopyright (c) 2000-2014, the authors. All rights reserved.@licenseBoost License 1.0
path
:
(alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))

Combines one or more path segments.

    This function takes a set of path segments, given as an input
    range of string elements or as a set of string arguments,
    and concatenates them with each other.  Directory separators
    are inserted between segments if necessary.  If any of the
    path segments are absolute (as defined by $(LREF isAbsolute)), the
    preceding segments will be dropped.

    On Windows, if one of the path segments are rooted, but not absolute
    (e.g. $(D `\foo`)), all preceding path segments down to the previous
    root will be dropped.  (See below for an example.)

    This function always allocates memory to hold the resulting path.
    The variadic overload is guaranteed to only perform a single
    allocation, as is the range version if `paths` is a forward
    range.

    Params:
        segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
        of segments to assemble the path from.
    Returns: The assembled path.
buildPath
;
(struct) sparkles.test_runner.driver.DriverOutcome

The outcome of one driver run.

DriverOutcome
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) ulong sparkles.test_runner.driver.DriverOutcome.testCount
testCount
=
(parameter) sparkles.test_runner.model.Test[] betterCTests
betterCTests
.
(field) ulong sparkles.test_runner.model.Test[].length
length
;
if (!
(parameter) sparkles.test_runner.model.Test[] betterCTests
betterCTests
.
(field) ulong sparkles.test_runner.model.Test[].length
length
)
{
void sparkles.test_runner.driver.say!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safe

args and a line feed, to report's output.

say
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "no @betterC tests found");
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} const
(local variable) const(string) compiler
compiler
=
string sparkles.test_runner.driver.detectCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report = ModeReport(null, null)) @safe

The D compiler to use: explicit choice, $DC, or the first of ldc2/dmd found in $PATH (empty string when none). An explicit choice that doesn't resolve is reported to report and treated as "no compiler", so the caller's toolchain-missing skip fires instead of a raw ProcessException escaping from the spawn.

detectCompiler
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string sparkles.test_runner.driver.DriverOptions.compiler

explicit D compiler; empty = $DC, then ldc2, dmd

compiler
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.report

where the modes' messages go

report
);
if (!
(local variable) const(string) compiler
compiler
.
(field) ulong const(string).length
length
)
{
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safe

args and a line feed, to report's diagnostics.

warn
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "skipping @betterC tests: no D compiler found (set $DC or --compiler)");
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.DriverOutcome.skipped

missing toolchain — reported but not a failure

skipped
= true;
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} const
(local variable) const(string) workDir
workDir
=
string sparkles.test_runner.driver.makeWorkDir(string flavor, string own = null)

A fresh scratch directory for the generated program: beneath own, the run's DriverOptions.probeDir, when it names one, so clients that run several modes at once in one process keep them apart; else beneath setProbeDir's.

makeWorkDir
("betterc",
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string sparkles.test_runner.driver.DriverOptions.probeDir

where generated programs go; empty = the temp directory

probeDir
);
const
(local variable) const(string) sourceFile
sourceFile
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) const(string) workDir
workDir
, "betterc_tests.d");
const
(local variable) const(string) binary
binary
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) const(string) workDir
workDir
, "betterc_tests");
void std.file.write!string(string name, const(void[]) buffer) @safe

Write 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);
@paramname string or range of characters representing the file name@parambuffer data to be written to file@throwsFileException on error.@seetoFile
write
(
(local variable) const(string) sourceFile
sourceFile
,
string sparkles.test_runner.extract.generateBetterCProgram(in sparkles.test_runner.extract.ExtractedTest[] tests) pure @safe

A complete standalone -betterC program running the given tests: the extracted functions plus an extern(C) main announcing each test before running it (so an assert abort is attributable).

generateBetterCProgram
(
sparkles.test_runner.extract.ExtractedTest[] sparkles.test_runner.driver.extractTests(in sparkles.test_runner.model.Test[] tests)

Slices the bodies of tests out of their source files. Files are read relative to the working directory — the same place the compiler resolved them from when the test build was created.

extractTests
(
(parameter) sparkles.test_runner.model.Test[] betterCTests
betterCTests
)));
const
(local variable) const(string[]) importFlags
importFlags
=
string[] sparkles.test_runner.driver.allImportFlags(in sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)

The compile context's flags: -I for the derived source roots, the harness roots, dub described dependency paths unless noDub, and the user's extras, then the string import paths, versions and flags (process-model TRX1–TRX4).

allImportFlags
(
(parameter) sparkles.test_runner.model.Test[] allTests
allTests
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
);
// Each test's own module is compiled in by default (see // `autoIncludeFlags`), so a test can call its module's ordinary functions // and not just its templates. Anything beyond that — a sibling module, or // a std module such as `--include-import=std.ascii` — is opt-in, and every // module compiled in must be betterC-codegen-clean. // `-checkaction=C` states the assert action the tests are written against // rather than inheriting it: a failed `assert` goes to the C library's, // which prints the message and aborts. `-betterC` already implies this // (verified: identical output with and without the flag), but the helpers // in `sparkles.base.buffer` reach for `assert(false, msg)` precisely // *because* `throw` is illegal here, so the pairing should be visible at // the compile site instead of resting on another switch's default. const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compile
compile
=
std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safe

Runs command, echoing it when verbose, and returns (status, output). A spawn failure (compiler binary vanished between the detectCompiler check and here, or an unlaunchable absolute path) becomes a failed result instead of a ProcessException stack trace.

run
(
[
(local variable) const(string) compiler
compiler
, "-betterC", "-checkaction=C", "-of=" ~
(local variable) const(string) binary
binary
]
~
string[] sparkles.test_runner.driver.autoIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safe

The -i=<module> flags derived from the tests being extracted: one per distinct module that owns a test, minus the ones whose tests all opted out with selfContained.

Compiling the owning module in is the useful default. Without it an extracted program links against nothing but templates, so a @betterC test that calls any ordinary function of the very module it lives in — the common case — fails at link time with an undefined reference, which made the marker attribute effectively decorative for such tests.

The opt-out is per test (@betterC(selfContained: true)) rather than global because it is a property of the test: a module that is not itself -betterC-codegen-clean can still host a template-only test, and that self-containment is exactly what such a test asserts. --no-auto-include disables the whole derivation for a one-off run.

autoIncludeFlags
(
(parameter) sparkles.test_runner.model.Test[] betterCTests
betterCTests
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
) ~
string[] sparkles.test_runner.driver.includeFlags(in sparkles.test_runner.driver.DriverOptions options) pure @safe

The extra -i=<pattern> flags requested with --include-import (e.g. --include-import=std.ascii to compile a std module in when an extracted test needs one of its non-template functions).

includeFlags
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
)
~
(local variable) const(string[]) importFlags
importFlags
~ [
(local variable) const(string) sourceFile
sourceFile
],
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
);
if (
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compile
compile
.status != 0)
{
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safe

args and a line feed, to report's diagnostics.

warn
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
,
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compile
compile
.
(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1
output
);
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safe

args and a line feed, to report's diagnostics.

warn
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "failed to compile the extracted @betterC tests (see above)");
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.DriverOutcome.succeeded
succeeded
= false;
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
=
std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safe

Runs command, echoing it when verbose, and returns (status, output). A spawn failure (compiler binary vanished between the detectCompiler check and here, or an unlaunchable absolute path) becomes a failed result instead of a ProcessException stack trace.

run
([
(local variable) const(string) binary
binary
],
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
);
void sparkles.test_runner.driver.sayRaw(in sparkles.test_runner.driver.DriverOptions options, string text)

text, as it is, to report's output.

sayRaw
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
,
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
.
(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1
output
);
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.DriverOutcome.succeeded
succeeded
=
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
.status == 0;
if (
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) bool sparkles.test_runner.driver.DriverOptions.keep

keep the generated files and print their location

keep
)
void sparkles.test_runner.driver.say!(string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2) @safe

args and a line feed, to report's output.

say
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "generated files kept in ",
(local variable) const(string) workDir
workDir
);
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} // ───────────────────────────────────────────────────────────────────────────── // --wasm // ───────────────────────────────────────────────────────────────────────────── /// The WASI target of `--wasm` (docs/specs/test-runner/SPEC.md, `@wasm`). enum
(constant) string sparkles.test_runner.driver.wasiTriple = "wasm32-unknown-wasip1"

The WASI target of --wasm (docs/specs/test-runner/SPEC.md, @wasm).

wasiTriple
= "wasm32-unknown-wasip1";
/// The variable naming an LDC that has the WASI runtime, when `$DC` does not. enum
(constant) string sparkles.test_runner.driver.wasiCompilerVariable = "SPARKLES_WASI_LDC"

The variable naming an LDC that has the WASI runtime, when $DC does not.

wasiCompilerVariable
= "SPARKLES_WASI_LDC";
/++ The compiler for `--wasm`: `--compiler`, then `$SPARKLES_WASI_LDC`, then the usual choice (`$DC`, `ldc2`); empty when none resolves. +/ private
(alias) object.string = string
string
string sparkles.test_runner.driver.wasiCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report) @safe

The compiler for --wasm: --compiler, then $SPARKLES_WASI_LDC, then the usual choice ($DC, ldc2); empty when none resolves.

wasiCompiler
(
(alias) object.string = string
string
(parameter) string preferred
preferred
, in
(struct) sparkles.test_runner.driver.ModeReport

Where the modes' messages go. The core prints nothing (process-model TRM1): its client renders these, to a terminal or as task output.

ModeReport
(parameter) const(sparkles.test_runner.driver.ModeReport) report
report
) @safe
{ import
(package) std
std
.
(module) std.process

Functions 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.

@authorsLars Tandle Kyllingstad, Steven Schveighoffer, Vladimir Panteleev@copyrightCopyright (c) 2013, the authors. All rights reserved.@licenseBoost License 1.0.
process
:
(class) std.process.environment

Manipulates 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
;
if (!
(parameter) string preferred
preferred
.
(field) ulong string.length
length
)
if (const
(local variable) const(string) wasi
wasi
=
(class) std.process.environment

Manipulates 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) @safe

Retrieves 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.
}
@paramname name of the environment variable to retrieve@paramdefaultValue default value to return if the environment variable doesn't exist.@returnsthe value of the environment variable if found, otherwise null if the environment doesn't exist.@throwsUTFException if the variable contains invalid UTF-16 characters (Windows only).
get
(
(constant) string sparkles.test_runner.driver.wasiCompilerVariable = "SPARKLES_WASI_LDC"

The variable naming an LDC that has the WASI runtime, when $DC does not.

wasiCompilerVariable
, null))
return
string sparkles.test_runner.driver.detectCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report = ModeReport(null, null)) @safe

The D compiler to use: explicit choice, $DC, or the first of ldc2/dmd found in $PATH (empty string when none). An explicit choice that doesn't resolve is reported to report and treated as "no compiler", so the caller's toolchain-missing skip fires instead of a raw ProcessException escaping from the spawn.

detectCompiler
(
(local variable) const(string) wasi
wasi
,
(parameter) const(sparkles.test_runner.driver.ModeReport) report
report
);
return
string sparkles.test_runner.driver.detectCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report = ModeReport(null, null)) @safe

The D compiler to use: explicit choice, $DC, or the first of ldc2/dmd found in $PATH (empty string when none). An explicit choice that doesn't resolve is reported to report and treated as "no compiler", so the caller's toolchain-missing skip fires instead of a raw ProcessException escaping from the spawn.

detectCompiler
(
(parameter) string preferred
preferred
,
(parameter) const(sparkles.test_runner.driver.ModeReport) report
report
);
} /++ The `-i` flags of a `--wasm` program. With the full druntime and Phobos there is no codegen restriction, so every module the tests import is compiled in (`-i`, which leaves out druntime and Phobos), except the owning modules of tests that are all `selfContained`. `--no-auto-include` compiles in nothing. +/
(alias) object.string = string
string
[]
string[] sparkles.test_runner.driver.wasiIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safe

The -i flags of a --wasm program. With the full druntime and Phobos there is no codegen restriction, so every module the tests import is compiled in (-i, which leaves out druntime and Phobos), except the owning modules of tests that are all selfContained. --no-auto-include compiles in nothing.

wasiIncludeFlags
(in
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
[]
(parameter) const(sparkles.test_runner.model.Test[]) extracted
extracted
, in
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
) @safe pure
{ import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.searching

This is a submodule of std.algorithm. It contains generic searching algorithms.

Function Name Description
all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive
any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive
balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses.
boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm.
canFind canFind("hello world", "or") returns true.
count Counts all elements or elements matching a predicate, specific element or sub-range.

count([1, 2, 1]) returns 3, count([1, 2, 1], 1) returns 2 and count!"a < 0"([1, -3, 0]) returns 1. | | countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. | | commonPrefix | commonPrefix("parakeet", "parachute") returns "para". | | endsWith | endsWith("rocks", "ks") returns true. | | extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. | | find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) | | findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. | | findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". | | findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. | | findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". | | findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". | | findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". | | minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). | | maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). | | minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. | | maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. | | minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. | | maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. | | minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. | | maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. | | skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. | | startsWith | startsWith("hello, world", "hello") returns true. | | until | Lazily iterates a range until a specific value is found. |

Source

std/algorithm/searching.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
searching
:
(alias template) all = std.algorithm.searching.all(alias pred = "a")

Checks if $(I _all) of the elements satisfy pred.

all
,
(alias template) 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 $(LREF find).

See_Also: $(REF among, std,algorithm,comparison) for checking a value against multiple arguments.

canFind
;
if (
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) bool sparkles.test_runner.driver.DriverOptions.noAutoInclude

don't compile the extracted tests' own modules in

noAutoInclude
)
return null;
(alias) object.string = string
string
[]
(local variable) string[] flags
flags
= ["-i"];
foreach (ref
(parameter) const(sparkles.test_runner.model.Test) test
test
;
(parameter) const(sparkles.test_runner.model.Test[]) extracted
extracted
)
{ const
(local variable) const(string) name
name
=
string sparkles.test_runner.driver.probeModuleName(const(sparkles.test_runner.model.Test) test) pure nothrow @safe

The actual module containing test: ``test.moduleName with aggregate qualifiers stripped (a nested test's fullName includes its aggregate), found by peeling trailing components until the name matches the file path.

probeModuleName
(
(local variable) const(sparkles.test_runner.model.Test) test
test
);
const
(local variable) const(string) exclude
exclude
= "-i=-" ~
(local variable) const(string) name
name
;
if (!
(local variable) string[] flags
flags
.
bool std.algorithm.searching.canFind!().canFind!(string[], string)(string[] haystack, scope string needle) pure nothrow @nogc @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
(
(local variable) const(string) exclude
exclude
)
&&
(parameter) const(sparkles.test_runner.model.Test[]) extracted
extracted
.
bool sparkles.test_runner.driver.wasiIncludeFlags.all!(const(sparkles.test_runner.model.Test)[])(const(sparkles.test_runner.model.Test)[] range) pure nothrow @safe

Checks if all of the elements satisfy pred.

Returns true if and only if the input range range is empty or all values found in range satisfy the predicate pred. Performs (at most) O(range.length) evaluations of pred.

Examples

assert( all!"a & 1"([1, 3, 5, 7, 9]));
assert(!all!"a & 1"([1, 2, 3, 5, 7, 9]));

all can also be used without a predicate, if its items can be evaluated to true or false in a conditional statement. This can be a convenient way to quickly evaluate that all of the elements of a range are true.

int[3] vals = [5, 3, 18];
assert( all(vals[]));
all
!(t => probeModuleName(t) != name || t.traits.selfContained))
(local variable) string[] flags
flags
~=
(local variable) const(string) exclude
exclude
;
} return
(local variable) string[] flags
flags
;
} @("driver.wasiIncludeFlags.everythingButSelfContainedModules") @safe pure unittest { static
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L808_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
(
(alias) object.string = string
string
(parameter) string fullName
fullName
, bool
(parameter) bool selfContained
selfContained
= false)
{
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
(local variable) sparkles.test_runner.model.Test t
t
;
(local variable) sparkles.test_runner.model.Test t
t
.
(field) string sparkles.test_runner.model.Test.fullName

Fully qualified name of the unittest symbol, e.g. sparkles.base.buffer.__unittest_L42_C1.

fullName
=
(parameter) string fullName
fullName
;
(local variable) sparkles.test_runner.model.Test t
t
.
(field) sparkles.test_runner.model.TestTraits sparkles.test_runner.model.Test.traits
traits
.
(field) bool sparkles.test_runner.model.TestTraits.selfContained

The test asserts it needs nothing linked from its own module, so the extracted --better-c / --wasm program leaves that module out (see betterC.selfContained``). One flag covers both modes: a test marked self-contained under either is self-contained under both.

selfContained
=
(parameter) bool selfContained
selfContained
;
return
(local variable) sparkles.test_runner.model.Test t
t
;
} assert(
string[] sparkles.test_runner.driver.wasiIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safe

The -i flags of a --wasm program. With the full druntime and Phobos there is no codegen restriction, so every module the tests import is compiled in (-i, which leaves out druntime and Phobos), except the owning modules of tests that are all selfContained. --no-auto-include compiles in nothing.

wasiIncludeFlags
([
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L808_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
("pkg.a.__unittest_L1_C1")],
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
.
(constant) sparkles.test_runner.driver.DriverOptions sparkles.test_runner.driver.DriverOptions.init = DriverOptions(null, null, null, false, false, false, ModeReport(null, null), null, null, null, null, false, null)
init
) == ["-i"]);
assert(
string[] sparkles.test_runner.driver.wasiIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safe

The -i flags of a --wasm program. With the full druntime and Phobos there is no codegen restriction, so every module the tests import is compiled in (-i, which leaves out druntime and Phobos), except the owning modules of tests that are all selfContained. --no-auto-include compiles in nothing.

wasiIncludeFlags
([
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L808_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
("pkg.a.__unittest_L1_C1", true),
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L808_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
("pkg.b.__unittest_L2_C1", true),
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L808_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
("pkg.b.__unittest_L3_C1"),
],
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
.
(constant) sparkles.test_runner.driver.DriverOptions sparkles.test_runner.driver.DriverOptions.init = DriverOptions(null, null, null, false, false, false, ModeReport(null, null), null, null, null, null, false, null)
init
) == ["-i", "-i=-pkg.a"]);
assert(
string[] sparkles.test_runner.driver.wasiIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safe

The -i flags of a --wasm program. With the full druntime and Phobos there is no codegen restriction, so every module the tests import is compiled in (-i, which leaves out druntime and Phobos), except the owning modules of tests that are all selfContained. --no-auto-include compiles in nothing.

wasiIncludeFlags
([
sparkles.test_runner.model.Test sparkles.test_runner.driver.__unittest_L808_C1.at(string fullName, bool selfContained = false) pure nothrow @nogc @safe
at
("pkg.a.__unittest_L1_C1")],
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(noAutoInclude: true)) is null);
} /// Extracts the `@wasm` tests, compiles them for `wasm32-unknown-wasip1` with /// the full druntime and Phobos of an LDC that has the WASI runtime (linked /// through that runtime's compiler driver, so no `wasm-ld` is needed), and /// runs the program under `wasmtime`. A missing runtime or `wasmtime` skips, /// naming what is missing.
(struct) sparkles.test_runner.driver.DriverOutcome

The outcome of one driver run.

DriverOutcome
sparkles.test_runner.driver.DriverOutcome sparkles.test_runner.driver.runWasmTests(sparkles.test_runner.model.Test[] wasmTests, sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)

Extracts the @wasm tests, compiles them for wasm32-unknown-wasip1 with the full druntime and Phobos of an LDC that has the WASI runtime (linked through that runtime's compiler driver, so no wasm-ld is needed), and runs the program under wasmtime. A missing runtime or wasmtime skips, naming what is missing.

runWasmTests
(
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
[]
(parameter) sparkles.test_runner.model.Test[] wasmTests
wasmTests
,
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
[]
(parameter) sparkles.test_runner.model.Test[] allTests
allTests
, in
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
)
{ import
(package) std
std
.
(module) std.file

Utilities 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

@copyrightCopyright The D Language Foundation 2007 - 2011.@seeThe official tutorial for an introduction to working with files in D, module std.stdio for opening files and manipulating them via handles, and module std.path for manipulating path strings.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis
file
:
(alias template) 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.

Params: name = string or range of characters representing the file _name buffer = data to be written to file

Throws: $(LREF FileException) on error.

See_also: $(REF toFile, std,stdio)

write
;
import
(package) std
std
.
(module) std.path

This module is used to manipulate path strings.

All functions, with the exception of expandTilde (and in some cases absolutePath and relativePath), are pure string manipulation functions; they don't depend on any state outside the program, nor do they perform any actual file system actions. This has the consequence that the module does not make any distinction between a path that points to a directory and a path that points to a file, and it does not know whether or not the object pointed to by the path actually exists in the file system. To differentiate between these cases, use isDir and exists.

Note that on Windows, both the backslash (\) and the slash (/) are in principle valid directory separators. This module treats them both on equal footing, but in cases where a new separator is added, a backslash will be used. Furthermore, the buildNormalizedPath function will replace all slashes with backslashes on that platform.

In general, the functions in this module assume that the input paths are well-formed. (That is, they should not contain invalid characters, they should follow the file system's path format, etc.) The result of calling a function on an ill-formed path is undefined. When there is a chance that a path or a file name is invalid (for instance, when it has been input by the user), it may sometimes be desirable to use the isValidFilename and isValidPath functions to check this.

Most functions do not perform any memory allocations, and if a string is returned, it is usually a slice of an input string. If a function allocates, this is explicitly mentioned in the documentation.

Category Functions
Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde
Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive
Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath
Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension
Other filenameCharCmp filenameCmp globMatch CaseSensitive

Source

std/path.d

@authorsLars Tandle Kyllingstad, Walter Bright, Grzegorz Adam Hankiewicz, Thomas Khne, Andrei Alexandrescu@copyrightCopyright (c) 2000-2014, the authors. All rights reserved.@licenseBoost License 1.0
path
:
(alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))

Combines one or more path segments.

    This function takes a set of path segments, given as an input
    range of string elements or as a set of string arguments,
    and concatenates them with each other.  Directory separators
    are inserted between segments if necessary.  If any of the
    path segments are absolute (as defined by $(LREF isAbsolute)), the
    preceding segments will be dropped.

    On Windows, if one of the path segments are rooted, but not absolute
    (e.g. $(D `\foo`)), all preceding path segments down to the previous
    root will be dropped.  (See below for an example.)

    This function always allocates memory to hold the resulting path.
    The variadic overload is guaranteed to only perform a single
    allocation, as is the range version if `paths` is a forward
    range.

    Params:
        segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
        of segments to assemble the path from.
    Returns: The assembled path.
buildPath
;
(struct) sparkles.test_runner.driver.DriverOutcome

The outcome of one driver run.

DriverOutcome
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) ulong sparkles.test_runner.driver.DriverOutcome.testCount
testCount
=
(parameter) sparkles.test_runner.model.Test[] wasmTests
wasmTests
.
(field) ulong sparkles.test_runner.model.Test[].length
length
;
if (!
(parameter) sparkles.test_runner.model.Test[] wasmTests
wasmTests
.
(field) ulong sparkles.test_runner.model.Test[].length
length
)
{
void sparkles.test_runner.driver.say!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safe

args and a line feed, to report's output.

say
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "no @wasm tests found");
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} const
(local variable) const(string) compiler
compiler
=
string sparkles.test_runner.driver.wasiCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report) @safe

The compiler for --wasm: --compiler, then $SPARKLES_WASI_LDC, then the usual choice ($DC, ldc2); empty when none resolves.

wasiCompiler
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string sparkles.test_runner.driver.DriverOptions.compiler

explicit D compiler; empty = $DC, then ldc2, dmd

compiler
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.report

where the modes' messages go

report
);
if (!
(local variable) const(string) compiler
compiler
.
(field) ulong const(string).length
length
)
{
void sparkles.test_runner.driver.warn!(string, string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2, string __param_3) @safe

args and a line feed, to report's diagnostics.

warn
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "skipping @wasm tests: no D compiler found (set $",
(constant) string sparkles.test_runner.driver.wasiCompilerVariable = "SPARKLES_WASI_LDC"

The variable naming an LDC that has the WASI runtime, when $DC does not.

wasiCompilerVariable
,
", --compiler or $DC)");
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.DriverOutcome.skipped

missing toolchain — reported but not a failure

skipped
= true;
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} if (!
bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safe

Whether an executable is reachable through searchPath ($PATH by default). On Windows the file is ``name.exe, as CreateProcess finds it: $DC=ldc2 names ldc2.exe there.

A local re-implementation rather than sparkles.core_cli.process_utils.isInPath: this module is source-compiled into base's test build, which has no core-cli dependency (the impl-library cycle is impl → base).

inPath
("wasmtime"))
{
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safe

args and a line feed, to report's diagnostics.

warn
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "skipping @wasm tests: wasmtime not found on PATH");
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.DriverOutcome.skipped

missing toolchain — reported but not a failure

skipped
= true;
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} const
(local variable) const(string) workDir
workDir
=
string sparkles.test_runner.driver.makeWorkDir(string flavor, string own = null)

A fresh scratch directory for the generated program: beneath own, the run's DriverOptions.probeDir, when it names one, so clients that run several modes at once in one process keep them apart; else beneath setProbeDir's.

makeWorkDir
("wasi",
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string sparkles.test_runner.driver.DriverOptions.probeDir

where generated programs go; empty = the temp directory

probeDir
);
// A compiler without the WASI runtime fails this, not the tests. const
(local variable) const(string) probeSource
probeSource
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) const(string) workDir
workDir
, "probe.d");
void std.file.write!string(string name, const(void[]) buffer) @safe

Write 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);
@paramname string or range of characters representing the file name@parambuffer data to be written to file@throwsFileException on error.@seetoFile
write
(
(local variable) const(string) probeSource
probeSource
, "void main() {}\n");
const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) probe
probe
=
std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safe

Runs command, echoing it when verbose, and returns (status, output). A spawn failure (compiler binary vanished between the detectCompiler check and here, or an unlaunchable absolute path) becomes a failed result instead of a ProcessException stack trace.

run
([
(local variable) const(string) compiler
compiler
, "-mtriple=" ~
(constant) string sparkles.test_runner.driver.wasiTriple = "wasm32-unknown-wasip1"

The WASI target of --wasm (docs/specs/test-runner/SPEC.md, @wasm).

wasiTriple
, "-of=" ~
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) const(string) workDir
workDir
, "probe.wasm"),
(local variable) const(string) probeSource
probeSource
],
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
);
if (
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) probe
probe
.status != 0)
{
void sparkles.test_runner.driver.warn!(string, string, string, string, string, string, string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2, string __param_3, string __param_4, string __param_5, string __param_6, string __param_7, string __param_8) @safe

args and a line feed, to report's diagnostics.

warn
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "skipping @wasm tests: ",
(local variable) const(string) compiler
compiler
, " cannot link a ",
(constant) string sparkles.test_runner.driver.wasiTriple = "wasm32-unknown-wasip1"

The WASI target of --wasm (docs/specs/test-runner/SPEC.md, @wasm).

wasiTriple
,
" program (no WASI runtime; set $",
(constant) string sparkles.test_runner.driver.wasiCompilerVariable = "SPARKLES_WASI_LDC"

The variable naming an LDC that has the WASI runtime, when $DC does not.

wasiCompilerVariable
, "):\n",
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) probe
probe
.
(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1
output
);
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.DriverOutcome.skipped

missing toolchain — reported but not a failure

skipped
= true;
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} const
(local variable) const(string) sourceFile
sourceFile
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) const(string) workDir
workDir
, "wasm_tests.d");
const
(local variable) const(string) wasmFile
wasmFile
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) const(string) workDir
workDir
, "wasm_tests.wasm");
void std.file.write!string(string name, const(void[]) buffer) @safe

Write 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);
@paramname string or range of characters representing the file name@parambuffer data to be written to file@throwsFileException on error.@seetoFile
write
(
(local variable) const(string) sourceFile
sourceFile
,
string sparkles.test_runner.extract.generateWasiProgram(in sparkles.test_runner.extract.ExtractedTest[] tests) pure @safe

A complete WASI program running the given tests (--wasm): the extracted functions plus a main that announces and runs each one, catching what it throws, so one failing test does not hide the rest. The full druntime is there, so a failed assert is an AssertError like any other Throwable. The exit status is 1 when any test failed.

generateWasiProgram
(
sparkles.test_runner.extract.ExtractedTest[] sparkles.test_runner.driver.extractTests(in sparkles.test_runner.model.Test[] tests)

Slices the bodies of tests out of their source files. Files are read relative to the working directory — the same place the compiler resolved them from when the test build was created.

extractTests
(
(parameter) sparkles.test_runner.model.Test[] wasmTests
wasmTests
)));
const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compile
compile
=
std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safe

Runs command, echoing it when verbose, and returns (status, output). A spawn failure (compiler binary vanished between the detectCompiler check and here, or an unlaunchable absolute path) becomes a failed result instead of a ProcessException stack trace.

run
(
[
(local variable) const(string) compiler
compiler
, "-mtriple=" ~
(constant) string sparkles.test_runner.driver.wasiTriple = "wasm32-unknown-wasip1"

The WASI target of --wasm (docs/specs/test-runner/SPEC.md, @wasm).

wasiTriple
, "-of=" ~
(local variable) const(string) wasmFile
wasmFile
]
~
string[] sparkles.test_runner.driver.wasiIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safe

The -i flags of a --wasm program. With the full druntime and Phobos there is no codegen restriction, so every module the tests import is compiled in (-i, which leaves out druntime and Phobos), except the owning modules of tests that are all selfContained. --no-auto-include compiles in nothing.

wasiIncludeFlags
(
(parameter) sparkles.test_runner.model.Test[] wasmTests
wasmTests
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
) ~
string[] sparkles.test_runner.driver.includeFlags(in sparkles.test_runner.driver.DriverOptions options) pure @safe

The extra -i=<pattern> flags requested with --include-import (e.g. --include-import=std.ascii to compile a std module in when an extracted test needs one of its non-template functions).

includeFlags
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
)
~ (
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) bool sparkles.test_runner.driver.DriverOptions.noDub

never run dub describe (process-model TRX2)

noDub
? null :
string[] sparkles.test_runner.driver.dubDescribeLanguageFlags(in string[] sourceRoots, in sparkles.test_runner.driver.DriverOptions options)

The language-semantics switches (-preview=, -revert=, -transition=) that dub describe reports for the packages containing the derived source roots. A program compiled outside dub needs them to see the packages' code the way their own builds do (-preview=dip1000 changes attribute inference). Best-effort: failures yield an empty list.

dubDescribeLanguageFlags
(
string[] sparkles.test_runner.driver.deriveImportPaths(in sparkles.test_runner.model.Test[] allTests, in string[] extra) pure @safe

-I roots derived from every discovered test's module-name ↔ file-path pair, after the extras: the user's, then the harness roots the binary reported. Never the runner's own root: the pinned runner's copy of the attributes is not the one the tested package was compiled against (process-model TRX4).

deriveImportPaths
(
(parameter) sparkles.test_runner.model.Test[] wasmTests
wasmTests
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string[] sparkles.test_runner.driver.DriverOptions.importPaths

extra -I paths

importPaths
),
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
))
~
string[] sparkles.test_runner.driver.allImportFlags(in sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)

The compile context's flags: -I for the derived source roots, the harness roots, dub described dependency paths unless noDub, and the user's extras, then the string import paths, versions and flags (process-model TRX1–TRX4).

allImportFlags
(
(parameter) sparkles.test_runner.model.Test[] allTests
allTests
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
) ~ [
(local variable) const(string) sourceFile
sourceFile
],
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
);
if (
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compile
compile
.status != 0)
{
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safe

args and a line feed, to report's diagnostics.

warn
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
,
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compile
compile
.
(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1
output
);
void sparkles.test_runner.driver.warn!(string, string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2, string __param_3) @safe

args and a line feed, to report's diagnostics.

warn
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "failed to compile the extracted @wasm tests for ",
(constant) string sparkles.test_runner.driver.wasiTriple = "wasm32-unknown-wasip1"

The WASI target of --wasm (docs/specs/test-runner/SPEC.md, @wasm).

wasiTriple
, " (see above)");
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.DriverOutcome.succeeded
succeeded
= false;
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
=
std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safe

Runs command, echoing it when verbose, and returns (status, output). A spawn failure (compiler binary vanished between the detectCompiler check and here, or an unlaunchable absolute path) becomes a failed result instead of a ProcessException stack trace.

run
(["wasmtime", "run",
(local variable) const(string) wasmFile
wasmFile
],
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
);
void sparkles.test_runner.driver.sayRaw(in sparkles.test_runner.driver.DriverOptions options, string text)

text, as it is, to report's output.

sayRaw
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
,
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
.
(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1
output
);
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.DriverOutcome.succeeded
succeeded
=
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
.status == 0;
if (
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) bool sparkles.test_runner.driver.DriverOptions.keep

keep the generated files and print their location

keep
)
void sparkles.test_runner.driver.say!(string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2) @safe

args and a line feed, to report's output.

say
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "generated files kept in ",
(local variable) const(string) workDir
workDir
);
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} // ───────────────────────────────────────────────────────────────────────────── // --wasm-bare // ───────────────────────────────────────────────────────────────────────────── /// Extracts the `@wasm` tests, cross-compiles them to bare `wasm32` with /// `-betterC` and LDC's internal linker, and runs them with the first /// available WebAssembly-capable runtime (`node`, `deno`, `bun`, or /// `wasmtime`).
(struct) sparkles.test_runner.driver.DriverOutcome

The outcome of one driver run.

DriverOutcome
sparkles.test_runner.driver.DriverOutcome sparkles.test_runner.driver.runWasmBareTests(sparkles.test_runner.model.Test[] wasmTests, sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)

Extracts the @wasm tests, cross-compiles them to bare wasm32 with -betterC and LDC's internal linker, and runs them with the first available WebAssembly-capable runtime (node, deno, bun, or wasmtime).

runWasmBareTests
(
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
[]
(parameter) sparkles.test_runner.model.Test[] wasmTests
wasmTests
,
(struct) sparkles.test_runner.model.Test

One discovered unittest block.

Test
[]
(parameter) sparkles.test_runner.model.Test[] allTests
allTests
, in
(struct) sparkles.test_runner.driver.DriverOptions

Options shared by both driver modes.

DriverOptions
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
)
{ import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.iteration

This is a submodule of std.algorithm. It contains generic iteration algorithms.

Function Name Description
cache Eagerly evaluates and caches another range's front.
lazyCache Lazily evaluates and caches another range's front, unlike cache.
cacheBidirectional As above, but also provides back and popBack.
chunkBy chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]]) returns a range containing 3 subranges: the first with just [1, 1]; the second with the elements [1, 2] and [2, 2]; and the third with just [2, 1].
cumulativeFold cumulativeFold!((a, b) => a + b)([1, 2, 3, 4]) returns a lazily-evaluated range containing the successive reduced values 1, 3, 6, 10.
each each!writeln([1, 2, 3]) eagerly prints the numbers 1, 2 and 3 on their own lines.
filter filter!(a => a > 0)([1, -1, 2, 0, -3]) iterates over elements 1 and 2.
filterBidirectional Similar to filter, but also provides back and popBack at a small increase in cost.
fold fold!((a, b) => a + b)([1, 2, 3, 4]) returns 10.
group group([5, 2, 2, 3, 3]) returns a range containing the tuples tuple(5, 1), tuple(2, 2), and tuple(3, 2).
joiner joiner(["hello", "world!"], "; ") returns a range that iterates over the characters "hello; world!". No new string is created - the existing inputs are iterated.
map map!(a => a * 2)([1, 2, 3]) lazily returns a range with the numbers 2, 4, 6.
mean Colloquially known as the average, mean([1, 2, 3]) returns 2.
permutations Lazily computes all permutations using Heap's algorithm.
reduce reduce!((a, b) => a + b)([1, 2, 3, 4]) returns 10. This is the old implementation of fold.
splitWhen Lazily splits a range by comparing adjacent elements.
splitter Lazily splits a range by a separator, element predicate or whitespace.
substitute [1, 2].substitute(1, 0.1) returns [0.1, 2].
sum Same as fold, but specialized for accurate summation.
uniq Iterates over the unique elements in a range, which is assumed sorted.

Source

std/algorithm/iteration.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
iteration
:
(alias template) map = std.algorithm.iteration.map(fun...) if (fun.length >= 1)

Implements the homonym function (also known as transform) present in many languages of functional flavor. The call map!(fun)(range) returns a range of which elements are obtained by applying fun(a) left to right for all elements a in range. The original ranges are not changed. Evaluation is done lazily.

Params: fun = one or more transformation functions

See_Also: $(HTTP en.wikipedia.org/wiki/Map_(higher-order_function), Map (higher-order function))

map
;
import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.searching

This is a submodule of std.algorithm. It contains generic searching algorithms.

Function Name Description
all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive
any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive
balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses.
boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm.
canFind canFind("hello world", "or") returns true.
count Counts all elements or elements matching a predicate, specific element or sub-range.

count([1, 2, 1]) returns 3, count([1, 2, 1], 1) returns 2 and count!"a < 0"([1, -3, 0]) returns 1. | | countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. | | commonPrefix | commonPrefix("parakeet", "parachute") returns "para". | | endsWith | endsWith("rocks", "ks") returns true. | | extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. | | find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) | | findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. | | findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". | | findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. | | findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". | | findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". | | findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". | | minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). | | maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). | | minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. | | maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. | | minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. | | maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. | | minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. | | maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. | | skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. | | startsWith | startsWith("hello, world", "hello") returns true. | | until | Lazily iterates a range until a specific value is found. |

Source

std/algorithm/searching.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
searching
:
(alias template) 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 $(LREF find).

See_Also: $(REF among, std,algorithm,comparison) for checking a value against multiple arguments.

canFind
;
import
(package) std
std
.
(module) std.array

Functions and types that manipulate built-in arrays and associative arrays.

This module provides all kinds of functions to create, manipulate or convert arrays:

Function Name Description

| array | Returns a copy of the input in a newly allocated dynamic array. | | appender | Returns a new Appender or RefAppender initialized with a given array. | | assocArray | Returns a newly allocated associative array from a range/ranges of keys and values. | | byPair | Construct a range iterating over an associative array by key/value tuples. | | insertInPlace | Inserts into an existing array at a given position. | | join | Concatenates a range of ranges into one array. | | minimallyInitializedArray | Returns a new array of type T. | | replace | Returns a new array with all occurrences of a certain subrange replaced. | | replaceFirst | Returns a new array with the first occurrence of a certain subrange replaced. | | replaceInPlace | Replaces all occurrences of a certain subrange and puts the result into a given array. | | replaceInto | Replaces all occurrences of a certain subrange and puts the result into an output range. | | replaceLast | Returns a new array with the last occurrence of a certain subrange replaced. | | replaceSlice | Returns a new array with a given slice replaced. | | replicate | Creates a new array out of several copies of an input array or range. | | sameHead | Checks if the initial segments of two arrays refer to the same place in memory. | | sameTail | Checks if the final segments of two arrays refer to the same place in memory. | | split | Eagerly split a range or string into an array. | | staticArray | Creates a new static array from given data. | | uninitializedArray | Returns a new array of type T without initializing its elements. |

Source

std/array.d

@copyrightCopyright Andrei Alexandrescu 2008- and Jonathan M Davis 2011-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu and Jonathan M Davis
array
:
(alias template) 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.

Params: r = range (or aggregate with opApply function) whose elements are copied into the allocated array Returns: allocated and initialized array

array
;
import
(package) std
std
.
(module) std.conv

A 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

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Shin Fujishiro, Adam D. Ruppe, Kenji Hara
conv
:
(alias template) text = std.conv.text(T...)(T args) if (T.length > 0)

Convenience functions for converting one or more arguments of any type into _text (the three character widths).

text
;
import
(package) std
std
.
(module) std.file

Utilities 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

@copyrightCopyright The D Language Foundation 2007 - 2011.@seeThe official tutorial for an introduction to working with files in D, module std.stdio for opening files and manipulating them via handles, and module std.path for manipulating path strings.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis
file
:
(alias template) 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.

Params: name = string or range of characters representing the file _name buffer = data to be written to file

Throws: $(LREF FileException) on error.

See_also: $(REF toFile, std,stdio)

write
;
import
(package) std
std
.
(module) std.path

This module is used to manipulate path strings.

All functions, with the exception of expandTilde (and in some cases absolutePath and relativePath), are pure string manipulation functions; they don't depend on any state outside the program, nor do they perform any actual file system actions. This has the consequence that the module does not make any distinction between a path that points to a directory and a path that points to a file, and it does not know whether or not the object pointed to by the path actually exists in the file system. To differentiate between these cases, use isDir and exists.

Note that on Windows, both the backslash (\) and the slash (/) are in principle valid directory separators. This module treats them both on equal footing, but in cases where a new separator is added, a backslash will be used. Furthermore, the buildNormalizedPath function will replace all slashes with backslashes on that platform.

In general, the functions in this module assume that the input paths are well-formed. (That is, they should not contain invalid characters, they should follow the file system's path format, etc.) The result of calling a function on an ill-formed path is undefined. When there is a chance that a path or a file name is invalid (for instance, when it has been input by the user), it may sometimes be desirable to use the isValidFilename and isValidPath functions to check this.

Most functions do not perform any memory allocations, and if a string is returned, it is usually a slice of an input string. If a function allocates, this is explicitly mentioned in the documentation.

Category Functions
Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde
Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive
Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath
Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension
Other filenameCharCmp filenameCmp globMatch CaseSensitive

Source

std/path.d

@authorsLars Tandle Kyllingstad, Walter Bright, Grzegorz Adam Hankiewicz, Thomas Khne, Andrei Alexandrescu@copyrightCopyright (c) 2000-2014, the authors. All rights reserved.@licenseBoost License 1.0
path
:
(alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))

Combines one or more path segments.

    This function takes a set of path segments, given as an input
    range of string elements or as a set of string arguments,
    and concatenates them with each other.  Directory separators
    are inserted between segments if necessary.  If any of the
    path segments are absolute (as defined by $(LREF isAbsolute)), the
    preceding segments will be dropped.

    On Windows, if one of the path segments are rooted, but not absolute
    (e.g. $(D `\foo`)), all preceding path segments down to the previous
    root will be dropped.  (See below for an example.)

    This function always allocates memory to hold the resulting path.
    The variadic overload is guaranteed to only perform a single
    allocation, as is the range version if `paths` is a forward
    range.

    Params:
        segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
        of segments to assemble the path from.
    Returns: The assembled path.
buildPath
;
(struct) sparkles.test_runner.driver.DriverOutcome

The outcome of one driver run.

DriverOutcome
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) ulong sparkles.test_runner.driver.DriverOutcome.testCount
testCount
=
(parameter) sparkles.test_runner.model.Test[] wasmTests
wasmTests
.
(field) ulong sparkles.test_runner.model.Test[].length
length
;
if (!
(parameter) sparkles.test_runner.model.Test[] wasmTests
wasmTests
.
(field) ulong sparkles.test_runner.model.Test[].length
length
)
{
void sparkles.test_runner.driver.say!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safe

args and a line feed, to report's output.

say
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "no @wasm tests found");
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} // llvm_trap + -mtriple make this LDC-specific. const
(local variable) const(string) compiler
compiler
=
string sparkles.test_runner.driver.detectCompiler(string preferred, in sparkles.test_runner.driver.ModeReport report = ModeReport(null, null)) @safe

The D compiler to use: explicit choice, $DC, or the first of ldc2/dmd found in $PATH (empty string when none). An explicit choice that doesn't resolve is reported to report and treated as "no compiler", so the caller's toolchain-missing skip fires instead of a raw ProcessException escaping from the spawn.

detectCompiler
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string sparkles.test_runner.driver.DriverOptions.compiler

explicit D compiler; empty = $DC, then ldc2, dmd

compiler
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) sparkles.test_runner.driver.ModeReport sparkles.test_runner.driver.DriverOptions.report

where the modes' messages go

report
);
if (!
(local variable) const(string) compiler
compiler
.
bool std.algorithm.searching.canFind!().canFind!(string, string)(string haystack, scope string needle) pure nothrow @nogc @safe

Convenience 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")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
("ldc"))
{
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safe

args and a line feed, to report's diagnostics.

warn
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "skipping @wasm tests: an LDC compiler is required (set $DC or --compiler)");
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.DriverOutcome.skipped

missing toolchain — reported but not a failure

skipped
= true;
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} const
(local variable) const(string) workDir
workDir
=
string sparkles.test_runner.driver.makeWorkDir(string flavor, string own = null)

A fresh scratch directory for the generated program: beneath own, the run's DriverOptions.probeDir, when it names one, so clients that run several modes at once in one process keep them apart; else beneath setProbeDir's.

makeWorkDir
("wasm",
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) string sparkles.test_runner.driver.DriverOptions.probeDir

where generated programs go; empty = the temp directory

probeDir
);
const
(local variable) const(string) sourceFile
sourceFile
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) const(string) workDir
workDir
, "wasm_tests.d");
const
(local variable) const(string) wasmFile
wasmFile
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) const(string) workDir
workDir
, "wasm_tests.wasm");
const
(local variable) const(string) shimFile
shimFile
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
(local variable) const(string) workDir
workDir
, "wasm_tests.js");
const
(local variable) const(sparkles.test_runner.extract.ExtractedTest[]) extracted
extracted
=
sparkles.test_runner.extract.ExtractedTest[] sparkles.test_runner.driver.extractTests(in sparkles.test_runner.model.Test[] tests)

Slices the bodies of tests out of their source files. Files are read relative to the working directory — the same place the compiler resolved them from when the test build was created.

extractTests
(
(parameter) sparkles.test_runner.model.Test[] wasmTests
wasmTests
);
void std.file.write!string(string name, const(void[]) buffer) @safe

Write 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);
@paramname string or range of characters representing the file name@parambuffer data to be written to file@throwsFileException on error.@seetoFile
write
(
(local variable) const(string) sourceFile
sourceFile
,
string sparkles.test_runner.extract.generateWasmBareProgram(in sparkles.test_runner.extract.ExtractedTest[] tests) pure @safe

A complete bare wasm32 test module (--wasm-bare): the extracted functions, each exported as test_<i> for individual invocation by the host shim, plus a trapping __assert handler (there is no libc on bare wasm32, so a failed assert traps and surfaces as a host-side RuntimeError).

generateWasmBareProgram
(
(local variable) const(sparkles.test_runner.extract.ExtractedTest[]) extracted
extracted
));
void std.file.write!string(string name, const(void[]) buffer) @safe

Write 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);
@paramname string or range of characters representing the file name@parambuffer data to be written to file@throwsFileException on error.@seetoFile
write
(
(local variable) const(string) shimFile
shimFile
,
string sparkles.test_runner.extract.generateWasmBareJsShim(in sparkles.test_runner.extract.ExtractedTest[] tests, string wasmFile) pure @safe

The JavaScript shim executing a generated wasm test module under node, deno, or bun: instantiates the module and calls each run_test_<i> export, reporting per-test outcomes.

generateWasmBareJsShim
(
(local variable) const(sparkles.test_runner.extract.ExtractedTest[]) extracted
extracted
,
(local variable) const(string) wasmFile
wasmFile
));
const
(local variable) const(string[]) importFlags
importFlags
=
string[] sparkles.test_runner.driver.allImportFlags(in sparkles.test_runner.model.Test[] allTests, in sparkles.test_runner.driver.DriverOptions options)

The compile context's flags: -I for the derived source roots, the harness roots, dub described dependency paths unless noDub, and the user's extras, then the string import paths, versions and flags (process-model TRX1–TRX4).

allImportFlags
(
(parameter) sparkles.test_runner.model.Test[] allTests
allTests
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
);
const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compile
compile
=
std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safe

Runs command, echoing it when verbose, and returns (status, output). A spawn failure (compiler binary vanished between the detectCompiler check and here, or an unlaunchable absolute path) becomes a failed result instead of a ProcessException stack trace.

run
(
[
(local variable) const(string) compiler
compiler
, "-mtriple=wasm32-unknown-unknown-wasm", "-betterC",
// LDC's own LLD: bare wasm32 has no C compiler driver to link with "-link-internally", // reactor-style module: no _start, tests are individual exports "-L--no-entry", // `export` alone does not make wasm-ld export a symbol; only some // LDC configurations add this switch themselves "-L--export-dynamic", "-of=" ~
(local variable) const(string) wasmFile
wasmFile
]
~
string[] sparkles.test_runner.driver.autoIncludeFlags(in sparkles.test_runner.model.Test[] extracted, in sparkles.test_runner.driver.DriverOptions options) pure @safe

The -i=<module> flags derived from the tests being extracted: one per distinct module that owns a test, minus the ones whose tests all opted out with selfContained.

Compiling the owning module in is the useful default. Without it an extracted program links against nothing but templates, so a @betterC test that calls any ordinary function of the very module it lives in — the common case — fails at link time with an undefined reference, which made the marker attribute effectively decorative for such tests.

The opt-out is per test (@betterC(selfContained: true)) rather than global because it is a property of the test: a module that is not itself -betterC-codegen-clean can still host a template-only test, and that self-containment is exactly what such a test asserts. --no-auto-include disables the whole derivation for a one-off run.

autoIncludeFlags
(
(parameter) sparkles.test_runner.model.Test[] wasmTests
wasmTests
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
) ~
string[] sparkles.test_runner.driver.includeFlags(in sparkles.test_runner.driver.DriverOptions options) pure @safe

The extra -i=<pattern> flags requested with --include-import (e.g. --include-import=std.ascii to compile a std module in when an extracted test needs one of its non-template functions).

includeFlags
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
)
~
(local variable) const(string[]) importFlags
importFlags
~ [
(local variable) const(string) sourceFile
sourceFile
],
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
);
if (
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compile
compile
.status != 0)
{
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safe

args and a line feed, to report's diagnostics.

warn
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
,
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) compile
compile
.
(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1
output
);
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safe

args and a line feed, to report's diagnostics.

warn
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "failed to cross-compile the extracted @wasm tests (see above)");
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safe

args and a line feed, to report's diagnostics.

warn
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "note: with a stock LDC, the import chain of a @wasm test's " ~
"module must avoid druntime headers that do not support wasm32;\n" ~ "point --compiler (or $DC) at a wasm-enabled LDC build for full " ~ "druntime/Phobos support");
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.DriverOutcome.succeeded
succeeded
= false;
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} const(
(alias) object.string = string
string
)[]
(local variable) const(string)[] runCommand
runCommand
;
if (
bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safe

Whether an executable is reachable through searchPath ($PATH by default). On Windows the file is ``name.exe, as CreateProcess finds it: $DC=ldc2 names ldc2.exe there.

A local re-implementation rather than sparkles.core_cli.process_utils.isInPath: this module is source-compiled into base's test build, which has no core-cli dependency (the impl-library cycle is impl → base).

inPath
("node"))
(local variable) const(string)[] runCommand
runCommand
= ["node",
(local variable) const(string) shimFile
shimFile
];
else if (
bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safe

Whether an executable is reachable through searchPath ($PATH by default). On Windows the file is ``name.exe, as CreateProcess finds it: $DC=ldc2 names ldc2.exe there.

A local re-implementation rather than sparkles.core_cli.process_utils.isInPath: this module is source-compiled into base's test build, which has no core-cli dependency (the impl-library cycle is impl → base).

inPath
("deno"))
(local variable) const(string)[] runCommand
runCommand
= ["deno", "run", "--allow-read",
(local variable) const(string) shimFile
shimFile
];
else if (
bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safe

Whether an executable is reachable through searchPath ($PATH by default). On Windows the file is ``name.exe, as CreateProcess finds it: $DC=ldc2 names ldc2.exe there.

A local re-implementation rather than sparkles.core_cli.process_utils.isInPath: this module is source-compiled into base's test build, which has no core-cli dependency (the impl-library cycle is impl → base).

inPath
("bun"))
(local variable) const(string)[] runCommand
runCommand
= ["bun",
(local variable) const(string) shimFile
shimFile
];
else if (
bool sparkles.test_runner.driver.inPath(string name, string searchPath = null) @safe

Whether an executable is reachable through searchPath ($PATH by default). On Windows the file is ``name.exe, as CreateProcess finds it: $DC=ldc2 names ldc2.exe there.

A local re-implementation rather than sparkles.core_cli.process_utils.isInPath: this module is source-compiled into base's test build, which has no core-cli dependency (the impl-library cycle is impl → base).

inPath
("wasmtime"))
{ // No JS runtime: invoke each exported test directly. foreach (
(parameter) ulong i
i
, ref
(parameter) const(sparkles.test_runner.extract.ExtractedTest) test
test
;
(local variable) const(sparkles.test_runner.extract.ExtractedTest[]) extracted
extracted
)
{ const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
=
std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safe

Runs command, echoing it when verbose, and returns (status, output). A spawn failure (compiler binary vanished between the detectCompiler check and here, or an unlaunchable absolute path) becomes a failed result instead of a ProcessException stack trace.

run
(["wasmtime", "run",
"--invoke",
string std.conv.text!(string, ulong)(string __param_0, ulong __param_1) pure nothrow @safe

Convenience functions for converting one or more arguments of any type into text (the three character widths).

text
("run_test_",
(local variable) ulong i
i
),
(local variable) const(string) wasmFile
wasmFile
],
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
);
const
(local variable) const(bool) ok
ok
=
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
.status == 0;
void sparkles.test_runner.driver.say!(string, string, string, string, string, const(ulong), string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2, string __param_3, string __param_4, string __param_5, const(ulong) __param_6, string __param_7) @safe

args and a line feed, to report's output.

say
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
,
(local variable) const(bool) ok
ok
? " ✓ " : " ✗ ",
(local variable) const(sparkles.test_runner.extract.ExtractedTest) test
test
.
(field) string sparkles.test_runner.extract.ExtractedTest.name

display name

name
,
" [",
(local variable) const(sparkles.test_runner.extract.ExtractedTest) test
test
.
(field) string sparkles.test_runner.extract.ExtractedTest.file
file
, ":",
(local variable) const(sparkles.test_runner.extract.ExtractedTest) test
test
.
(field) ulong sparkles.test_runner.extract.ExtractedTest.line
line
, "]");
if (!
(local variable) const(bool) ok
ok
)
{
void sparkles.test_runner.driver.sayRaw(in sparkles.test_runner.driver.DriverOptions options, string text)

text, as it is, to report's output.

sayRaw
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
,
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
.
(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1
output
);
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.DriverOutcome.succeeded
succeeded
= false;
} } if (
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) bool sparkles.test_runner.driver.DriverOptions.keep

keep the generated files and print their location

keep
)
void sparkles.test_runner.driver.say!(string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2) @safe

args and a line feed, to report's output.

say
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "generated files kept in ",
(local variable) const(string) workDir
workDir
);
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} else {
void sparkles.test_runner.driver.warn!string(in sparkles.test_runner.driver.DriverOptions options, string __param_1) @safe

args and a line feed, to report's diagnostics.

warn
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "skipping @wasm tests: no WebAssembly runtime found " ~
"(looked for node, deno, bun, wasmtime)");
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.DriverOutcome.skipped

missing toolchain — reported but not a failure

skipped
= true;
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
} const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
=
std.typecons.Tuple!(int, "status", string, "output") sparkles.test_runner.driver.run(const(string)[] command, in sparkles.test_runner.driver.DriverOptions options) @safe

Runs command, echoing it when verbose, and returns (status, output). A spawn failure (compiler binary vanished between the detectCompiler check and here, or an unlaunchable absolute path) becomes a failed result instead of a ProcessException stack trace.

run
(
(local variable) const(string)[] runCommand
runCommand
,
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
);
void sparkles.test_runner.driver.sayRaw(in sparkles.test_runner.driver.DriverOptions options, string text)

text, as it is, to report's output.

sayRaw
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
,
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
.
(field) string std.typecons.Tuple!(int, "status", string, "output").__expand_field_1
output
);
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
.
(field) bool sparkles.test_runner.driver.DriverOutcome.succeeded
succeeded
=
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
.status == 0;
if (
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
.
(field) bool sparkles.test_runner.driver.DriverOptions.keep

keep the generated files and print their location

keep
)
void sparkles.test_runner.driver.say!(string, string)(in sparkles.test_runner.driver.DriverOptions options, string __param_1, string __param_2) @safe

args and a line feed, to report's output.

say
(
(parameter) const(sparkles.test_runner.driver.DriverOptions) options
options
, "generated files kept in ",
(local variable) const(string) workDir
workDir
);
return
(local variable) sparkles.test_runner.driver.DriverOutcome outcome
outcome
;
}