gui-ab.dhover×578all
#!/usr/bin/env dub
/+ dub.sdl:
    name "gui_ab"
    dependency "sparkles:core-cli" path="../../.."
    dependency "sparkles:base" path="../../.."
    dependency "raylib-d" version="~>6.2.0"
    // raylib-d's `library` config does not declare it; the image API is
    // CPU-side, so no window is opened.
    libs "raylib"
    buildType "checked" {
        buildOptions "optimize" "inline" "debugInfo"
    }
+/
// The A/B oracle a behaviour-preserving hue GUI change otherwise lacks — the
// window sibling of `tui-ab.d`.
//
// A terminal application's output IS its frame, which is what lets `tui-ab`
// compare bytes off a pty. A window has no such stream, so the frame has to be
// asked for: `HUE_GUI_SCREENSHOT` renders a fixed number of warm-up frames and
// writes a PNG (`DBG1`). That capture is specified to be REPRODUCIBLE — it
// waits out the async git-status worker, whose landing rebuilds the tree — so
// two runs of one binary produce identical bytes, and two builds that paint the
// same window produce identical bytes too.
//
//   dub run --single apps/hue/tools/gui-ab.d -- \
//       --old /tmp/hue-before --new apps/hue/build/hue \
//       --file docs/specs/ui/containers.md
//
// Three guards, each because its failure reads as a pass:
//
//   * A capture must be REPRODUCIBLE before it may be compared. Every side is
//     captured `--runs` times and a side that disagrees with itself is a
//     failure, not a diff — otherwise the tool blames the change for a race.
//   * The two binaries must actually DIFFER, because `dub build -c no-gui`
//     writes to the same path as the default config and A/B-ing one build
//     against itself reads as "identical" for the wrong reason.
//   * The display number is PINNED. `xvfb-run -a` picks a free number, but it
//     can land on the workstation's real display, where ambient keystrokes
//     reach the window and act as commands — a `t` toggles the copy format, an
//     arrow cycles the theme. That is recorded in the ui-app plan as something
//     that already happened.
//
// The font size is pinned too (`--font-size`, via `HUE_GUI_FONTSIZE`): a
// capture whose size quietly follows the panel's DPI is a broken oracle rather
// than a cosmetic difference (`CLI6`).
//
// `--pointer x,y` parks the pointer through `HUE_GUI_POINTER`, which is how a
// hovered scrollbar — a lit track, an expanded rail — becomes photographable.
//
// Exit status: 0 identical, 1 drift, 2 a setup problem — a missing binary,
// no `xvfb-run`, or a non-reproducible capture.
module 
(module) gui_ab
gui_ab
;
import
(package) std
std
.
(module) std.algorithm

This package implements generic algorithms oriented towards the processing of sequences. Sequences processed by these functions define range-based interfaces. See also Reference on ranges and tutorial on ranges.

Algorithms are categorized into the following submodules:

Submodule Functions

| Searching | all any balancedParens boyerMooreFinder canFind commonPrefix count countUntil endsWith find findAdjacent findAmong findSkip findSplit findSplitAfter findSplitBefore minCount maxCount minElement maxElement minIndex maxIndex minPos maxPos skipOver startsWith until |

| Comparison | among castSwitch clamp cmp either equal isPermutation isSameLength levenshteinDistance levenshteinDistanceAndPath max min mismatch predSwitch |

| Iteration | cache cacheBidirectional chunkBy cumulativeFold each filter filterBidirectional fold group joiner map mean permutations reduce splitWhen splitter substitute sum uniq |

| Sorting | completeSort isPartitioned isSorted isStrictlyMonotonic ordered strictlyOrdered makeIndex merge multiSort nextEvenPermutation nextPermutation nthPermutation partialSort partition partition3 schwartzSort sort topN topNCopy topNIndex |

| Set operations (setops) | cartesianProduct largestPartialIntersection largestPartialIntersectionWeighted multiwayMerge multiwayUnion setDifference setIntersection setSymmetricDifference |

| Mutation | bringToFront copy fill initializeAll move moveAll moveSome moveEmplace moveEmplaceAll moveEmplaceSome remove reverse strip stripLeft stripRight swap swapRanges uninitializedFill |

Many functions in this package are parameterized with a predicate. The predicate may be any suitable callable type (a function, a delegate, a functor, or a lambda), or a compile-time string. The string may consist of any legal D expression that uses the symbol a (for unary functions) or the symbols a and b (for binary functions). These names will NOT interfere with other homonym symbols in user code because they are evaluated in a different context. The default for all binary comparison predicates is "a == b" for unordered operations and "a < b" for ordered operations.

Example

int[] a = ...;
static bool greater(int a, int b)
{
    return a > b;
}
sort!greater(a);           // predicate as alias
sort!((a, b) => a > b)(a); // predicate as a lambda.
sort!"a > b"(a);           // predicate as string
                           // (no ambiguity with array name)
sort(a);                   // no predicate, "a < b" is implicit

Source

std/algorithm/package.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
algorithm
:
(alias template) gui_ab.min = std.algorithm.comparison.min(T...)(T args) if (T.length >= 2 && !is(CommonType!T == void))

Iterates the passed arguments and returns the minimum value.

@paramargs The values to select the minimum from. At least two arguments must be passed, and they must be comparable with <.@returnsThe minimum of the passed-in values. The type of the returned value is the type among the passed arguments that is able to store the smallest value. If at least one of the arguments is NaN, the result is an unspecified value. See minElement for examples on how to cope with NaNs.@seeminElement
min
;
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) gui_ab.to = std.conv.to(T)

The to template converts a value from one type to another. The source type is deduced and the target type must be specified, for example the expression to`!int(42.0)` converts the number 42 from `double` to `int`. The conversion is "safe", i.e., it checks for overflow; to!int(4.2e10) would throw the ConvOverflowException exception. Overflow checks are only inserted when necessary, e.g., ``to!double(42) does not do any checking because any int fits in a double.

Conversions from string to numeric types differ from the C equivalents atoi() and atol() by checking for overflow and not allowing whitespace.

For conversion of strings to signed types, the grammar recognized is: Integer: Sign UnsignedInteger UnsignedInteger Sign: + -

For conversion to unsigned types, the grammar recognized is: UnsignedInteger: DecimalDigit DecimalDigit UnsignedInteger

to
;
import
(package) std
std
.
(package) std.digest
digest
.
(module) std.digest.md

Computes MD5 hashes of arbitrary data. MD5 hashes are 16 byte quantities that are like a checksum or CRC, but are more robust.

Category Functions

| Template API | MD5 |

| OOP API | MD5Digest |

| Helpers | md5Of |

This module conforms to the APIs defined in std.digest. To understand the differences between the template and the OOP API, see std.digest.

This module publicly imports std.digest and can be used as a stand-alone module.

CTFE

Digests do not work in CTFE

References

Wikipedia on MD5

Source

std/digest/md.d

Examples

//Template API
import std.digest.md;

//Feeding data
ubyte[1024] data;
MD5 md5;
md5.start();
md5.put(data[]);
md5.start(); //Start again
md5.put(data[]);
auto hash = md5.finish();
//OOP API
import std.digest.md;

auto md5 = new MD5Digest();
ubyte[] hash = md5.digest("abc");
assert(toHexString(hash) == "900150983CD24FB0D6963F7D28E17F72");

//Feeding data
ubyte[1024] data;
md5.put(data[]);
md5.reset(); //Start again
md5.put(data[]);
hash = md5.finish();
@licenseBoost License 1.0.@authors

Piotr Szturmaj, Kai Nacke, Johannes Pfau

The routines and algorithms are derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm.

md
:
(alias template) gui_ab.md5Of = std.digest.md.md5Of(T...)(T data)

This is a convenience alias for digest using the MD5 implementation.

md5Of
,
(alias template) gui_ab.toHexString = std.digest.toHexString(Order order = Order.increasing, ulong num, LetterCase letterCase = LetterCase.upper)(const ubyte[num] digest)

Used to convert a hash value (a static or dynamic array of ubytes) to a string. Can be used with the OOP and with the template API.

The additional order parameter can be used to specify the order of the input data. By default the data is processed in increasing order, starting at index 0. To process it in the opposite order, pass Order.decreasing as a parameter.

The additional letterCase parameter can be used to specify the case of the output data. By default the output is in upper case. To change it to the lower case pass LetterCase.lower as a parameter.

Note

The function overloads returning a string allocate their return values using the GC. The versions returning static arrays use pass-by-value for the return value, effectively avoiding dynamic allocation.

toHexString
;
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) gui_ab.exists = std.file.exists(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)

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
,
(alias template) gui_ab.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.

@paramname The path to the file.@returnstrue if name specifies a file@throwsFileException if the given file does not exist.
isFile
,
(alias) gui_ab.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.

@parampathname the full path of the directory to create@throwsFileException on error.
mkdirRecurse
,
(alias template) gui_ab.read = std.file.read(R)(R name, size_t upTo = size_t.max) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)

Read entire contents of file name and returns it as an untyped array. If the file size is larger than upTo, only upTo bytes are read.

@paramname string or range of characters representing the file name@paramupTo if present, the maximum number of bytes to read@returnsUntyped array of bytes read.@throwsFileException on error.@seereadText for reading and validating a text file.
read
,
(alias template) gui_ab.remove = std.file.remove(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)

Delete file name.

@paramname string or range of characters representing the file name@throwsFileException on error.
remove
;
import
(package) std
std
.
(module) std.format

This package provides string formatting functionality using printf style format strings.

Submodule Function Name Description
package
format
Converts its arguments according to a format string into a string.

| package | sformat | Converts its arguments according to a format string into a buffer. |

| package | FormatException | Signals a problem while formatting. |

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

| write | formatValue | Formats a value of any type according to a format specifier and writes the result to an output range. |

| read | formattedRead | Reads an input range according to a format string and stores the read values into its arguments. |

| read | unformatValue | Reads a value from the given input range and converts it according to a format specifier. |

| spec | FormatSpec | A general handler for format strings. |

| spec | singleSpec | Helper function that returns a FormatSpec for a single format specifier. |

Limitation

This package does not support localization, but adheres to the rounding mode of the floating point unit, if available.

Format Strings

The functions contained in this package use format strings. A format string describes the layout of another string for reading or writing purposes. A format string is composed of normal text interspersed with format specifiers. A format specifier starts with a percentage sign '%', optionally followed by one or more parameters and ends with a format indicator. A format indicator may be a simple format character or a compound indicator.

Format strings are composed according to the following grammar:

FormatString: FormatStringItem FormatString FormatStringItem: Character FormatSpecifier FormatSpecifier: '%' Parameters FormatIndicator

FormatIndicator: FormatCharacter CompoundIndicator FormatCharacter: see remark below CompoundIndicator: '(' FormatString '%)' '(' FormatString '%|' Delimiter '%)' Delimiter empty Character Delimiter

Parameters: Position Flags Width Precision Separator Position: empty Integer '$'** *Integer* **':'** *Integer* **'$' Integer ':' '$'** *Flags*: *empty* *Flag* *Flags* *Flag*: **'-'**|**'+'**|**'&nbsp;'**|**'0'**|**'#'**|**'='** *Width*: *OptionalPositionalInteger* *Precision*: *empty* **'.'** *OptionalPositionalInteger* *Separator*: *empty* **','** *OptionalInteger* **','** *OptionalInteger* **'?'** *OptionalInteger*: *empty* *Integer* **'*'** *OptionalPositionalInteger*: *OptionalInteger* **'*'** *Integer* **'$'

Character '%%' AnyCharacterExceptPercent Integer: NonZeroDigit Digits Digits: empty Digit Digits NonZeroDigit: '1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9' Digit: '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'

Note

FormatCharacter is unspecified. It can be any character that has no other purpose in this grammar, but it is recommended to assign (lower- and uppercase) letters.

Note

The Parameters of a CompoundIndicator are currently limited to a '-' flag.

Format Indicator

The format indicator can either be a single character or an expression surrounded by '%(' and '%)'. It specifies the basic manner in which a value will be formatted and is the minimum requirement to format a value.

The following characters can be used as format characters:

FormatCharacter Semantics
's'
To be formatted in a human readable format.
Can be used with all types.
'c'
To be formatted as a character.
'd'
To be formatted as a signed decimal integer.
'u'
To be formatted as a decimal image of the underlying bit representation.
'b'
To be formatted as a binary image of the underlying bit representation.
'o'
To be formatted as an octal image of the underlying bit representation.
'x' / 'X'
To be formatted as a hexadecimal image of the underlying bit representation.
'e' / 'E'
To be formatted as a real number in decimal scientific notation.
'f' / 'F'
To be formatted as a real number in decimal natural notation.
'g' / 'G'
To be formatted as a real number in decimal short notation.
Depending on the number, a scientific notation or
a natural notation is used.
'a' / 'A'
To be formatted as a real number in hexadecimal scientific notation.
'r'
To be formatted as raw bytes.
The output may not be printable and depends on endianness.

The compound indicator can be used to describe compound types like arrays or structs in more detail. A compound type is enclosed within '%(' and '%)'. The enclosed sub-format string is applied to individual elements. The trailing portion of the sub-format string following the specifier for the element is interpreted as the delimiter, and is therefore omitted following the last element. The '%|' specifier may be used to explicitly indicate the start of the delimiter, so that the preceding portion of the string will be included following the last element.

The format string inside of the compound indicator should contain exactly one format specifier (two in case of associative arrays), which specifies the formatting mode of the elements of the compound type. This format specifier can be a compound indicator itself.

Note

Inside a compound indicator, strings and characters are escaped automatically. To avoid this behavior, use "%-(" instead of "%(".

Flags

There are several flags that affect the outcome of the formatting.

Flag Semantics
'-'
When the formatted result is shorter than the value
given by the width parameter, the output is left
justified. Without the '-' flag, the output remains
right justified.

There are two exceptions where the '-' flag has a different meaning: (1) with 'r' it denotes to use little endian and (2) in case of a compound indicator it means that no special handling of the members is applied. | | '=' | When the formatted result is shorter than the value given by the width parameter, the output is centered. If the central position is not possible it is moved slightly to the right. In this case, if '-' flag is present in addition to the '=' flag, it is moved slightly to the left. | | '+'&nbsp;/&nbsp;*'&nbsp;'* | Applies to numerical values. By default, positive numbers are not formatted to include the + sign. With one of these two flags present, positive numbers are preceded by a plus sign or a space. When both flags are present, a plus sign is used.

In case of 'r', a big endian format is used. | | '0' | Is applied to numerical values that are printed right justified. If the zero flag is present, the space left to the number is filled with zeros instead of spaces. | | '#' | Denotes that an alternative output must be used. This depends on the type to be formatted and the format character used. See the sections below for more information. |

Width, Precision and Separator

The width parameter specifies the minimum width of the result.

The meaning of precision depends on the format indicator. For integers it denotes the minimum number of digits printed, for real numbers it denotes the number of fractional digits and for strings and compound types it denotes the maximum number of elements that are included in the output.

A separator is used for formatting numbers. If it is specified, the output is divided into chunks of three digits, separated by a ','. The number of digits in a chunk can be given explicitly by providing a number or a ''* after the ','.

In all three cases the number of digits can be replaced by a ''*. In this scenario, the next argument is used as the number of digits. If the argument is a negative number, the precision and separator parameters are considered unspecified. For width, the absolute value is used and the '-' flag is set.

The separator can also be followed by a '?'. In that case, an additional argument is used to specify the symbol that should be used to separate the chunks.

Position

By default, the arguments are processed in the provided order. With the position parameter it is possible to address arguments directly. It is also possible to denote a series of arguments with two numbers separated by ':', that are all processed in the same way. The second number can be omitted. In that case the series ends with the last argument.

It's also possible to use positional arguments for width, precision and separator by adding a number and a '$' after the ''*.

Types

This section describes the result of combining types with format characters. It is organized in 2 subsections: a list of general information regarding the formatting of types in the presence of format characters and a table that contains details for every available combination of type and format character.

When formatting types, the following rules apply:

  • If the format character is upper case, the resulting string will be formatted using upper case letters.

  • The default precision for floating point numbers is 6 digits.

  • Rounding of floating point numbers adheres to the rounding mode of the floating point unit, if available.

  • The floating point values NaN and Infinity are formatted as nan and inf, possibly preceded by '+' or '-' sign.

  • Formatting reals is only supported for 64 bit reals and 80 bit reals. All other reals are cast to double before they are formatted. This will cause the result to be inf for very large numbers.

  • Characters and strings formatted with the 's' format character inside of compound types are surrounded by single and double quotes and unprintable characters are escaped. To avoid this, a '-' flag can be specified for the compound specifier (e.g. "%-(%s%)" instead of "%(%s%)" ).

  • Structs, unions, classes and interfaces are formatted by calling a toString method if available. See module std.format.write for more details.

  • Only part of these combinations can be used for reading. See module std.format.read for more detailed information.

This table contains descriptions for every possible combination of type and format character:

<th scope="col" width="20%">Type</th> <th scope="col" width="20%">Format Character</th> Formatted as...
<td rowspan="1">null</td> 's'
null

|<td rowspan="3">bool</td> 's' | false or true |

| 'b', 'd', 'o', 'u', 'x', 'X' | As the integrals 0 or 1 with the same format character.

Please note, that 'o' and 'x' with '#' flag might produce unexpected results due to special handling of the value 0. |

| 'r' | \0 or \1 |

|<td rowspan="4">Integral</td> 's', 'd' | A signed decimal number. The '#' flag is ignored. |

| 'b', 'o', 'u', 'x', 'X' | An unsigned binary, decimal, octal or hexadecimal number.

In case of 'o' and 'x', the '#' flag denotes that the number must be preceded by 0 and 0x, with the exception of the value 0, where this does not apply. For 'b' and 'u' the '#' flag has no effect. |

| 'e', 'E', 'f', 'F', 'g', 'G', 'a', 'A' | As a floating point value with the same specifier.

Default precision is large enough to add all digits of the integral value.

In case of 'a' and 'A', the integral digit can be any hexadecimal digit. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="5">Floating Point</td> 'e', 'E' | Scientific notation: Exactly one integral digit followed by a dot and fractional digits, followed by the exponent. The exponent is formatted as 'e' followed by a '+' or '-' sign, followed by at least two digits.

When there are no fractional digits and the '#' flag is not present, the dot is omitted. |

| 'f', 'F' | Natural notation: Integral digits followed by a dot and fractional digits.

When there are no fractional digits and the '#' flag is not present, the dot is omitted.

Please note: the difference between 'f' and 'F' is only visible for NaN and Infinity. |

| 's', 'g', 'G' | Short notation: If the absolute value is larger than 10 ^^ precision or smaller than 0.0001, the scientific notation is used. If not, the natural notation is applied.

In both cases precision denotes the count of all digits, including the integral digits. Trailing zeros (including a trailing dot) are removed.

If '#' flag is present, trailing zeros are not removed. |

| 'a', 'A' | Hexadecimal scientific notation: 0x followed by 1 (or 0 in case of value zero or denormalized number) followed by a dot, fractional digits in hexadecimal notation and an exponent. The exponent is build by p, followed by a sign and the exponent in decimal notation.

When there are no fractional digits and the '#' flag is not present, the dot is omitted. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="3">Character</td> 's', 'c' | As the character.

Inside of a compound indicator 's' is treated differently: The character is surrounded by single quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a '-' flag (e.g. "%-(%s%)"). |

| 'b', 'd', 'o', 'u', 'x', 'X' | As the integral that represents the character. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="3">String</td> 's' | The sequence of characters that form the string.

Inside of a compound indicator the string is surrounded by double quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a '-' flag (e.g. "%-(%s%)"). |

| 'r' | The sequence of characters, each formatted with 'r'. |

| compound | As an array of characters. |

|<td rowspan="3">Array</td> 's' | When the elements are characters, the array is formatted as a string. In all other cases the array is surrounded by square brackets and the elements are separated by a comma and a space. If the elements are strings, they are surrounded by double quotes and non printable characters are escaped. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="2">Associative Array</td> 's' | As a sequence of the elements in unpredictable order. The output is surrounded by square brackets. The elements are separated by a comma and a space. The elements are formatted as key:value. |

| compound | As a sequence of the elements in unpredictable order. Each element is formatted according to the specifications given inside of the compound specifier. The first specifier is used for formatting the key and the second specifier is used for formatting the value. The order can be changed with positional arguments. For example "%(%2$s (%1$s), %)" will write the value, followed by the key in parenthesis. |

|<td rowspan="2">Enum</td> 's' | The name of the value. If the name is not available, the base value is used, preceeded by a cast. |

| All, but 's' | Enums can be formatted with all format characters that can be used with the base value. In that case they are formatted like the base value. |

|<td rowspan="3">Input Range</td> 's' | When the elements of the range are characters, they are written like a string. In all other cases, the elements are enclosed by square brackets and separated by a comma and a space. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="1">Struct</td> 's' | When the struct has neither an applicable toString nor is an input range, it is formatted as follows: StructType(field1, field2, ...). |

|<td rowspan="1">Class</td> 's' | When the class has neither an applicable toString nor is an input range, it is formatted as the fully qualified name of the class. |

|<td rowspan="1">Union</td> 's' | When the union has neither an applicable toString nor is an input range, it is formatted as its base name. |

|<td rowspan="2">Pointer</td> 's' | A null pointer is formatted as 'null'. All other pointers are formatted as hexadecimal numbers with the format character 'X'. |

| 'x', 'X' | Formatted as a hexadecimal number. |

|<td rowspan="3">SIMD vector</td> 's' | The array is surrounded by square brackets and the elements are separated by a comma and a space. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="1">Delegate</td> 's', 'r', compound | As the .stringof of this delegate treated as a string.

Please note: The implementation is currently buggy and its use is discouraged. |

Source

std/format/package.d

Examples

Simple use:

// Easiest way is to use `%s` everywhere:
assert(format("I got %s %s for %s euros.", 30, "eggs", 5.27) == "I got 30 eggs for 5.27 euros.");

// Other format characters provide more control:
assert(format("I got %b %(%X%) for %f euros.", 30, "eggs", 5.27) == "I got 11110 65676773 for 5.270000 euros.");

Compound specifiers allow formatting arrays and other compound types:

/*
The trailing end of the sub-format string following the specifier for
each item is interpreted as the array delimiter, and is therefore
omitted following the last array item:
 */
    assert(format("My items are %(%s %).", [1,2,3]) == "My items are 1 2 3.");
    assert(format("My items are %(%s, %).", [1,2,3]) == "My items are 1, 2, 3.");

/*
The "%|" delimiter specifier may be used to indicate where the
delimiter begins, so that the portion of the format string prior to
it will be retained in the last array element:
 */
    assert(format("My items are %(-%s-%|, %).", [1,2,3]) == "My items are -1-, -2-, -3-.");

/*
These compound format specifiers may be nested in the case of a
nested array argument:
 */
    auto mat = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]];

    assert(format("%(%(%d %) - %)", mat), "1 2 3 - 4 5 6 - 7 8 9");
    assert(format("[%(%(%d %) - %)]", mat), "[1 2 3 - 4 5 6 - 7 8 9]");
    assert(format("[%([%(%d %)]%| - %)]", mat), "[1 2 3] - [4 5 6] - [7 8 9]");

/*
Strings and characters are escaped automatically inside compound
format specifiers. To avoid this behavior, use "%-(" instead of "%(":
 */
    assert(format("My friends are %s.", ["John", "Nancy"]) == `My friends are ["John", "Nancy"].`);
    assert(format("My friends are %(%s, %).", ["John", "Nancy"]) == `My friends are "John", "Nancy".`);
    assert(format("My friends are %-(%s, %).", ["John", "Nancy"]) == `My friends are John, Nancy.`);

Using parameters:

// Flags can be used to influence to outcome:
assert(format("%g != %+#g", 3.14, 3.14) == "3.14 != +3.14000");

// Width and precision help to arrange the formatted result:
assert(format(">%10.2f<", 1234.56789) == ">   1234.57<");

// Numbers can be grouped:
assert(format("%,4d", int.max) == "21,4748,3647");

// It's possible to specify the position of an argument:
assert(format("%3$s %1$s", 3, 17, 5) == "5 3");

Providing parameters as arguments:

// Width as argument
assert(format(">%*s<", 10, "abc") == ">       abc<");

// Precision as argument
assert(format(">%.*f<", 5, 123.2) == ">123.20000<");

// Grouping as argument
assert(format("%,*d", 1, int.max) == "2,1,4,7,4,8,3,6,4,7");

// Grouping separator as argument
assert(format("%,3?d", '_', int.max) == "2_147_483_647");

// All at once
assert(format("%*.*,*?d", 20, 15, 6, '/', int.max) == "   000/002147/483647");
@copyrightCopyright The D Language Foundation 2000-2021.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, and Kenji Hara
format
:
(alias template) gui_ab.format = std.format.format(Char, Args...)(in Char[] fmt, Args args) if (isSomeChar!Char)

Converts its arguments according to a format string into a string.

The second version of format takes the format string as template argument. In this case, it is checked for consistency at compile-time and produces slightly faster code, because the length of the output buffer can be estimated in advance.

@paramfmt a format string@paramargs a variadic list of arguments to be formatted@paramChar character type of fmt@paramArgs a variadic list of types of the arguments@returnsThe formatted string.@throwsA FormatException if formatting did not succeed.@seesformat for a variant, that tries to avoid garbage collection.
format
;
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) gui_ab.absolutePath = string std.path.absolutePath(return scope const(string) path, lazy string base = getcwd()) pure @safe

Transforms path into an absolute path.

The following algorithm is used:

  1. If path is empty, return null.

  2. If path is already absolute, return it.

  3. Otherwise, append path to base and return the result. If base is not specified, the current working directory is used.

The function allocates memory if and only if it gets to the third stage of this algorithm.

Note that absolutePath will not normalize .. segments. Use buildNormalizedPath(absolutePath(path)) if that is desired.

@parampath the relative path to transform@parambase the base directory of the relative path@returnsstring of transformed path@throwsException if the specified base directory is not absolute.@seeasAbsolutePath which does not allocate
absolutePath
,
(alias template) gui_ab.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 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.

@paramsegments An input range of segments to assemble the path from.@returnsThe 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
:
(struct) std.process.Config

Options that control the behaviour of process creation functions in this module. Most options only apply to spawnProcess and spawnShell.

Example

auto logFile = File("myapp_error.log", "w");

// Start program, suppressing the console window (Windows only),
// redirect its error stream to logFile, and leave logFile open
// in the parent process as well.
auto pid = spawnProcess("myapp", stdin, stdout, logFile,
                        Config.retainStderr | Config.suppressConsole);
scope(exit)
{
    auto exitCode = wait(pid);
    logFile.writeln("myapp exited with code ", exitCode);
    logFile.close();
}
Config
,
(class) std.process.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
,
(alias) gui_ab.spawnProcess = std.process.Pid std.process.spawnProcess(scope const(char[])[] args, std.stdio.File stdin = makeGlobal(), std.stdio.File stdout = makeGlobal(), std.stdio.File stderr = makeGlobal(), const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), scope const(char[]) workDir = null) @safe

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. It is recommended to always call wait on the returned Pid unless the process was spawned with Config.detached flag, as detailed in the documentation for wait.

Command line

There are four overloads of this function. The first two take an array of strings, args, which should contain the program name as the zeroth element and any command-line arguments in subsequent elements. The third and fourth versions are included for convenience, and may be used when there are no command-line arguments. They take a single string, program, which specifies the program name.

Unless a directory is specified in args[0] or program, spawnProcess will search for the program in a platform-dependent manner. On POSIX systems, it will look for the executable in the directories listed in the PATH environment variable, in the order they are listed. On Windows, it will search for the executable in the following sequence:

  1. The directory from which the application loaded.

  2. The current directory for the parent process.

  3. The 32-bit Windows system directory.

  4. The 16-bit Windows system directory.

  5. The Windows directory.

  6. The directories listed in the PATH environment variable.

// Run an executable called "prog" located in the current working
// directory:
auto pid = spawnProcess("./prog");
scope(exit) wait(pid);
// We can do something else while the program runs.  The scope guard
// ensures that the process is waited for at the end of the scope.
...

// Run DMD on the file "myprog.d", specifying a few compiler switches:
auto dmdPid = spawnProcess(["dmd", "-O", "-release", "-inline", "myprog.d" ]);
if (wait(dmdPid) != 0)
    writeln("Compilation failed!");

Environment variables

By default, the child process inherits the environment of the parent process, along with any additional variables specified in the env parameter. If the same variable exists in both the parent's environment and in env, the latter takes precedence.

If the Config.newEnv flag is set in config, the child process will not inherit the parent's environment. Its entire environment will then be determined by env.

wait(spawnProcess("myapp", ["foo" : "bar"], Config.newEnv));

Standard streams

The optional arguments stdin, stdout and stderr may be used to assign arbitrary File objects as the standard input, output and error streams, respectively, of the child process. The former must be opened for reading, while the latter two must be opened for writing. The default is for the child process to inherit the standard streams of its parent.

// Run DMD on the file myprog.d, logging any error messages to a
// file named errors.log.
auto logFile = File("errors.log", "w");
auto pid = spawnProcess(["dmd", "myprog.d"],
                        std.stdio.stdin,
                        std.stdio.stdout,
                        logFile);
if (wait(pid) != 0)
    writeln("Compilation failed. See errors.log for details.");

Note that if you pass a File object that is not one of the standard input/output/error streams of the parent process, that stream will by default be closed in the parent process when this function returns. See the Config documentation below for information about how to disable this behaviour.

Beware of buffering issues when passing File objects to spawnProcess. The child process will inherit the low-level raw read/write offset associated with the underlying file descriptor, but it will not be aware of any buffered data. In cases where this matters (e.g. when a file should be aligned before being passed on to the child process), it may be a good idea to use unbuffered streams, or at least ensure all relevant buffers are flushed.

@paramargs An array which contains the program name as the zeroth element and any command-line arguments in the following elements.@paramstdin The standard input stream of the child process. This can be any File that is opened for reading. By default the child process inherits the parent's input stream.@paramstdout The standard output stream of the child process. This can be any File that is opened for writing. By default the child process inherits the parent's output stream.@paramstderr The standard error stream of the child process. This can be any File that is opened for writing. By default the child process inherits the parent's error stream.@paramenv Additional environment variables for the child process.@paramconfig Flags that control process creation. See Config for an overview of available flags.@paramworkDir The working directory for the new process. By default the child process inherits the parent's working directory.@returnsA Pid object that corresponds to the spawned process.@throws

ProcessException on failure to start the process.

StdioException on failure to pass one of the streams to the child process (Windows only).

RangeError if args is empty.

spawnProcess
,
(alias) gui_ab.wait = int std.process.wait(std.process.Pid pid) @safe

Waits for the process associated with pid to terminate, and returns its exit status.

In general one should always wait for child processes to terminate before exiting the parent process unless the process was spawned as detached (that was spawned with Config.detached flag). Otherwise, they may become "zombies" – processes that are defunct, yet still occupy a slot in the OS process table. You should not and must not wait for detached processes, since you don't own them.

If the process has already terminated, this function returns directly. The exit code is cached, so that if wait() is called multiple times on the same Pid it will always return the same value.

POSIX specific

If the process is terminated by a signal, this function returns a negative number whose absolute value is the signal number. Since POSIX restricts normal exit codes to the range 0-255, a negative return value will always indicate termination by signal. Signal codes are defined in the core.sys.posix.signal module (which corresponds to the signal.h POSIX header).

Example

See the spawnProcess documentation.

@throwsProcessException on failure or on attempt to wait for detached process.@seetryWait, for a non-blocking function.
wait
;
import
(package) std
std
.
(module) std.stdio
Category Symbols
File handles _popen File isFileHandle openNetwork stderr stdin stdout
Reading chunks lines readf readfln readln
Writing toFile write writef writefln writeln
Misc KeepTerminator LockType StdioException

Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio is publically imported when importing std.stdio.

There are three layers of I/O:

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

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

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

Source

std/stdio.d

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Alex Rønne Petersen
stdio
: stderr,
(alias template) gui_ab.writefln = std.stdio.writefln(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))

Equivalent to writef(fmt, args, '\n').

writefln
,
(alias template) gui_ab.writeln = std.stdio.writeln(T...)(T args)

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
;
import
(package) sparkles
sparkles
.
(package) sparkles.core_cli
core_cli
.
(module) sparkles.core_cli.args
args
:
(struct) sparkles.core_cli.help_formatting.HelpInfo
HelpInfo
,
(struct) sparkles.core_cli.args.uda.Option
Option
,
(alias template) gui_ab.parseCli = sparkles.core_cli.args.internal.parseCli(Cli)(string[] argv, HelpInfo helpInfo = HelpInfo.init, EnvLookup env = null)
parseCli
,
(alias) gui_ab.reportCliError = int sparkles.core_cli.args.internal.reportCliError(in sparkles.core_cli.args.error.CliError e)

Reports a failed parse and returns the exit code the program should use.

A help request is a failure in the Expected sense but a success to the user, and carries exitCode == 0 to say so — returning this value is what keeps --help from looking like an error to a shell.

For a program whose commands have run methods, prefer runCli, which calls this. This is the entry point for a program that parses into a struct and then does its own work.

reportCliError
;
/// CLI surface (parsed by `sparkles:core-cli`, per the D-tooling guideline). struct
(struct) gui_ab.Params

CLI surface (parsed by sparkles:core-cli, per the D-tooling guideline).

Params
{ @(
(struct) sparkles.core_cli.args.uda.Option
Option
("old|o", description: "The baseline hue binary"))
(alias) object.string = string
string
(field) string gui_ab.Params.old
old
;
@(
(struct) sparkles.core_cli.args.uda.Option
Option
("new|n", description: "The changed hue binary"))
(alias) object.string = string
string
(field) string gui_ab.Params.new_
new_
= "apps/hue/build/hue";
@(
(struct) sparkles.core_cli.args.uda.Option
Option
("file|f", description: "The file to open in the viewer"))
(alias) object.string = string
string
(field) string gui_ab.Params.file
file
;
@(
(struct) sparkles.core_cli.args.uda.Option
Option
("args", description: "Argument template; {file} is substituted"))
(alias) object.string = string
string
(field) string gui_ab.Params.extraArgs
extraArgs
= "view {file} --gui";
@(
(struct) sparkles.core_cli.args.uda.Option
Option
("display|d", description: "X display number to pin Xvfb to"))
int
(field) int gui_ab.Params.display
display
= 99;
@(
(struct) sparkles.core_cli.args.uda.Option
Option
("screen", description: "Xvfb screen geometry"))
(alias) object.string = string
string
(field) string gui_ab.Params.screen
screen
= "1600x1000x24";
@(
(struct) sparkles.core_cli.args.uda.Option
Option
("font-size", description: "Pixel font size; pins the capture"))
int
(field) int gui_ab.Params.fontSize
fontSize
= 18;
@(
(struct) sparkles.core_cli.args.uda.Option
Option
("frame", description: "Which frame to capture"))
int
(field) int gui_ab.Params.frame
frame
= 20;
@(
(struct) sparkles.core_cli.args.uda.Option
Option
("pointer|p", description: "Park the pointer at 'x,y' (device px)"))
(alias) object.string = string
string
(field) string gui_ab.Params.pointer
pointer
;
@(
(struct) sparkles.core_cli.args.uda.Option
Option
("top|t", description: "Initial scroll line; brings a fence border "
~ "or a bar into frame")) int
(field) int gui_ab.Params.top
top
= -1;
@(
(struct) sparkles.core_cli.args.uda.Option
Option
("runs|r", description: "Captures per side; they must all agree"))
int
(field) int gui_ab.Params.runs
runs
= 2;
@(
(struct) sparkles.core_cli.args.uda.Option
Option
("out|O", description: "Directory for the captured PNGs"))
(alias) object.string = string
string
(field) string gui_ab.Params.outDir
outDir
= "/tmp/hue-gui-ab";
} int
int D main(string[] rawArgs)
main
(
(alias) object.string = string
string
[]
(parameter) string[] rawArgs
rawArgs
)
{ auto
(local variable) sparkles.base.expected.Expected!(Params, CliError, Abort) parsed
parsed
=
sparkles.base.expected.Expected!(Params, CliError, Abort) sparkles.core_cli.args.internal.parseCli!(gui_ab.Params)(string[] argv, sparkles.core_cli.help_formatting.HelpInfo helpInfo = HelpInfo(null, null, null), string delegate(string name) @safe env = cast(string delegate(string name) @safe)null) @system
parseCli
!
(struct) gui_ab.Params

CLI surface (parsed by sparkles:core-cli, per the D-tooling guideline).

Params
(
(parameter) string[] rawArgs
rawArgs
,
(struct) sparkles.core_cli.help_formatting.HelpInfo
HelpInfo
("gui-ab",
"A/B two hue builds by their rendered window: `HUE_GUI_SCREENSHOT` " ~ "under a pinned Xvfb, captured twice a side so a race cannot be " ~ "mistaken for a difference.", null)); if (!
(local variable) sparkles.base.expected.Expected!(Params, CliError, Abort) parsed
parsed
)
return
int sparkles.core_cli.args.internal.reportCliError(in sparkles.core_cli.args.error.CliError e)

Reports a failed parse and returns the exit code the program should use.

A help request is a failure in the Expected sense but a success to the user, and carries exitCode == 0 to say so — returning this value is what keeps --help from looking like an error to a shell.

For a program whose commands have run methods, prefer runCli, which calls this. This is the entry point for a program that parses into a struct and then does its own work.

reportCliError
(
(local variable) sparkles.base.expected.Expected!(Params, CliError, Abort) parsed
parsed
.
inout(sparkles.core_cli.args.error.CliError) sparkles.base.expected.Expected!(gui_ab.Params, sparkles.core_cli.args.error.CliError, sparkles.base.expected.Abort).error() inout pure nothrow @nogc @property ref @safe

Returns the error value. May only be called when hasValue returns false.

If there is no error value, it calls hook's onAccessEmptyError.

It returns E.init when hook doesn't provide onAccessEmptyError.

Note

Error is returned by reference only when hook provides onAccessEmptyError. Otherwise the E.init fallback forces it to be returned by value (a copy).

error
);
auto
(local variable) gui_ab.Params p
p
=
(local variable) sparkles.base.expected.Expected!(Params, CliError, Abort) parsed
parsed
.
inout(gui_ab.Params) sparkles.base.expected.Expected!(gui_ab.Params, sparkles.core_cli.args.error.CliError, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safe

Returns the expected value if there is one.

With default Abort hook, it asserts when there is no value. It calls hook's onAccessEmptyValue otherwise.

It returns T.init when hook doesn't provide onAccessEmptyValue.

Note

Value is returned by reference only when hook provides onAccessEmptyValue. Otherwise the T.init fallback forces it to be returned by value (a copy).

value
;
if (!
bool gui_ab.onPath(string tool)
onPath
("xvfb-run"))
{ stderr.
std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @system
writeln
("gui-ab: `xvfb-run` is not on PATH — enter `nix develop`.");
return 2; } if (
(local variable) gui_ab.Params p
p
.
(field) string gui_ab.Params.old
old
.
(field) ulong string.length
length
== 0)
{ stderr.
std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @system
writeln
("gui-ab: --old is required (build the baseline first "
~ "and copy the binary aside)."); return 2; } if (
(local variable) gui_ab.Params p
p
.
(field) string gui_ab.Params.file
file
.
(field) ulong string.length
length
== 0 || !
(local variable) gui_ab.Params p
p
.
(field) string gui_ab.Params.file
file
.
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
)
{ stderr.
std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @system
writeln
("gui-ab: --file must name a file to open.");
return 2; } foreach (
(parameter) string bin
bin
; [
(local variable) gui_ab.Params p
p
.
(field) string gui_ab.Params.old
old
,
(local variable) gui_ab.Params p
p
.
(field) string gui_ab.Params.new_
new_
])
if (!
(local variable) string bin
bin
.
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) string bin
bin
.
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
)
{ stderr.
std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @system
writefln
("gui-ab: no such binary: %s",
(local variable) string bin
bin
);
return 2; } // Guard two: one build compared against itself proves nothing, and is the // easy mistake because both configs write to the same target path. const
(local variable) const(ubyte[]) oldBytes
oldBytes
= cast(const(ubyte)[])
void[] std.file.read!string(string name, ulong upTo = 18446744073709551615LU) @safe

Read entire contents of file name and returns it as an untyped array. If the file size is larger than upTo, only upTo bytes are read.

Examples

import std.utf : byChar;
scope(exit)
{
    assert(exists(deleteme));
    remove(deleteme);
}

std.file.write(deleteme, "1234"); // deleteme is the name of a temporary file
assert(read(deleteme, 2) == "12");
assert(read(deleteme.byChar) == "1234");
assert((cast(const(ubyte)[])read(deleteme)).length == 4);
@paramname string or range of characters representing the file name@paramupTo if present, the maximum number of bytes to read@returnsUntyped array of bytes read.@throwsFileException on error.@seereadText for reading and validating a text file.
read
(
(local variable) gui_ab.Params p
p
.
(field) string gui_ab.Params.old
old
);
const
(local variable) const(ubyte[]) newBytes
newBytes
= cast(const(ubyte)[])
void[] std.file.read!string(string name, ulong upTo = 18446744073709551615LU) @safe

Read entire contents of file name and returns it as an untyped array. If the file size is larger than upTo, only upTo bytes are read.

Examples

import std.utf : byChar;
scope(exit)
{
    assert(exists(deleteme));
    remove(deleteme);
}

std.file.write(deleteme, "1234"); // deleteme is the name of a temporary file
assert(read(deleteme, 2) == "12");
assert(read(deleteme.byChar) == "1234");
assert((cast(const(ubyte)[])read(deleteme)).length == 4);
@paramname string or range of characters representing the file name@paramupTo if present, the maximum number of bytes to read@returnsUntyped array of bytes read.@throwsFileException on error.@seereadText for reading and validating a text file.
read
(
(local variable) gui_ab.Params p
p
.
(field) string gui_ab.Params.new_
new_
);
if (
(local variable) const(ubyte[]) oldBytes
oldBytes
==
(local variable) const(ubyte[]) newBytes
newBytes
)
{ stderr.
std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @system
writeln
("gui-ab: the two binaries are byte-identical, so this "
~ "comparison could not have detected anything. Rebuild one."); return 2; }
void std.stdio.writefln!(char, string, ulong, string, ulong)(in char[] fmt, string __param_1, ulong __param_2, string __param_3, ulong __param_4) @safe

Equivalent to writef(fmt, args, '\n').

writefln
("binaries differ: old %s (%s bytes), new %s (%s bytes)",
string gui_ab.digest(in ubyte[] bytes)
digest
(
(local variable) const(ubyte[]) oldBytes
oldBytes
),
(local variable) const(ubyte[]) oldBytes
oldBytes
.
(field) ulong const(ubyte[]).length
length
,
string gui_ab.digest(in ubyte[] bytes)
digest
(
(local variable) const(ubyte[]) newBytes
newBytes
),
(local variable) const(ubyte[]) newBytes
newBytes
.
(field) ulong const(ubyte[]).length
length
);
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) gui_ab.Params p
p
.
(field) string gui_ab.Params.outDir
outDir
);
ubyte[]
(local variable) ubyte[] oldPng
oldPng
,
(local variable) ubyte[] newPng
newPng
;
if (!
bool gui_ab.capture(in gui_ab.Params p, string bin, string side, out ubyte[] bytes)

Captures bin ``p.runs times, failing unless every run agrees with itself.

capture
(
(local variable) gui_ab.Params p
p
,
(local variable) gui_ab.Params p
p
.
(field) string gui_ab.Params.old
old
, "old",
(local variable) ubyte[] oldPng
oldPng
))
return 2; if (!
bool gui_ab.capture(in gui_ab.Params p, string bin, string side, out ubyte[] bytes)

Captures bin ``p.runs times, failing unless every run agrees with itself.

capture
(
(local variable) gui_ab.Params p
p
,
(local variable) gui_ab.Params p
p
.
(field) string gui_ab.Params.new_
new_
, "new",
(local variable) ubyte[] newPng
newPng
))
return 2; if (
(local variable) ubyte[] oldPng
oldPng
==
(local variable) ubyte[] newPng
newPng
)
{
void std.stdio.writefln!(char, ulong, string)(in char[] fmt, ulong __param_1, string __param_2) @safe

Equivalent to writef(fmt, args, '\n').

writefln
("identical: %s bytes, %s",
(local variable) ubyte[] oldPng
oldPng
.
(field) ulong ubyte[].length
length
,
string gui_ab.digest(in ubyte[] bytes)
digest
(
(local variable) ubyte[] oldPng
oldPng
));
return 0; }
void std.stdio.writeln!string(string __param_0) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("DRIFT: the two builds painted different windows.");
void std.stdio.writefln!(char, string, ulong, string)(in char[] fmt, string __param_1, ulong __param_2, string __param_3) @safe

Equivalent to writef(fmt, args, '\n').

writefln
(" old %s (%s bytes) -> %s",
string gui_ab.digest(in ubyte[] bytes)
digest
(
(local variable) ubyte[] oldPng
oldPng
),
(local variable) ubyte[] oldPng
oldPng
.
(field) ulong ubyte[].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) gui_ab.Params p
p
.
(field) string gui_ab.Params.outDir
outDir
, "old.png"));
void std.stdio.writefln!(char, string, ulong, string)(in char[] fmt, string __param_1, ulong __param_2, string __param_3) @safe

Equivalent to writef(fmt, args, '\n').

writefln
(" new %s (%s bytes) -> %s",
string gui_ab.digest(in ubyte[] bytes)
digest
(
(local variable) ubyte[] newPng
newPng
),
(local variable) ubyte[] newPng
newPng
.
(field) ulong ubyte[].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) gui_ab.Params p
p
.
(field) string gui_ab.Params.outDir
outDir
, "new.png"));
void gui_ab.reportPixelDiff(string oldPath, string newPath, string outDir) @system

Where the two captures actually differ, in pixels.

A byte offset into a compressed PNG says nothing about the window — one changed pixel shifts every subsequent byte — so the drift is reported as a bounding box and a count, and the differing pixels are written out as a mask. That is the difference between "something moved" and "the fence's bottom border row changed and nothing else did".

reportPixelDiff
(
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) gui_ab.Params p
p
.
(field) string gui_ab.Params.outDir
outDir
, "old.png"),
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) gui_ab.Params p
p
.
(field) string gui_ab.Params.outDir
outDir
, "new.png"),
(local variable) gui_ab.Params p
p
.
(field) string gui_ab.Params.outDir
outDir
);
return 1; } /** Where the two captures actually differ, in pixels. A byte offset into a compressed PNG says nothing about the window — one changed pixel shifts every subsequent byte — so the drift is reported as a bounding box and a count, and the differing pixels are written out as a mask. That is the difference between "something moved" and "the fence's bottom border row changed and nothing else did". */ private void
void gui_ab.reportPixelDiff(string oldPath, string newPath, string outDir) @system

Where the two captures actually differ, in pixels.

A byte offset into a compressed PNG says nothing about the window — one changed pixel shifts every subsequent byte — so the drift is reported as a bounding box and a count, and the differing pixels are written out as a mask. That is the difference between "something moved" and "the fence's bottom border row changed and nothing else did".

reportPixelDiff
(
(alias) object.string = string
string
(parameter) string oldPath
oldPath
,
(alias) object.string = string
string
(parameter) string newPath
newPath
,
(alias) object.string = string
string
(parameter) string outDir
outDir
)
@system { import
(module) raylib

raylib v6.2 - A simple and easy-to-use library to enjoy videogames programming (www.raylib.com)

FEATURES

  • NO external dependencies, all required libraries included with raylib

  • Multiplatform: Windows, Linux, macOS, FreeBSD, Web, Android, Raspberry Pi, DRM native...

  • Written in plain C code (C99) in PascalCase/camelCase notation

  • Hardware accelerated with OpenGL (1.1, 2.1, 3.3, 4.3, ES2, ES3 - choose at compile)

  • Software renderer optional, for systems with no GPU: [rlsw]

  • Custom OpenGL abstraction layer (usable as standalone module): [rlgl]

  • Multiple Fonts formats supported (TTF, OTF, FNT, BDF, Sprite fonts)

  • Many texture formats supported, including compressed formats (DXT, ETC, ASTC)

  • Full 3d support for 3d Shapes, Models, Billboards, Heightmaps and more!

  • Flexible Materials system, supporting classic maps and PBR maps

  • Animated 3D models supported (skeletal bones animation) (IQM, M3D, GLTF)

  • Shaders support, including Model shaders and Postprocessing shaders

  • Powerful math module for Vector, Matrix and Quaternion operations: [raymath]

  • Audio loading and playing with streaming support (WAV, OGG, MP3, FLAC, QOA, XM, MOD)

  • VR stereo rendering with configurable HMD device parameters

  • Bindings to multiple programming languages available!

NOTES

  • One default Font is loaded on InitWindow()->LoadFontDefault() [core, text]

  • One default Texture2D is loaded on rlglInit(), 1x1 white pixel R8G8B8A8 [rlgl] (OpenGL 3.3 or ES2)

  • One default Shader is loaded on rlglInit()->rlLoadShaderDefault() [rlgl] (OpenGL 3.3 or ES2)

  • One default RenderBatch is loaded on rlglInit()->rlLoadRenderBatch() [rlgl] (OpenGL 3.3 or ES2)

DEPENDENCIES

[rcore] Depends on the selected platform backend, check rcore.c header for details [rlgl] glad/glad_gles2 (David Herberth - github.com/Dav1dde/glad) for OpenGL extensions loading [raudio] miniaudio (David Reid - github.com/mackron/miniaudio) for audio device/context management

OPTIONAL DEPENDENCIES (included): [rcore] sinfl (Micha Mettke) for DEFLATE decompression algorithm [rcore] sdefl (Micha Mettke) for DEFLATE compression algorithm [rcore] rprand (Ramon Santamaria) for pseudo-random numbers generation [rtextures] qoi (Dominic Szablewski - https://phoboslab.org) for QOI image management [rtextures] stb_image (Sean Barrett) for images loading (BMP, TGA, PNG, JPEG, HDR...) [rtextures] stb_image_write (Sean Barrett) for image writing (BMP, TGA, PNG, JPG) [rtextures] stb_image_resize2 (Sean Barrett) for image resizing algorithms [rtextures] stb_perlin (Sean Barrett) for Perlin Noise image generation [rtextures] rltexgpu (Ramon Santamaria) for GPU-compressed texture formats [rtext] stb_truetype (Sean Barrett) for ttf fonts loading [rtext] stb_rect_pack (Sean Barrett) for rectangles packing [rmodels] par_shapes (Philip Rideout) for parametric 3d shapes generation [rmodels] tinyobj_loader_c (Syoyo Fujita) for models loading (OBJ, MTL) [rmodels] cgltf (Johannes Kuhlmann) for models loading (glTF) [rmodels] m3d (bzt) for models loading (M3D, https://bztsrc.gitlab.io/model3d) [rmodels] vox_loader (Johann Nadalutti) for models loading (VOX) [raudio] dr_wav (David Reid) for WAV audio file loading [raudio] dr_flac (David Reid) for FLAC audio file loading [raudio] dr_mp3 (David Reid) for MP3 audio file loading [raudio] stb_vorbis (Sean Barrett) for OGG audio loading [raudio] jar_xm (Joshua Reisenauer) for XM audio module loading [raudio] jar_mod (Joshua Reisenauer) for MOD audio module loading [raudio] qoa (Dominic Szablewski - https://phoboslab.org) for QOA audio management

@license

zlib/libpng

raylib is licensed under an unmodified zlib/libpng license, which is an OSI-certified, BSD-like license that allows static linking with closed source software:

Copyright (c) 2013-2026 Ramon Santamaria (@raysan5)

This software is provided "as-is", without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not claim that you

wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.

  1. Altered source versions must be plainly marked as such, and must not be misrepresented

as being the original software.

  1. This notice may not be removed or altered from any source distribution.

raylib
:
(struct) raylib.raylib_types.Color
Color
,
(alias) ExportImage = bool raylib.ExportImage(raylib.Image image, const(char)* fileName) nothrow @nogc
ExportImage
,
(alias) GenImageColor = raylib.Image raylib.GenImageColor(int width, int height, raylib.raylib_types.Color color) nothrow @nogc
GenImageColor
,
(struct) raylib.Image
Image
,
(alias) ImageDrawPixel = void raylib.ImageDrawPixel(raylib.Image* dst, int posX, int posY, raylib.raylib_types.Color color) nothrow @nogc
ImageDrawPixel
,
(alias) LoadImage = raylib.Image raylib.LoadImage(const(char)* fileName) nothrow @nogc
LoadImage
,
(alias) LoadImageColors = raylib.raylib_types.Color* raylib.LoadImageColors(raylib.Image image) nothrow @nogc
LoadImageColors
,
(alias) UnloadImage = void raylib.UnloadImage(raylib.Image image) nothrow @nogc
UnloadImage
,
(alias) UnloadImageColors = void raylib.UnloadImageColors(raylib.raylib_types.Color* colors) nothrow @nogc
UnloadImageColors
;
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) toStringz = immutable(char)* std.string.toStringz(scope const(char)[] s) pure nothrow @trusted

Params: s = A D-style string.

    Returns: A C-style null-terminated string equivalent to `s`. `s`
    must not contain embedded `'\0'`'s as any C function will treat the
    first `'\0'` that it sees as the end of the string. If `s.empty` is
    `true`, then a string containing only `'\0'` is returned.

    $(RED Important Note:) When passing a `char*` to a C function, and the C
    function keeps it around for any reason, make sure that you keep a
    reference to it in your D code. Otherwise, it may become invalid during a
    garbage collection cycle and cause a nasty bug when the C code tries to use
    it.
toStringz
;
auto
(local variable) raylib.Image a
a
=
raylib.Image raylib.LoadImage(const(char)* fileName) nothrow @nogc
LoadImage
(
(parameter) string oldPath
oldPath
.
immutable(char)* std.string.toStringz(scope const(char)[] s) pure nothrow @trusted

Examples

import core.stdc.string : strlen;
import std.conv : to;

auto p = toStringz("foo");
assert(strlen(p) == 3);
const(char)[] foo = "abbzxyzzy";
p = toStringz(foo[3 .. 5]);
assert(strlen(p) == 2);

string test = "";
p = toStringz(test);
assert(*p == 0);

test = "\0";
p = toStringz(test);
assert(*p == 0);

test = "foo\0";
p = toStringz(test);
assert(p[0] == 'f' && p[1] == 'o' && p[2] == 'o' && p[3] == 0);

const string test2 = "";
p = toStringz(test2);
assert(*p == 0);

assert(toStringz([]) is toStringz(""));
@params A D-style string.@returns

A C-style null-terminated string equivalent to s. s must not contain embedded '\0''s as any C function will treat the first '\0' that it sees as the end of the string. If ``s.empty is true, then a string containing only '\0' is returned.

Important Note: When passing a char* to a C function, and the C function keeps it around for any reason, make sure that you keep a reference to it in your D code. Otherwise, it may become invalid during a garbage collection cycle and cause a nasty bug when the C code tries to use it.

toStringz
);
auto
(local variable) raylib.Image b
b
=
raylib.Image raylib.LoadImage(const(char)* fileName) nothrow @nogc
LoadImage
(
(parameter) string newPath
newPath
.
immutable(char)* std.string.toStringz(scope const(char)[] s) pure nothrow @trusted

Examples

import core.stdc.string : strlen;
import std.conv : to;

auto p = toStringz("foo");
assert(strlen(p) == 3);
const(char)[] foo = "abbzxyzzy";
p = toStringz(foo[3 .. 5]);
assert(strlen(p) == 2);

string test = "";
p = toStringz(test);
assert(*p == 0);

test = "\0";
p = toStringz(test);
assert(*p == 0);

test = "foo\0";
p = toStringz(test);
assert(p[0] == 'f' && p[1] == 'o' && p[2] == 'o' && p[3] == 0);

const string test2 = "";
p = toStringz(test2);
assert(*p == 0);

assert(toStringz([]) is toStringz(""));
@params A D-style string.@returns

A C-style null-terminated string equivalent to s. s must not contain embedded '\0''s as any C function will treat the first '\0' that it sees as the end of the string. If ``s.empty is true, then a string containing only '\0' is returned.

Important Note: When passing a char* to a C function, and the C function keeps it around for any reason, make sure that you keep a reference to it in your D code. Otherwise, it may become invalid during a garbage collection cycle and cause a nasty bug when the C code tries to use it.

toStringz
);
scope (exit) {
void raylib.UnloadImage(raylib.Image image) nothrow @nogc
UnloadImage
(
(local variable) raylib.Image a
a
);
void raylib.UnloadImage(raylib.Image image) nothrow @nogc
UnloadImage
(
(local variable) raylib.Image b
b
);
} if (
(local variable) raylib.Image a
a
.
(field) int raylib.Image.width
width
!=
(local variable) raylib.Image b
b
.
(field) int raylib.Image.width
width
||
(local variable) raylib.Image a
a
.
(field) int raylib.Image.height
height
!=
(local variable) raylib.Image b
b
.
(field) int raylib.Image.height
height
)
{
void std.stdio.writefln!(char, int, int, int, int)(in char[] fmt, int __param_1, int __param_2, int __param_3, int __param_4) @safe

Equivalent to writef(fmt, args, '\n').

writefln
(" sizes differ: %sx%s vs %sx%s",
(local variable) raylib.Image a
a
.
(field) int raylib.Image.width
width
,
(local variable) raylib.Image a
a
.
(field) int raylib.Image.height
height
,
(local variable) raylib.Image b
b
.
(field) int raylib.Image.width
width
,
(local variable) raylib.Image b
b
.
(field) int raylib.Image.height
height
);
return; } auto
(local variable) raylib.raylib_types.Color* pa
pa
=
raylib.raylib_types.Color* raylib.LoadImageColors(raylib.Image image) nothrow @nogc
LoadImageColors
(
(local variable) raylib.Image a
a
);
auto
(local variable) raylib.raylib_types.Color* pb
pb
=
raylib.raylib_types.Color* raylib.LoadImageColors(raylib.Image image) nothrow @nogc
LoadImageColors
(
(local variable) raylib.Image b
b
);
scope (exit) {
void raylib.UnloadImageColors(raylib.raylib_types.Color* colors) nothrow @nogc
UnloadImageColors
(
(local variable) raylib.raylib_types.Color* pa
pa
);
void raylib.UnloadImageColors(raylib.raylib_types.Color* colors) nothrow @nogc
UnloadImageColors
(
(local variable) raylib.raylib_types.Color* pb
pb
);
} auto
(local variable) raylib.Image mask
mask
=
raylib.Image raylib.GenImageColor(int width, int height, raylib.raylib_types.Color color) nothrow @nogc
GenImageColor
(
(local variable) raylib.Image a
a
.
(field) int raylib.Image.width
width
,
(local variable) raylib.Image a
a
.
(field) int raylib.Image.height
height
,
(struct) raylib.raylib_types.Color
Color
(0, 0, 0, 255));
scope (exit)
void raylib.UnloadImage(raylib.Image image) nothrow @nogc
UnloadImage
(
(local variable) raylib.Image mask
mask
);
int
(local variable) int minX
minX
= int.
(constant) int int.max = 2147483647
max
,
(local variable) int minY
minY
= int.
(constant) int int.max = 2147483647
max
,
(local variable) int maxX
maxX
= -1,
(local variable) int maxY
maxY
= -1;
(alias) object.size_t = ulong
size_t
(local variable) ulong differing
differing
;
foreach (
(local variable) int y
y
; 0 ..
(local variable) raylib.Image a
a
.
(field) int raylib.Image.height
height
)
foreach (
(local variable) int x
x
; 0 ..
(local variable) raylib.Image a
a
.
(field) int raylib.Image.width
width
)
{ const
(local variable) const(int) i
i
=
(local variable) int y
y
*
(local variable) raylib.Image a
a
.
(field) int raylib.Image.width
width
+
(local variable) int x
x
;
if (
(local variable) raylib.raylib_types.Color* pa
pa
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.r
r
==
(local variable) raylib.raylib_types.Color* pb
pb
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.r
r
&&
(local variable) raylib.raylib_types.Color* pa
pa
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.g
g
==
(local variable) raylib.raylib_types.Color* pb
pb
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.g
g
&&
(local variable) raylib.raylib_types.Color* pa
pa
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.b
b
==
(local variable) raylib.raylib_types.Color* pb
pb
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.b
b
&&
(local variable) raylib.raylib_types.Color* pa
pa
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.a
a
==
(local variable) raylib.raylib_types.Color* pb
pb
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.a
a
)
continue; ++
(local variable) ulong differing
differing
;
if (
(local variable) int x
x
<
(local variable) int minX
minX
)
(local variable) int minX
minX
=
(local variable) int x
x
;
if (
(local variable) int y
y
<
(local variable) int minY
minY
)
(local variable) int minY
minY
=
(local variable) int y
y
;
if (
(local variable) int x
x
>
(local variable) int maxX
maxX
)
(local variable) int maxX
maxX
=
(local variable) int x
x
;
if (
(local variable) int y
y
>
(local variable) int maxY
maxY
)
(local variable) int maxY
maxY
=
(local variable) int y
y
;
void raylib.ImageDrawPixel(raylib.Image* dst, int posX, int posY, raylib.raylib_types.Color color) nothrow @nogc
ImageDrawPixel
(&
(local variable) raylib.Image mask
mask
,
(local variable) int x
x
,
(local variable) int y
y
,
(struct) raylib.raylib_types.Color
Color
(255, 0, 0, 255));
} if (
(local variable) ulong differing
differing
== 0)
{
void std.stdio.writeln!string(string __param_0) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
(" …but every pixel matches: the PNGs differ only in encoding.");
return; }
void std.stdio.writefln!(char, ulong, ulong, double)(in char[] fmt, ulong __param_1, ulong __param_2, double __param_3) @safe

Equivalent to writef(fmt, args, '\n').

writefln
(" %s of %s pixels differ (%.4f%%)",
(local variable) ulong differing
differing
,
cast(
(alias) object.size_t = ulong
size_t
)(
(local variable) raylib.Image a
a
.
(field) int raylib.Image.width
width
*
(local variable) raylib.Image a
a
.
(field) int raylib.Image.height
height
),
100.0 *
(local variable) ulong differing
differing
/ (
(local variable) raylib.Image a
a
.
(field) int raylib.Image.width
width
*
(local variable) raylib.Image a
a
.
(field) int raylib.Image.height
height
));
void std.stdio.writefln!(char, int, int, int, int, int, int)(in char[] fmt, int __param_1, int __param_2, int __param_3, int __param_4, int __param_5, int __param_6) @safe

Equivalent to writef(fmt, args, '\n').

writefln
(" bounding box: x %s..%s, y %s..%s (%sx%s)",
(local variable) int minX
minX
,
(local variable) int maxX
maxX
,
(local variable) int minY
minY
,
(local variable) int maxY
maxY
,
(local variable) int maxX
maxX
-
(local variable) int minX
minX
+ 1,
(local variable) int maxY
maxY
-
(local variable) int minY
minY
+ 1);
// A handful of actual before/after colours, because "76 pixels moved" and // "76 pixels changed shade" are different bugs and the box cannot tell // them apart.
(alias) object.size_t = ulong
size_t
(local variable) ulong shown
shown
;
foreach (
(local variable) int y
y
; 0 ..
(local variable) raylib.Image a
a
.
(field) int raylib.Image.height
height
)
{ foreach (
(local variable) int x
x
; 0 ..
(local variable) raylib.Image a
a
.
(field) int raylib.Image.width
width
)
{ const
(local variable) const(int) i
i
=
(local variable) int y
y
*
(local variable) raylib.Image a
a
.
(field) int raylib.Image.width
width
+
(local variable) int x
x
;
if (
(local variable) raylib.raylib_types.Color* pa
pa
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.r
r
==
(local variable) raylib.raylib_types.Color* pb
pb
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.r
r
&&
(local variable) raylib.raylib_types.Color* pa
pa
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.g
g
==
(local variable) raylib.raylib_types.Color* pb
pb
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.g
g
&&
(local variable) raylib.raylib_types.Color* pa
pa
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.b
b
==
(local variable) raylib.raylib_types.Color* pb
pb
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.b
b
&&
(local variable) raylib.raylib_types.Color* pa
pa
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.a
a
==
(local variable) raylib.raylib_types.Color* pb
pb
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.a
a
)
continue;
void std.stdio.writefln!(char, int, int, ubyte, ubyte, ubyte, ubyte, ubyte, ubyte, ubyte, ubyte)(in char[] fmt, int __param_1, int __param_2, ubyte __param_3, ubyte __param_4, ubyte __param_5, ubyte __param_6, ubyte __param_7, ubyte __param_8, ubyte __param_9, ubyte __param_10) @safe

Equivalent to writef(fmt, args, '\n').

writefln
(" (%s,%s) %02x%02x%02x%02x -> %02x%02x%02x%02x",
(local variable) int x
x
,
(local variable) int y
y
,
(local variable) raylib.raylib_types.Color* pa
pa
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.r
r
,
(local variable) raylib.raylib_types.Color* pa
pa
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.g
g
,
(local variable) raylib.raylib_types.Color* pa
pa
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.b
b
,
(local variable) raylib.raylib_types.Color* pa
pa
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.a
a
,
(local variable) raylib.raylib_types.Color* pb
pb
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.r
r
,
(local variable) raylib.raylib_types.Color* pb
pb
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.g
g
,
(local variable) raylib.raylib_types.Color* pb
pb
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.b
b
,
(local variable) raylib.raylib_types.Color* pb
pb
[
(local variable) const(int) i
i
].
(field) ubyte raylib.raylib_types.Color.a
a
);
if (++
(local variable) ulong shown
shown
== 4)
break; } if (
(local variable) ulong shown
shown
== 4)
break; } const
(local variable) const(string) maskPath
maskPath
=
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
(
(parameter) string outDir
outDir
, "diff-mask.png");
bool raylib.ExportImage(raylib.Image image, const(char)* fileName) nothrow @nogc
ExportImage
(
(local variable) raylib.Image mask
mask
,
(local variable) const(string) maskPath
maskPath
.
immutable(char)* std.string.toStringz(scope const(char)[] s) pure nothrow @trusted

Examples

import core.stdc.string : strlen;
import std.conv : to;

auto p = toStringz("foo");
assert(strlen(p) == 3);
const(char)[] foo = "abbzxyzzy";
p = toStringz(foo[3 .. 5]);
assert(strlen(p) == 2);

string test = "";
p = toStringz(test);
assert(*p == 0);

test = "\0";
p = toStringz(test);
assert(*p == 0);

test = "foo\0";
p = toStringz(test);
assert(p[0] == 'f' && p[1] == 'o' && p[2] == 'o' && p[3] == 0);

const string test2 = "";
p = toStringz(test2);
assert(*p == 0);

assert(toStringz([]) is toStringz(""));
@params A D-style string.@returns

A C-style null-terminated string equivalent to s. s must not contain embedded '\0''s as any C function will treat the first '\0' that it sees as the end of the string. If ``s.empty is true, then a string containing only '\0' is returned.

Important Note: When passing a char* to a C function, and the C function keeps it around for any reason, make sure that you keep a reference to it in your D code. Otherwise, it may become invalid during a garbage collection cycle and cause a nasty bug when the C code tries to use it.

toStringz
);
void std.stdio.writefln!(char, string)(in char[] fmt, string __param_1) @safe

Equivalent to writef(fmt, args, '\n').

writefln
(" mask -> %s",
(local variable) const(string) maskPath
maskPath
);
} /// Captures `bin` `p.runs` times, failing unless every run agrees with itself. private bool
bool gui_ab.capture(in gui_ab.Params p, string bin, string side, out ubyte[] bytes)

Captures bin ``p.runs times, failing unless every run agrees with itself.

capture
(in
(struct) gui_ab.Params

CLI surface (parsed by sparkles:core-cli, per the D-tooling guideline).

Params
(parameter) const(gui_ab.Params) p
p
,
(alias) object.string = string
string
(parameter) string bin
bin
,
(alias) object.string = string
string
(parameter) string side
side
, out ubyte[]
(parameter) ubyte[] bytes
bytes
)
{ ubyte[]
(local variable) ubyte[] first
first
;
foreach (
(local variable) int run
run
; 0 ..
(parameter) const(gui_ab.Params) p
p
.
(field) int gui_ab.Params.runs
runs
)
{ ubyte[]
(local variable) ubyte[] shot
shot
;
if (!
bool gui_ab.shoot(in gui_ab.Params p, string bin, string side, out ubyte[] bytes)

One xvfb-run capture into <outDir>/<side>.png.

shoot
(
(parameter) const(gui_ab.Params) p
p
,
(parameter) string bin
bin
,
(parameter) string side
side
,
(local variable) ubyte[] shot
shot
))
return false; if (
(local variable) int run
run
== 0)
{
(local variable) ubyte[] first
first
=
(local variable) ubyte[] shot
shot
;
continue; } if (
(local variable) ubyte[] shot
shot
!=
(local variable) ubyte[] first
first
)
{ stderr.
std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @system
writefln
("gui-ab: %s is NOT reproducible — run %s differs "
~ "from run 0 (%s vs %s). A capture that disagrees with itself " ~ "cannot be compared against anything.",
(parameter) string side
side
,
(local variable) int run
run
,
string gui_ab.digest(in ubyte[] bytes)
digest
(
(local variable) ubyte[] shot
shot
),
string gui_ab.digest(in ubyte[] bytes)
digest
(
(local variable) ubyte[] first
first
));
return false; } }
(parameter) ubyte[] bytes
bytes
=
(local variable) ubyte[] first
first
;
void std.stdio.writefln!(char, string, ulong, string, const(int))(in char[] fmt, string __param_1, ulong __param_2, string __param_3, const(int) __param_4) @safe

Equivalent to writef(fmt, args, '\n').

writefln
("%s: %s bytes, %s (%s runs agreed)",
(parameter) string side
side
,
(parameter) ubyte[] bytes
bytes
.
(field) ulong ubyte[].length
length
,
string gui_ab.digest(in ubyte[] bytes)
digest
(
(parameter) ubyte[] bytes
bytes
),
(parameter) const(gui_ab.Params) p
p
.
(field) int gui_ab.Params.runs
runs
);
return true; } /// One `xvfb-run` capture into `<outDir>/<side>.png`. private bool
bool gui_ab.shoot(in gui_ab.Params p, string bin, string side, out ubyte[] bytes)

One xvfb-run capture into <outDir>/<side>.png.

shoot
(in
(struct) gui_ab.Params

CLI surface (parsed by sparkles:core-cli, per the D-tooling guideline).

Params
(parameter) const(gui_ab.Params) p
p
,
(alias) object.string = string
string
(parameter) string bin
bin
,
(alias) object.string = string
string
(parameter) string side
side
, out ubyte[]
(parameter) ubyte[] bytes
bytes
)
{ const
(local variable) const(string) png
png
=
(parameter) string side
side
~ ".png"; // relative — raylib's TakeScreenshot prepends CWD
const
(local variable) const(string) full
full
=
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
(
(parameter) const(gui_ab.Params) p
p
.
(field) string gui_ab.Params.outDir
outDir
,
(local variable) const(string) png
png
);
if (
(local variable) const(string) full
full
.
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
)
void std.file.remove!string(string name) @safe

Delete file name.

@paramname string or range of characters representing the file name@throwsFileException on error.
remove
(
(local variable) const(string) full
full
);
auto
(local variable) string[string] env
env
=
(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[string] std.process.environment.toAA() @trusted

Copies all environment variables into an associative array.

Windows specific

While Windows environment variable names are case insensitive, D's built-in associative arrays are not. This function will store all variable names in uppercase (e.g. PATH).

@throwsException if the environment variables could not be retrieved (Windows only).
toAA
;
string* core.internal.newaa._d_aaGetY!(string, string, string[string], string, string, string)(ref scope string[string] aa, 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
env
["HUE_GUI_SCREENSHOT"] =
(local variable) const(string) png
png
;
string* core.internal.newaa._d_aaGetY!(string, string, string[string], string, string, string)(ref scope string[string] aa, 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
env
["HUE_GUI_SCREENSHOT_FRAME"] =
(parameter) const(gui_ab.Params) p
p
.
(field) int gui_ab.Params.frame
frame
.
string std.conv.to!string.to!(const(int))(const(int) __param_0) pure nothrow @safe

The to template converts a value from one type to another. The source type is deduced and the target type must be specified, for example the expression to`!int(42.0)` converts the number 42 from `double` to `int`. The conversion is "safe", i.e., it checks for overflow; to!int(4.2e10) would throw the ConvOverflowException exception. Overflow checks are only inserted when necessary, e.g., ``to!double(42) does not do any checking because any int fits in a double.

Conversions from string to numeric types differ from the C equivalents atoi() and atol() by checking for overflow and not allowing whitespace.

For conversion of strings to signed types, the grammar recognized is: Integer: Sign UnsignedInteger UnsignedInteger Sign: + -

For conversion to unsigned types, the grammar recognized is: UnsignedInteger: DecimalDigit DecimalDigit UnsignedInteger

Examples

Converting a value to its own type (useful mostly for generic code) simply returns its argument.

int a = 42;
int b = to!int(a);
double c = to!double(3.14); // c is double with value 3.14

Converting among numeric types is a safe way to cast them around.

Conversions from floating-point types to integral types allow loss of precision (the fractional part of a floating-point number). The conversion is truncating towards zero, the same way a cast would truncate. (To round a floating point value when casting to an integral, use roundTo.)

import std.exception : assertThrown;

int a = 420;
assert(to!long(a) == a);
assertThrown!ConvOverflowException(to!byte(a));

assert(to!int(4.2e6) == 4200000);
assertThrown!ConvOverflowException(to!uint(-3.14));
assert(to!uint(3.14) == 3);
assert(to!uint(3.99) == 3);
assert(to!int(-3.99) == -3);

When converting strings to numeric types, note that D hexadecimal and binary literals are not handled. Neither the prefixes that indicate the base, nor the horizontal bar used to separate groups of digits are recognized. This also applies to the suffixes that indicate the type.

To work around this, you can specify a radix for conversions involving numbers.

auto str = to!string(42, 16);
assert(str == "2A");
auto i = to!int(str, 16);
assert(i == 42);

Conversions from integral types to floating-point types always succeed, but might lose accuracy. The largest integers with a predecessor representable in floating-point format are 2^24-1 for float, 2^53-1 for double, and 2^64-1 for real (when real is 80-bit, e.g. on Intel machines).

// 2^24 - 1, largest proper integer representable as float
int a = 16_777_215;
assert(to!int(to!float(a)) == a);
assert(to!int(to!float(-a)) == -a);

Conversion from string types to char types enforces the input to consist of a single code point, and said code point must fit in the target type. Otherwise, ConvException is thrown.

import std.exception : assertThrown;

assert(to!char("a") == 'a');
assertThrown(to!char("ñ")); // 'ñ' does not fit into a char
assert(to!wchar("ñ") == 'ñ');
assertThrown(to!wchar("😃")); // '😃' does not fit into a wchar
assert(to!dchar("😃") == '😃');

// Using wstring or dstring as source type does not affect the result
assert(to!char("a"w) == 'a');
assert(to!char("a"d) == 'a');

// Two code points cannot be converted to a single one
assertThrown(to!char("ab"));

Converting an array to another array type works by converting each element in turn. Associative arrays can be converted to associative arrays as long as keys and values can in turn be converted.

import std.string : split;

int[] a = [1, 2, 3];
auto b = to!(float[])(a);
assert(b == [1.0f, 2, 3]);
string str = "1 2 3 4 5 6";
auto numbers = to!(double[])(split(str));
assert(numbers == [1.0, 2, 3, 4, 5, 6]);
int[string] c;
c["a"] = 1;
c["b"] = 2;
auto d = to!(double[wstring])(c);
assert(d["a"w] == 1 && d["b"w] == 2);

Conversions operate transitively, meaning that they work on arrays and associative arrays of any complexity.

This conversion works because to`!short` applies to an `int`, to!wstring applies to a string, to`!string` applies to a `double`, and to!(double[]) applies to an int[]. The conversion might throw an exception because ``to!short might fail the range check.

int[string][double[int[]]] a;
auto b = to!(short[wstring][string[double[]]])(a);

Object-to-object conversions by dynamic casting throw exception when the source is non-null and the target is null.

import std.exception : assertThrown;
// Testing object conversions
class A {}
class B : A {}
class C : A {}
A a1 = new A, a2 = new B, a3 = new C;
assert(to!B(a2) is a2);
assert(to!C(a3) is a3);
assertThrown!ConvException(to!B(a3));

Stringize conversion from all types is supported.

  • String to string conversion works for any two string types having (char, wchar, dchar) character widths and any combination of qualifiers (mutable, const, or immutable).

  • Converts array (other than strings) to string. Each element is converted by calling ``to!T.

  • Associative array to string conversion. Each element is converted by calling ``to!T.

  • Object to string conversion calls toString against the object or returns "null" if the object is null.

  • Struct to string conversion calls toString against the struct if it is defined.

  • For structs that do not define toString, the conversion to string produces the list of fields.

  • Enumerated types are converted to strings as their symbolic names.

  • Boolean values are converted to "true" or "false".

  • char, wchar, dchar to a string type.

  • Unsigned or signed integers to strings.

    [special case]

    : Convert integral value to string in radix radix. radix must be a value from 2 to 36. value is treated as a signed value only if radix is 10. The characters A through Z are used to represent values 10 through 36 and their case is determined by the letterCase parameter.

  • All floating point types to all string types.

  • Pointer to string conversions convert the pointer to a size_t value. If pointer is char*, treat it as C-style strings. In that case, this function is @system.

See formatValue on how toString should be defined.

// Conversion representing dynamic/static array with string
long[] a = [ 1, 3, 5 ];
assert(to!string(a) == "[1, 3, 5]");

// Conversion representing associative array with string
int[string] associativeArray = ["0":1, "1":2];
assert(to!string(associativeArray) == `["0":1, "1":2]` ||
       to!string(associativeArray) == `["1":2, "0":1]`);

// char* to string conversion
assert(to!string(cast(char*) null) == "");
assert(to!string("foo\0".ptr) == "foo");

// Conversion reinterpreting void array to string
auto w = "abcx"w;
const(void)[] b = w;
assert(b.length == 8);

auto c = to!(wchar[])(b);
assert(c == "abcx");

Strings can be converted to enum types. The enum member with the same name as the input string is returned. The comparison is case-sensitive.

A ConvException is thrown if the enum does not have the specified member.

import std.exception : assertThrown;

enum E { a, b, c }
assert(to!E("a") == E.a);
assert(to!E("b") == E.b);
assertThrown!ConvException(to!E("A"));
to
!
(alias) object.string = string
string
;
string* core.internal.newaa._d_aaGetY!(string, string, string[string], string, string, string)(ref scope string[string] aa, 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
env
["HUE_GUI_FONTSIZE"] =
(parameter) const(gui_ab.Params) p
p
.
(field) int gui_ab.Params.fontSize
fontSize
.
string std.conv.to!string.to!(const(int))(const(int) __param_0) pure nothrow @safe

The to template converts a value from one type to another. The source type is deduced and the target type must be specified, for example the expression to`!int(42.0)` converts the number 42 from `double` to `int`. The conversion is "safe", i.e., it checks for overflow; to!int(4.2e10) would throw the ConvOverflowException exception. Overflow checks are only inserted when necessary, e.g., ``to!double(42) does not do any checking because any int fits in a double.

Conversions from string to numeric types differ from the C equivalents atoi() and atol() by checking for overflow and not allowing whitespace.

For conversion of strings to signed types, the grammar recognized is: Integer: Sign UnsignedInteger UnsignedInteger Sign: + -

For conversion to unsigned types, the grammar recognized is: UnsignedInteger: DecimalDigit DecimalDigit UnsignedInteger

Examples

Converting a value to its own type (useful mostly for generic code) simply returns its argument.

int a = 42;
int b = to!int(a);
double c = to!double(3.14); // c is double with value 3.14

Converting among numeric types is a safe way to cast them around.

Conversions from floating-point types to integral types allow loss of precision (the fractional part of a floating-point number). The conversion is truncating towards zero, the same way a cast would truncate. (To round a floating point value when casting to an integral, use roundTo.)

import std.exception : assertThrown;

int a = 420;
assert(to!long(a) == a);
assertThrown!ConvOverflowException(to!byte(a));

assert(to!int(4.2e6) == 4200000);
assertThrown!ConvOverflowException(to!uint(-3.14));
assert(to!uint(3.14) == 3);
assert(to!uint(3.99) == 3);
assert(to!int(-3.99) == -3);

When converting strings to numeric types, note that D hexadecimal and binary literals are not handled. Neither the prefixes that indicate the base, nor the horizontal bar used to separate groups of digits are recognized. This also applies to the suffixes that indicate the type.

To work around this, you can specify a radix for conversions involving numbers.

auto str = to!string(42, 16);
assert(str == "2A");
auto i = to!int(str, 16);
assert(i == 42);

Conversions from integral types to floating-point types always succeed, but might lose accuracy. The largest integers with a predecessor representable in floating-point format are 2^24-1 for float, 2^53-1 for double, and 2^64-1 for real (when real is 80-bit, e.g. on Intel machines).

// 2^24 - 1, largest proper integer representable as float
int a = 16_777_215;
assert(to!int(to!float(a)) == a);
assert(to!int(to!float(-a)) == -a);

Conversion from string types to char types enforces the input to consist of a single code point, and said code point must fit in the target type. Otherwise, ConvException is thrown.

import std.exception : assertThrown;

assert(to!char("a") == 'a');
assertThrown(to!char("ñ")); // 'ñ' does not fit into a char
assert(to!wchar("ñ") == 'ñ');
assertThrown(to!wchar("😃")); // '😃' does not fit into a wchar
assert(to!dchar("😃") == '😃');

// Using wstring or dstring as source type does not affect the result
assert(to!char("a"w) == 'a');
assert(to!char("a"d) == 'a');

// Two code points cannot be converted to a single one
assertThrown(to!char("ab"));

Converting an array to another array type works by converting each element in turn. Associative arrays can be converted to associative arrays as long as keys and values can in turn be converted.

import std.string : split;

int[] a = [1, 2, 3];
auto b = to!(float[])(a);
assert(b == [1.0f, 2, 3]);
string str = "1 2 3 4 5 6";
auto numbers = to!(double[])(split(str));
assert(numbers == [1.0, 2, 3, 4, 5, 6]);
int[string] c;
c["a"] = 1;
c["b"] = 2;
auto d = to!(double[wstring])(c);
assert(d["a"w] == 1 && d["b"w] == 2);

Conversions operate transitively, meaning that they work on arrays and associative arrays of any complexity.

This conversion works because to`!short` applies to an `int`, to!wstring applies to a string, to`!string` applies to a `double`, and to!(double[]) applies to an int[]. The conversion might throw an exception because ``to!short might fail the range check.

int[string][double[int[]]] a;
auto b = to!(short[wstring][string[double[]]])(a);

Object-to-object conversions by dynamic casting throw exception when the source is non-null and the target is null.

import std.exception : assertThrown;
// Testing object conversions
class A {}
class B : A {}
class C : A {}
A a1 = new A, a2 = new B, a3 = new C;
assert(to!B(a2) is a2);
assert(to!C(a3) is a3);
assertThrown!ConvException(to!B(a3));

Stringize conversion from all types is supported.

  • String to string conversion works for any two string types having (char, wchar, dchar) character widths and any combination of qualifiers (mutable, const, or immutable).

  • Converts array (other than strings) to string. Each element is converted by calling ``to!T.

  • Associative array to string conversion. Each element is converted by calling ``to!T.

  • Object to string conversion calls toString against the object or returns "null" if the object is null.

  • Struct to string conversion calls toString against the struct if it is defined.

  • For structs that do not define toString, the conversion to string produces the list of fields.

  • Enumerated types are converted to strings as their symbolic names.

  • Boolean values are converted to "true" or "false".

  • char, wchar, dchar to a string type.

  • Unsigned or signed integers to strings.

    [special case]

    : Convert integral value to string in radix radix. radix must be a value from 2 to 36. value is treated as a signed value only if radix is 10. The characters A through Z are used to represent values 10 through 36 and their case is determined by the letterCase parameter.

  • All floating point types to all string types.

  • Pointer to string conversions convert the pointer to a size_t value. If pointer is char*, treat it as C-style strings. In that case, this function is @system.

See formatValue on how toString should be defined.

// Conversion representing dynamic/static array with string
long[] a = [ 1, 3, 5 ];
assert(to!string(a) == "[1, 3, 5]");

// Conversion representing associative array with string
int[string] associativeArray = ["0":1, "1":2];
assert(to!string(associativeArray) == `["0":1, "1":2]` ||
       to!string(associativeArray) == `["1":2, "0":1]`);

// char* to string conversion
assert(to!string(cast(char*) null) == "");
assert(to!string("foo\0".ptr) == "foo");

// Conversion reinterpreting void array to string
auto w = "abcx"w;
const(void)[] b = w;
assert(b.length == 8);

auto c = to!(wchar[])(b);
assert(c == "abcx");

Strings can be converted to enum types. The enum member with the same name as the input string is returned. The comparison is case-sensitive.

A ConvException is thrown if the enum does not have the specified member.

import std.exception : assertThrown;

enum E { a, b, c }
assert(to!E("a") == E.a);
assert(to!E("b") == E.b);
assertThrown!ConvException(to!E("A"));
to
!
(alias) object.string = string
string
;
if (
(parameter) const(gui_ab.Params) p
p
.
(field) string gui_ab.Params.pointer
pointer
.
(field) ulong const(string).length
length
)
string* core.internal.newaa._d_aaGetY!(string, string, string[string], string, string, string)(ref scope string[string] aa, 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
env
["HUE_GUI_POINTER"] =
(parameter) const(gui_ab.Params) p
p
.
(field) string gui_ab.Params.pointer
pointer
;
if (
(parameter) const(gui_ab.Params) p
p
.
(field) int gui_ab.Params.top
top
>= 0)
string* core.internal.newaa._d_aaGetY!(string, string, string[string], string, string, string)(ref scope string[string] aa, 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
env
["HUE_GUI_TOP"] =
(parameter) const(gui_ab.Params) p
p
.
(field) int gui_ab.Params.top
top
.
string std.conv.to!string.to!(const(int))(const(int) __param_0) pure nothrow @safe

The to template converts a value from one type to another. The source type is deduced and the target type must be specified, for example the expression to`!int(42.0)` converts the number 42 from `double` to `int`. The conversion is "safe", i.e., it checks for overflow; to!int(4.2e10) would throw the ConvOverflowException exception. Overflow checks are only inserted when necessary, e.g., ``to!double(42) does not do any checking because any int fits in a double.

Conversions from string to numeric types differ from the C equivalents atoi() and atol() by checking for overflow and not allowing whitespace.

For conversion of strings to signed types, the grammar recognized is: Integer: Sign UnsignedInteger UnsignedInteger Sign: + -

For conversion to unsigned types, the grammar recognized is: UnsignedInteger: DecimalDigit DecimalDigit UnsignedInteger

Examples

Converting a value to its own type (useful mostly for generic code) simply returns its argument.

int a = 42;
int b = to!int(a);
double c = to!double(3.14); // c is double with value 3.14

Converting among numeric types is a safe way to cast them around.

Conversions from floating-point types to integral types allow loss of precision (the fractional part of a floating-point number). The conversion is truncating towards zero, the same way a cast would truncate. (To round a floating point value when casting to an integral, use roundTo.)

import std.exception : assertThrown;

int a = 420;
assert(to!long(a) == a);
assertThrown!ConvOverflowException(to!byte(a));

assert(to!int(4.2e6) == 4200000);
assertThrown!ConvOverflowException(to!uint(-3.14));
assert(to!uint(3.14) == 3);
assert(to!uint(3.99) == 3);
assert(to!int(-3.99) == -3);

When converting strings to numeric types, note that D hexadecimal and binary literals are not handled. Neither the prefixes that indicate the base, nor the horizontal bar used to separate groups of digits are recognized. This also applies to the suffixes that indicate the type.

To work around this, you can specify a radix for conversions involving numbers.

auto str = to!string(42, 16);
assert(str == "2A");
auto i = to!int(str, 16);
assert(i == 42);

Conversions from integral types to floating-point types always succeed, but might lose accuracy. The largest integers with a predecessor representable in floating-point format are 2^24-1 for float, 2^53-1 for double, and 2^64-1 for real (when real is 80-bit, e.g. on Intel machines).

// 2^24 - 1, largest proper integer representable as float
int a = 16_777_215;
assert(to!int(to!float(a)) == a);
assert(to!int(to!float(-a)) == -a);

Conversion from string types to char types enforces the input to consist of a single code point, and said code point must fit in the target type. Otherwise, ConvException is thrown.

import std.exception : assertThrown;

assert(to!char("a") == 'a');
assertThrown(to!char("ñ")); // 'ñ' does not fit into a char
assert(to!wchar("ñ") == 'ñ');
assertThrown(to!wchar("😃")); // '😃' does not fit into a wchar
assert(to!dchar("😃") == '😃');

// Using wstring or dstring as source type does not affect the result
assert(to!char("a"w) == 'a');
assert(to!char("a"d) == 'a');

// Two code points cannot be converted to a single one
assertThrown(to!char("ab"));

Converting an array to another array type works by converting each element in turn. Associative arrays can be converted to associative arrays as long as keys and values can in turn be converted.

import std.string : split;

int[] a = [1, 2, 3];
auto b = to!(float[])(a);
assert(b == [1.0f, 2, 3]);
string str = "1 2 3 4 5 6";
auto numbers = to!(double[])(split(str));
assert(numbers == [1.0, 2, 3, 4, 5, 6]);
int[string] c;
c["a"] = 1;
c["b"] = 2;
auto d = to!(double[wstring])(c);
assert(d["a"w] == 1 && d["b"w] == 2);

Conversions operate transitively, meaning that they work on arrays and associative arrays of any complexity.

This conversion works because to`!short` applies to an `int`, to!wstring applies to a string, to`!string` applies to a `double`, and to!(double[]) applies to an int[]. The conversion might throw an exception because ``to!short might fail the range check.

int[string][double[int[]]] a;
auto b = to!(short[wstring][string[double[]]])(a);

Object-to-object conversions by dynamic casting throw exception when the source is non-null and the target is null.

import std.exception : assertThrown;
// Testing object conversions
class A {}
class B : A {}
class C : A {}
A a1 = new A, a2 = new B, a3 = new C;
assert(to!B(a2) is a2);
assert(to!C(a3) is a3);
assertThrown!ConvException(to!B(a3));

Stringize conversion from all types is supported.

  • String to string conversion works for any two string types having (char, wchar, dchar) character widths and any combination of qualifiers (mutable, const, or immutable).

  • Converts array (other than strings) to string. Each element is converted by calling ``to!T.

  • Associative array to string conversion. Each element is converted by calling ``to!T.

  • Object to string conversion calls toString against the object or returns "null" if the object is null.

  • Struct to string conversion calls toString against the struct if it is defined.

  • For structs that do not define toString, the conversion to string produces the list of fields.

  • Enumerated types are converted to strings as their symbolic names.

  • Boolean values are converted to "true" or "false".

  • char, wchar, dchar to a string type.

  • Unsigned or signed integers to strings.

    [special case]

    : Convert integral value to string in radix radix. radix must be a value from 2 to 36. value is treated as a signed value only if radix is 10. The characters A through Z are used to represent values 10 through 36 and their case is determined by the letterCase parameter.

  • All floating point types to all string types.

  • Pointer to string conversions convert the pointer to a size_t value. If pointer is char*, treat it as C-style strings. In that case, this function is @system.

See formatValue on how toString should be defined.

// Conversion representing dynamic/static array with string
long[] a = [ 1, 3, 5 ];
assert(to!string(a) == "[1, 3, 5]");

// Conversion representing associative array with string
int[string] associativeArray = ["0":1, "1":2];
assert(to!string(associativeArray) == `["0":1, "1":2]` ||
       to!string(associativeArray) == `["1":2, "0":1]`);

// char* to string conversion
assert(to!string(cast(char*) null) == "");
assert(to!string("foo\0".ptr) == "foo");

// Conversion reinterpreting void array to string
auto w = "abcx"w;
const(void)[] b = w;
assert(b.length == 8);

auto c = to!(wchar[])(b);
assert(c == "abcx");

Strings can be converted to enum types. The enum member with the same name as the input string is returned. The comparison is case-sensitive.

A ConvException is thrown if the enum does not have the specified member.

import std.exception : assertThrown;

enum E { a, b, c }
assert(to!E("a") == E.a);
assert(to!E("b") == E.b);
assertThrown!ConvException(to!E("A"));
to
!
(alias) object.string = string
string
;
// A Wayland socket in the environment makes raylib's GLFW prefer it over // the Xvfb display we just pinned, and the capture then lands on the real // compositor (or fails outright).
(local variable) string[string] env
env
.
env.remove
remove
("WAYLAND_DISPLAY");
// The subcommand, the file and the flags are one template because their // ORDER matters: hue takes `view <file> --gui`, and a tool that appended // the file after the flags silently got the help text instead of a window.
(alias) object.string = string
string
[]
(local variable) string[] cmd
cmd
= ["xvfb-run", "-n",
(parameter) const(gui_ab.Params) p
p
.
(field) int gui_ab.Params.display
display
.
string std.conv.to!string.to!(const(int))(const(int) __param_0) pure nothrow @safe

The to template converts a value from one type to another. The source type is deduced and the target type must be specified, for example the expression to`!int(42.0)` converts the number 42 from `double` to `int`. The conversion is "safe", i.e., it checks for overflow; to!int(4.2e10) would throw the ConvOverflowException exception. Overflow checks are only inserted when necessary, e.g., ``to!double(42) does not do any checking because any int fits in a double.

Conversions from string to numeric types differ from the C equivalents atoi() and atol() by checking for overflow and not allowing whitespace.

For conversion of strings to signed types, the grammar recognized is: Integer: Sign UnsignedInteger UnsignedInteger Sign: + -

For conversion to unsigned types, the grammar recognized is: UnsignedInteger: DecimalDigit DecimalDigit UnsignedInteger

Examples

Converting a value to its own type (useful mostly for generic code) simply returns its argument.

int a = 42;
int b = to!int(a);
double c = to!double(3.14); // c is double with value 3.14

Converting among numeric types is a safe way to cast them around.

Conversions from floating-point types to integral types allow loss of precision (the fractional part of a floating-point number). The conversion is truncating towards zero, the same way a cast would truncate. (To round a floating point value when casting to an integral, use roundTo.)

import std.exception : assertThrown;

int a = 420;
assert(to!long(a) == a);
assertThrown!ConvOverflowException(to!byte(a));

assert(to!int(4.2e6) == 4200000);
assertThrown!ConvOverflowException(to!uint(-3.14));
assert(to!uint(3.14) == 3);
assert(to!uint(3.99) == 3);
assert(to!int(-3.99) == -3);

When converting strings to numeric types, note that D hexadecimal and binary literals are not handled. Neither the prefixes that indicate the base, nor the horizontal bar used to separate groups of digits are recognized. This also applies to the suffixes that indicate the type.

To work around this, you can specify a radix for conversions involving numbers.

auto str = to!string(42, 16);
assert(str == "2A");
auto i = to!int(str, 16);
assert(i == 42);

Conversions from integral types to floating-point types always succeed, but might lose accuracy. The largest integers with a predecessor representable in floating-point format are 2^24-1 for float, 2^53-1 for double, and 2^64-1 for real (when real is 80-bit, e.g. on Intel machines).

// 2^24 - 1, largest proper integer representable as float
int a = 16_777_215;
assert(to!int(to!float(a)) == a);
assert(to!int(to!float(-a)) == -a);

Conversion from string types to char types enforces the input to consist of a single code point, and said code point must fit in the target type. Otherwise, ConvException is thrown.

import std.exception : assertThrown;

assert(to!char("a") == 'a');
assertThrown(to!char("ñ")); // 'ñ' does not fit into a char
assert(to!wchar("ñ") == 'ñ');
assertThrown(to!wchar("😃")); // '😃' does not fit into a wchar
assert(to!dchar("😃") == '😃');

// Using wstring or dstring as source type does not affect the result
assert(to!char("a"w) == 'a');
assert(to!char("a"d) == 'a');

// Two code points cannot be converted to a single one
assertThrown(to!char("ab"));

Converting an array to another array type works by converting each element in turn. Associative arrays can be converted to associative arrays as long as keys and values can in turn be converted.

import std.string : split;

int[] a = [1, 2, 3];
auto b = to!(float[])(a);
assert(b == [1.0f, 2, 3]);
string str = "1 2 3 4 5 6";
auto numbers = to!(double[])(split(str));
assert(numbers == [1.0, 2, 3, 4, 5, 6]);
int[string] c;
c["a"] = 1;
c["b"] = 2;
auto d = to!(double[wstring])(c);
assert(d["a"w] == 1 && d["b"w] == 2);

Conversions operate transitively, meaning that they work on arrays and associative arrays of any complexity.

This conversion works because to`!short` applies to an `int`, to!wstring applies to a string, to`!string` applies to a `double`, and to!(double[]) applies to an int[]. The conversion might throw an exception because ``to!short might fail the range check.

int[string][double[int[]]] a;
auto b = to!(short[wstring][string[double[]]])(a);

Object-to-object conversions by dynamic casting throw exception when the source is non-null and the target is null.

import std.exception : assertThrown;
// Testing object conversions
class A {}
class B : A {}
class C : A {}
A a1 = new A, a2 = new B, a3 = new C;
assert(to!B(a2) is a2);
assert(to!C(a3) is a3);
assertThrown!ConvException(to!B(a3));

Stringize conversion from all types is supported.

  • String to string conversion works for any two string types having (char, wchar, dchar) character widths and any combination of qualifiers (mutable, const, or immutable).

  • Converts array (other than strings) to string. Each element is converted by calling ``to!T.

  • Associative array to string conversion. Each element is converted by calling ``to!T.

  • Object to string conversion calls toString against the object or returns "null" if the object is null.

  • Struct to string conversion calls toString against the struct if it is defined.

  • For structs that do not define toString, the conversion to string produces the list of fields.

  • Enumerated types are converted to strings as their symbolic names.

  • Boolean values are converted to "true" or "false".

  • char, wchar, dchar to a string type.

  • Unsigned or signed integers to strings.

    [special case]

    : Convert integral value to string in radix radix. radix must be a value from 2 to 36. value is treated as a signed value only if radix is 10. The characters A through Z are used to represent values 10 through 36 and their case is determined by the letterCase parameter.

  • All floating point types to all string types.

  • Pointer to string conversions convert the pointer to a size_t value. If pointer is char*, treat it as C-style strings. In that case, this function is @system.

See formatValue on how toString should be defined.

// Conversion representing dynamic/static array with string
long[] a = [ 1, 3, 5 ];
assert(to!string(a) == "[1, 3, 5]");

// Conversion representing associative array with string
int[string] associativeArray = ["0":1, "1":2];
assert(to!string(associativeArray) == `["0":1, "1":2]` ||
       to!string(associativeArray) == `["1":2, "0":1]`);

// char* to string conversion
assert(to!string(cast(char*) null) == "");
assert(to!string("foo\0".ptr) == "foo");

// Conversion reinterpreting void array to string
auto w = "abcx"w;
const(void)[] b = w;
assert(b.length == 8);

auto c = to!(wchar[])(b);
assert(c == "abcx");

Strings can be converted to enum types. The enum member with the same name as the input string is returned. The comparison is case-sensitive.

A ConvException is thrown if the enum does not have the specified member.

import std.exception : assertThrown;

enum E { a, b, c }
assert(to!E("a") == E.a);
assert(to!E("b") == E.b);
assertThrown!ConvException(to!E("A"));
to
!
(alias) object.string = string
string
,
"-s", "-screen 0 " ~
(parameter) const(gui_ab.Params) p
p
.
(field) string gui_ab.Params.screen
screen
,
(parameter) string bin
bin
.
string std.path.absolutePath(return scope const(string) path, lazy string base = getcwd()) pure @safe

Transforms path into an absolute path.

The following algorithm is used:

  1. If path is empty, return null.

  2. If path is already absolute, return it.

  3. Otherwise, append path to base and return the result. If base is not specified, the current working directory is used.

The function allocates memory if and only if it gets to the third stage of this algorithm.

Note that absolutePath will not normalize .. segments. Use buildNormalizedPath(absolutePath(path)) if that is desired.

Examples

version (Posix)
{
    assert(absolutePath("some/file", "/foo/bar")  == "/foo/bar/some/file");
    assert(absolutePath("../file", "/foo/bar")    == "/foo/bar/../file");
    assert(absolutePath("/some/file", "/foo/bar") == "/some/file");
}

version (Windows)
{
    assert(absolutePath(`some\file`, `c:\foo\bar`)    == `c:\foo\bar\some\file`);
    assert(absolutePath(`..\file`, `c:\foo\bar`)      == `c:\foo\bar\..\file`);
    assert(absolutePath(`c:\some\file`, `c:\foo\bar`) == `c:\some\file`);
    assert(absolutePath(`\`, `c:\`)                   == `c:\`);
    assert(absolutePath(`\some\file`, `c:\foo\bar`)   == `c:\some\file`);
}
@parampath the relative path to transform@parambase the base directory of the relative path@returnsstring of transformed path@throwsException if the specified base directory is not absolute.@seeasAbsolutePath which does not allocate
absolutePath
];
foreach (
(parameter) string a
a
;
(parameter) const(gui_ab.Params) p
p
.
(field) string gui_ab.Params.extraArgs
extraArgs
.
string[] gui_ab.splitArgs(string s)

Splits --args on spaces, dropping empties.

splitArgs
)
(local variable) string[] cmd
cmd
~=
(local variable) string a
a
== "{file}" ?
(parameter) const(gui_ab.Params) p
p
.
(field) string gui_ab.Params.file
file
.
string std.path.absolutePath(return scope const(string) path, lazy string base = getcwd()) pure @safe

Transforms path into an absolute path.

The following algorithm is used:

  1. If path is empty, return null.

  2. If path is already absolute, return it.

  3. Otherwise, append path to base and return the result. If base is not specified, the current working directory is used.

The function allocates memory if and only if it gets to the third stage of this algorithm.

Note that absolutePath will not normalize .. segments. Use buildNormalizedPath(absolutePath(path)) if that is desired.

Examples

version (Posix)
{
    assert(absolutePath("some/file", "/foo/bar")  == "/foo/bar/some/file");
    assert(absolutePath("../file", "/foo/bar")    == "/foo/bar/../file");
    assert(absolutePath("/some/file", "/foo/bar") == "/some/file");
}

version (Windows)
{
    assert(absolutePath(`some\file`, `c:\foo\bar`)    == `c:\foo\bar\some\file`);
    assert(absolutePath(`..\file`, `c:\foo\bar`)      == `c:\foo\bar\..\file`);
    assert(absolutePath(`c:\some\file`, `c:\foo\bar`) == `c:\some\file`);
    assert(absolutePath(`\`, `c:\`)                   == `c:\`);
    assert(absolutePath(`\some\file`, `c:\foo\bar`)   == `c:\some\file`);
}
@parampath the relative path to transform@parambase the base directory of the relative path@returnsstring of transformed path@throwsException if the specified base directory is not absolute.@seeasAbsolutePath which does not allocate
absolutePath
:
(local variable) string a
a
;
auto
(local variable) std.process.Pid pid
pid
=
std.process.Pid std.process.spawnProcess(scope const(char[])[] args, const(string[string]) env, std.process.Config config = Config(Flags.none, null, null), scope const(char)[] workDir = null) @trusted
spawnProcess
(
(local variable) string[] cmd
cmd
, env:
(local variable) string[string] env
env
, config:
(struct) std.process.Config

Options that control the behaviour of process creation functions in this module. Most options only apply to spawnProcess and spawnShell.

Example

auto logFile = File("myapp_error.log", "w");

// Start program, suppressing the console window (Windows only),
// redirect its error stream to logFile, and leave logFile open
// in the parent process as well.
auto pid = spawnProcess("myapp", stdin, stdout, logFile,
                        Config.retainStderr | Config.suppressConsole);
scope(exit)
{
    auto exitCode = wait(pid);
    logFile.writeln("myapp exited with code ", exitCode);
    logFile.close();
}
Config
.
(constant) std.process.Config std.process.Config.none = Config(Flags.none, null, null)

For backwards compatibility, and cases when only flags need to be specified in the Config, these allow building Config instances using flag names only.

none
,
workDir:
(parameter) const(gui_ab.Params) p
p
.
(field) string gui_ab.Params.outDir
outDir
);
const
(local variable) const(int) rc
rc
=
(local variable) std.process.Pid pid
pid
.
int std.process.wait(std.process.Pid pid) @safe

Waits for the process associated with pid to terminate, and returns its exit status.

In general one should always wait for child processes to terminate before exiting the parent process unless the process was spawned as detached (that was spawned with Config.detached flag). Otherwise, they may become "zombies" – processes that are defunct, yet still occupy a slot in the OS process table. You should not and must not wait for detached processes, since you don't own them.

If the process has already terminated, this function returns directly. The exit code is cached, so that if wait() is called multiple times on the same Pid it will always return the same value.

POSIX specific

If the process is terminated by a signal, this function returns a negative number whose absolute value is the signal number. Since POSIX restricts normal exit codes to the range 0-255, a negative return value will always indicate termination by signal. Signal codes are defined in the core.sys.posix.signal module (which corresponds to the signal.h POSIX header).

Example

See the spawnProcess documentation.

@throwsProcessException on failure or on attempt to wait for detached process.@seetryWait, for a non-blocking function.
wait
;
if (!
(local variable) const(string) full
full
.
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
)
{ stderr.
std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @system
writefln
("gui-ab: %s produced no screenshot (exit %s). Is this "
~ "a GUI-enabled build? `dub build :hue` (not --config=no-gui).",
(parameter) string side
side
,
(local variable) const(int) rc
rc
);
return false; }
(parameter) ubyte[] bytes
bytes
= cast(ubyte[])
void[] std.file.read!string(string name, ulong upTo = 18446744073709551615LU) @safe

Read entire contents of file name and returns it as an untyped array. If the file size is larger than upTo, only upTo bytes are read.

Examples

import std.utf : byChar;
scope(exit)
{
    assert(exists(deleteme));
    remove(deleteme);
}

std.file.write(deleteme, "1234"); // deleteme is the name of a temporary file
assert(read(deleteme, 2) == "12");
assert(read(deleteme.byChar) == "1234");
assert((cast(const(ubyte)[])read(deleteme)).length == 4);
@paramname string or range of characters representing the file name@paramupTo if present, the maximum number of bytes to read@returnsUntyped array of bytes read.@throwsFileException on error.@seereadText for reading and validating a text file.
read
(
(local variable) const(string) full
full
);
return true; } /// Splits `--args` on spaces, dropping empties. private
(alias) object.string = string
string
[]
string[] gui_ab.splitArgs(string s)

Splits --args on spaces, dropping empties.

splitArgs
(
(alias) object.string = string
string
(parameter) string s
s
)
{ import
(package) std
std
.
(module) std.algorithm

This package implements generic algorithms oriented towards the processing of sequences. Sequences processed by these functions define range-based interfaces. See also Reference on ranges and tutorial on ranges.

Algorithms are categorized into the following submodules:

Submodule Functions

| Searching | all any balancedParens boyerMooreFinder canFind commonPrefix count countUntil endsWith find findAdjacent findAmong findSkip findSplit findSplitAfter findSplitBefore minCount maxCount minElement maxElement minIndex maxIndex minPos maxPos skipOver startsWith until |

| Comparison | among castSwitch clamp cmp either equal isPermutation isSameLength levenshteinDistance levenshteinDistanceAndPath max min mismatch predSwitch |

| Iteration | cache cacheBidirectional chunkBy cumulativeFold each filter filterBidirectional fold group joiner map mean permutations reduce splitWhen splitter substitute sum uniq |

| Sorting | completeSort isPartitioned isSorted isStrictlyMonotonic ordered strictlyOrdered makeIndex merge multiSort nextEvenPermutation nextPermutation nthPermutation partialSort partition partition3 schwartzSort sort topN topNCopy topNIndex |

| Set operations (setops) | cartesianProduct largestPartialIntersection largestPartialIntersectionWeighted multiwayMerge multiwayUnion setDifference setIntersection setSymmetricDifference |

| Mutation | bringToFront copy fill initializeAll move moveAll moveSome moveEmplace moveEmplaceAll moveEmplaceSome remove reverse strip stripLeft stripRight swap swapRanges uninitializedFill |

Many functions in this package are parameterized with a predicate. The predicate may be any suitable callable type (a function, a delegate, a functor, or a lambda), or a compile-time string. The string may consist of any legal D expression that uses the symbol a (for unary functions) or the symbols a and b (for binary functions). These names will NOT interfere with other homonym symbols in user code because they are evaluated in a different context. The default for all binary comparison predicates is "a == b" for unordered operations and "a < b" for ordered operations.

Example

int[] a = ...;
static bool greater(int a, int b)
{
    return a > b;
}
sort!greater(a);           // predicate as alias
sort!((a, b) => a > b)(a); // predicate as a lambda.
sort!"a > b"(a);           // predicate as string
                           // (no ambiguity with array name)
sort(a);                   // no predicate, "a < b" is implicit

Source

std/algorithm/package.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
algorithm
:
(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
,
(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.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) string s
s
.
std.algorithm.iteration.splitter!("a == b", Flag.no, string, char).Result std.algorithm.iteration.splitter!("a == b", Flag.no, string, char)(string r, char s) pure nothrow @nogc @safe

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

Constraints

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

Examples

Basic splitting with characters and numbers.

import std.algorithm.comparison : equal;

assert("a|bc|def".splitter('|').equal([ "a", "bc", "def" ]));

int[] a = [1, 0, 2, 3, 0, 4, 5, 6];
int[][] w = [ [1], [2, 3], [4, 5, 6] ];
assert(a.splitter(0).equal(w));

Basic splitting with characters and numbers and keeping sentinels.

import std.algorithm.comparison : equal;
import std.typecons : Yes;

assert("a|bc|def".splitter!("a == b", Yes.keepSeparators)('|')
    .equal([ "a", "|", "bc", "|", "def" ]));

int[] a = [1, 0, 2, 3, 0, 4, 5, 6];
int[][] w = [ [1], [0], [2, 3], [0], [4, 5, 6] ];
assert(a.splitter!("a == b", Yes.keepSeparators)(0).equal(w));

Adjacent separators.

import std.algorithm.comparison : equal;

assert("|ab|".splitter('|').equal([ "", "ab", "" ]));
assert("ab".splitter('|').equal([ "ab" ]));

assert("a|b||c".splitter('|').equal([ "a", "b", "", "c" ]));
assert("hello  world".splitter(' ').equal([ "hello", "", "world" ]));

auto a = [ 1, 2, 0, 0, 3, 0, 4, 5, 0 ];
auto w = [ [1, 2], [], [3], [4, 5], [] ];
assert(a.splitter(0).equal(w));

Adjacent separators and keeping sentinels.

import std.algorithm.comparison : equal;
import std.typecons : Yes;

assert("|ab|".splitter!("a == b", Yes.keepSeparators)('|')
    .equal([ "", "|", "ab", "|", "" ]));
assert("ab".splitter!("a == b", Yes.keepSeparators)('|')
    .equal([ "ab" ]));

assert("a|b||c".splitter!("a == b", Yes.keepSeparators)('|')
    .equal([ "a", "|", "b", "|", "", "|", "c" ]));
assert("hello  world".splitter!("a == b", Yes.keepSeparators)(' ')
    .equal([ "hello", " ", "", " ", "world" ]));

auto a = [ 1, 2, 0, 0, 3, 0, 4, 5, 0 ];
auto w = [ [1, 2], [0], [], [0], [3], [0], [4, 5], [0], [] ];
assert(a.splitter!("a == b", Yes.keepSeparators)(0).equal(w));

Empty and separator-only ranges.

import std.algorithm.comparison : equal;
import std.range : empty;

assert("".splitter('|').empty);
assert("|".splitter('|').equal([ "", "" ]));
assert("||".splitter('|').equal([ "", "", "" ]));

Empty and separator-only ranges and keeping sentinels.

import std.algorithm.comparison : equal;
import std.typecons : Yes;
import std.range : empty;

assert("".splitter!("a == b", Yes.keepSeparators)('|').empty);
assert("|".splitter!("a == b", Yes.keepSeparators)('|')
    .equal([ "", "|", "" ]));
assert("||".splitter!("a == b", Yes.keepSeparators)('|')
    .equal([ "", "|", "", "|", "" ]));

Use a range for splitting

import std.algorithm.comparison : equal;

assert("a=>bc=>def".splitter("=>").equal([ "a", "bc", "def" ]));
assert("a|b||c".splitter("||").equal([ "a|b", "c" ]));
assert("hello  world".splitter("  ").equal([ "hello", "world" ]));

int[] a = [ 1, 2, 0, 0, 3, 0, 4, 5, 0 ];
int[][] w = [ [1, 2], [3, 0, 4, 5, 0] ];
assert(a.splitter([0, 0]).equal(w));

a = [ 0, 0 ];
assert(a.splitter([0, 0]).equal([ (int[]).init, (int[]).init ]));

a = [ 0, 0, 1 ];
assert(a.splitter([0, 0]).equal([ [], [1] ]));

Use a range for splitting

import std.algorithm.comparison : equal;
import std.typecons : Yes;

assert("a=>bc=>def".splitter!("a == b", Yes.keepSeparators)("=>")
    .equal([ "a", "=>", "bc", "=>", "def" ]));
assert("a|b||c".splitter!("a == b", Yes.keepSeparators)("||")
    .equal([ "a|b", "||", "c" ]));
assert("hello  world".splitter!("a == b", Yes.keepSeparators)("  ")
    .equal([ "hello", "  ",  "world" ]));

int[] a = [ 1, 2, 0, 0, 3, 0, 4, 5, 0 ];
int[][] w = [ [1, 2], [0, 0], [3, 0, 4, 5, 0] ];
assert(a.splitter!("a == b", Yes.keepSeparators)([0, 0]).equal(w));

a = [ 0, 0 ];
assert(a.splitter!("a == b", Yes.keepSeparators)([0, 0])
    .equal([ (int[]).init, [0, 0], (int[]).init ]));

a = [ 0, 0, 1 ];
assert(a.splitter!("a == b", Yes.keepSeparators)([0, 0])
    .equal([ [], [0, 0], [1] ]));

Custom predicate functions.

import std.algorithm.comparison : equal;
import std.ascii : toLower;

assert("abXcdxef".splitter!"a.toLower == b"('x').equal(
             [ "ab", "cd", "ef" ]));

auto w = [ [0], [1], [2] ];
assert(w.splitter!"a.front == b"(1).equal([ [[0]], [[2]] ]));

Custom predicate functions.

import std.algorithm.comparison : equal;
import std.typecons : Yes;
import std.ascii : toLower;

assert("abXcdxef".splitter!("a.toLower == b", Yes.keepSeparators)('x')
    .equal([ "ab", "X", "cd", "x", "ef" ]));

auto w = [ [0], [1], [2] ];
assert(w.splitter!("a.front == b", Yes.keepSeparators)(1)
    .equal([ [[0]], [[1]], [[2]] ]));

Leading separators, trailing separators, or no separators.

import std.algorithm.comparison : equal;

assert("|ab|".splitter('|').equal([ "", "ab", "" ]));
assert("ab".splitter('|').equal([ "ab" ]));

Leading separators, trailing separators, or no separators.

import std.algorithm.comparison : equal;
import std.typecons : Yes;

assert("|ab|".splitter!("a == b", Yes.keepSeparators)('|')
    .equal([ "", "|", "ab", "|", "" ]));
assert("ab".splitter!("a == b", Yes.keepSeparators)('|')
    .equal([ "ab" ]));

Splitter returns bidirectional ranges if the delimiter is a single element

import std.algorithm.comparison : equal;
import std.range : retro;
assert("a|bc|def".splitter('|').retro.equal([ "def", "bc", "a" ]));

Splitter returns bidirectional ranges if the delimiter is a single element

import std.algorithm.comparison : equal;
import std.typecons : Yes;
import std.range : retro;
assert("a|bc|def".splitter!("a == b", Yes.keepSeparators)('|')
    .retro.equal([ "def", "|", "bc", "|", "a" ]));
@parampred The predicate for comparing each element with the separator, defaulting to "a == b".@paramr The input range to be split. Must support slicing and .length or be a narrow string type.@params The element (or range) to be treated as the separator between range segments to be split.@paramkeepSeparators The flag for deciding if the separators are kept@returns

An input range of the subranges of elements between separators. If r is a forward range or bidirectional range, 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
  • splitter for a version that splits using a regular expression defined separator.

  • split for a version that splits eagerly.

  • splitWhen, which compares adjacent elements instead of element against separator.

splitter
(' ').
gui_ab.splitArgs.FilterResult!(__lambda_L350_C36, Result) gui_ab.splitArgs.filter!(std.algorithm.iteration.splitter!("a == b", Flag.no, string, char).Result)(std.algorithm.iteration.splitter!("a == b", Flag.no, string, char).Result 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
!(a => a.length != 0).
string[] std.array.array!(gui_ab.splitArgs.FilterResult!(__lambda_L350_C36, Result))(gui_ab.splitArgs.FilterResult!(__lambda_L350_C36, Result) 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
;
} private bool
bool gui_ab.onPath(string tool)
onPath
(
(alias) object.string = string
string
(parameter) string tool
tool
)
{ import
(package) std
std
.
(module) std.algorithm

This package implements generic algorithms oriented towards the processing of sequences. Sequences processed by these functions define range-based interfaces. See also Reference on ranges and tutorial on ranges.

Algorithms are categorized into the following submodules:

Submodule Functions

| Searching | all any balancedParens boyerMooreFinder canFind commonPrefix count countUntil endsWith find findAdjacent findAmong findSkip findSplit findSplitAfter findSplitBefore minCount maxCount minElement maxElement minIndex maxIndex minPos maxPos skipOver startsWith until |

| Comparison | among castSwitch clamp cmp either equal isPermutation isSameLength levenshteinDistance levenshteinDistanceAndPath max min mismatch predSwitch |

| Iteration | cache cacheBidirectional chunkBy cumulativeFold each filter filterBidirectional fold group joiner map mean permutations reduce splitWhen splitter substitute sum uniq |

| Sorting | completeSort isPartitioned isSorted isStrictlyMonotonic ordered strictlyOrdered makeIndex merge multiSort nextEvenPermutation nextPermutation nthPermutation partialSort partition partition3 schwartzSort sort topN topNCopy topNIndex |

| Set operations (setops) | cartesianProduct largestPartialIntersection largestPartialIntersectionWeighted multiwayMerge multiwayUnion setDifference setIntersection setSymmetricDifference |

| Mutation | bringToFront copy fill initializeAll move moveAll moveSome moveEmplace moveEmplaceAll moveEmplaceSome remove reverse strip stripLeft stripRight swap swapRanges uninitializedFill |

Many functions in this package are parameterized with a predicate. The predicate may be any suitable callable type (a function, a delegate, a functor, or a lambda), or a compile-time string. The string may consist of any legal D expression that uses the symbol a (for unary functions) or the symbols a and b (for binary functions). These names will NOT interfere with other homonym symbols in user code because they are evaluated in a different context. The default for all binary comparison predicates is "a == b" for unordered operations and "a < b" for ordered operations.

Example

int[] a = ...;
static bool greater(int a, int b)
{
    return a > b;
}
sort!greater(a);           // predicate as alias
sort!((a, b) => a > b)(a); // predicate as a lambda.
sort!"a > b"(a);           // predicate as string
                           // (no ambiguity with array name)
sort(a);                   // no predicate, "a < b" is implicit

Source

std/algorithm/package.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
algorithm
:
(alias template) any = std.algorithm.searching.any(alias pred = "a")

Checks if $(I _any) of the elements satisfies `pred`. `!any` can be used to verify that $(I none) of the elements satisfy pred. This is sometimes called exists in other languages.

any
;
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) split = std.array.split(S)(S s) if (isSomeString!S)

Eagerly splits range into an array, using sep as the delimiter.

When no delimiter is provided, strings are split into an array of words, using whitespace as delimiter. Runs of whitespace are merged together (no empty words are produced).

The range must be a $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives). The separator can be a value of the same type as the elements in range or it can be another forward range.

Params: s = the string to split by word if no separator is given range = the range to split sep = a value of the same type as the elements of range or another isTerminator = a predicate that splits the range when it returns true.

Returns: An array containing the divided parts of range (or the words of s).

See_Also: $(REF splitter, std,algorithm,iteration) for a lazy version without allocating memory.

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

split
;
auto
(local variable) string path
path
=
(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", "");
return
(local variable) string path
path
.
string[] std.array.split!(string, char)(string range, char sep) pure @safe
split
(':').
bool gui_ab.onPath.any!(string[])(string[] range) nothrow @safe

Checks if any of the elements satisfies pred. !any`` can be used to verify that none of the elements satisfy pred. This is sometimes called exists in other languages.

Returns true if and only if the input range range is non-empty and any value found in range satisfies the predicate pred. Performs (at most) O(range.length) evaluations of pred.

Examples

import std.ascii : isWhite;
assert( all!(any!isWhite)(["a a", "b b"]));
assert(!any!(all!isWhite)(["a a", "b b"]));

any can also be used without a predicate, if its items can be evaluated to true or false in a conditional statement. !any`` can be a convenient way to quickly test that none of the elements of a range evaluate to true.

int[3] vals1 = [0, 0, 0];
assert(!any(vals1[])); //none of vals1 evaluate to true

int[3] vals2 = [2, 0, 2];
assert( any(vals2[]));
assert(!all(vals2[]));

int[3] vals3 = [3, 3, 3];
assert( any(vals3[]));
assert( all(vals3[]));
any
!(dir => buildPath(dir, tool).exists);
} private
(alias) object.string = string
string
string gui_ab.digest(in ubyte[] bytes)
digest
(in ubyte[]
(parameter) const(ubyte[]) bytes
bytes
)
=>
ubyte[16] std.digest.md.md5Of!(const(ubyte)[])(const(ubyte)[] __param_0) pure nothrow @nogc @safe

This is a convenience alias for digest using the MD5 implementation.

Examples

ubyte[16] hash = md5Of("abc");
assert(hash == digest!MD5("abc"));
md5Of
(
(parameter) const(ubyte[]) bytes
bytes
).
char[32] std.digest.toHexString!(Order.increasing, 16LU, LetterCase.upper)(const(ubyte[16]) digest) pure nothrow @nogc @safe

Used to convert a hash value (a static or dynamic array of ubytes) to a string. Can be used with the OOP and with the template API.

The additional order parameter can be used to specify the order of the input data. By default the data is processed in increasing order, starting at index 0. To process it in the opposite order, pass Order.decreasing as a parameter.

The additional letterCase parameter can be used to specify the case of the output data. By default the output is in upper case. To change it to the lower case pass LetterCase.lower as a parameter.

Note

The function overloads returning a string allocate their return values using the GC. The versions returning static arrays use pass-by-value for the return value, effectively avoiding dynamic allocation.

toHexString
()[0 .. 12].
string object.idup!char(char[] a) pure nothrow @property @safe

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

idup
;